|
| 1 | +async function onPayPalLoaded() { |
| 2 | + try { |
| 3 | + const clientToken = await getBrowserSafeClientToken(); |
| 4 | + const sdkInstance = await window.paypal.createInstance({ |
| 5 | + clientToken, |
| 6 | + components: ["paypal-messages"], |
| 7 | + }); |
| 8 | + const content = await createMessage(sdkInstance); |
| 9 | + addAmountEventListener(content); |
| 10 | + } catch (error) { |
| 11 | + console.error(error); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +async function getBrowserSafeClientToken() { |
| 16 | + const response = await fetch("/paypal-api/auth/browser-safe-client-token", { |
| 17 | + method: "GET", |
| 18 | + headers: { |
| 19 | + "Content-Type": "application/json", |
| 20 | + }, |
| 21 | + }); |
| 22 | + const { accessToken } = await response.json(); |
| 23 | + |
| 24 | + return accessToken; |
| 25 | +} |
| 26 | + |
| 27 | +async function createMessage(sdkInstance) { |
| 28 | + const messagesInstance = sdkInstance.createPayPalMessages({ |
| 29 | + buyerCountry: "US", |
| 30 | + currencyCode: "USD", |
| 31 | + }); |
| 32 | + const messageElement = document.querySelector("#paypal-message"); |
| 33 | + |
| 34 | + const content = await messagesInstance.fetchContent({ |
| 35 | + onReady: (content) => { |
| 36 | + messageElement.setContent(content); |
| 37 | + }, |
| 38 | + }); |
| 39 | + |
| 40 | + return content; |
| 41 | +} |
| 42 | + |
| 43 | +// basic example product interaction |
| 44 | +function addAmountEventListener(content) { |
| 45 | + const quantityInput = document.querySelector("#quantity-input"); |
| 46 | + const totalAmount = document.querySelector("#total-amount"); |
| 47 | + const quantity = document.querySelector("#quantity"); |
| 48 | + |
| 49 | + quantityInput.addEventListener("input", (event) => { |
| 50 | + const quantityValue = event.target.value; |
| 51 | + const calculatedTotalAmount = (50 * quantityValue).toString(); |
| 52 | + |
| 53 | + quantity.innerHTML = quantityValue; |
| 54 | + totalAmount.innerHTML = calculatedTotalAmount; |
| 55 | + |
| 56 | + content.update({ amount: calculatedTotalAmount }); |
| 57 | + }); |
| 58 | +} |
0 commit comments