|
| 1 | +async function createOrderCallback() { |
| 2 | + try { |
| 3 | + const response = await fetch("/api/orders", { |
| 4 | + method: "POST", |
| 5 | + headers: { |
| 6 | + "Content-Type": "application/json", |
| 7 | + }, |
| 8 | + // use the "body" param to optionally pass additional order information |
| 9 | + // like product ids and quantities |
| 10 | + body: JSON.stringify({ |
| 11 | + cart: [ |
| 12 | + { |
| 13 | + id: "YOUR_PRODUCT_ID", |
| 14 | + quantity: "YOUR_PRODUCT_QUANTITY", |
| 15 | + }, |
| 16 | + ], |
| 17 | + }), |
| 18 | + }); |
| 19 | + |
| 20 | + const orderData = await response.json(); |
| 21 | + |
| 22 | + if (orderData.id) { |
| 23 | + return orderData.id; |
| 24 | + } else { |
| 25 | + const errorDetail = orderData?.details?.[0]; |
| 26 | + const errorMessage = errorDetail |
| 27 | + ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})` |
| 28 | + : JSON.stringify(orderData); |
| 29 | + |
| 30 | + throw new Error(errorMessage); |
| 31 | + } |
| 32 | + } catch (error) { |
| 33 | + console.error(error); |
| 34 | + resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +async function onApproveCallback(data, actions) { |
| 39 | + try { |
| 40 | + const response = await fetch(`/api/orders/${data.orderID}/capture`, { |
| 41 | + method: "POST", |
| 42 | + headers: { |
| 43 | + "Content-Type": "application/json", |
| 44 | + }, |
| 45 | + }); |
| 46 | + |
| 47 | + const orderData = await response.json(); |
| 48 | + // Three cases to handle: |
| 49 | + // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() |
| 50 | + // (2) Other non-recoverable errors -> Show a failure message |
| 51 | + // (3) Successful transaction -> Show confirmation or thank you message |
| 52 | + |
| 53 | + const transaction = |
| 54 | + orderData?.purchase_units?.[0]?.payments?.captures?.[0] || |
| 55 | + orderData?.purchase_units?.[0]?.payments?.authorizations?.[0]; |
| 56 | + const errorDetail = orderData?.details?.[0]; |
| 57 | + |
| 58 | + // this actions.restart() behavior only applies to the Buttons component |
| 59 | + if (errorDetail?.issue === "INSTRUMENT_DECLINED" && !data.card && actions) { |
| 60 | + // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() |
| 61 | + // recoverable state, per https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/ |
| 62 | + return actions.restart(); |
| 63 | + } else if ( |
| 64 | + errorDetail || |
| 65 | + !transaction || |
| 66 | + transaction.status === "DECLINED" |
| 67 | + ) { |
| 68 | + // (2) Other non-recoverable errors -> Show a failure message |
| 69 | + let errorMessage; |
| 70 | + if (transaction) { |
| 71 | + errorMessage = `Transaction ${transaction.status}: ${transaction.id}`; |
| 72 | + } else if (errorDetail) { |
| 73 | + errorMessage = `${errorDetail.description} (${orderData.debug_id})`; |
| 74 | + } else { |
| 75 | + errorMessage = JSON.stringify(orderData); |
| 76 | + } |
| 77 | + |
| 78 | + throw new Error(errorMessage); |
| 79 | + } else { |
| 80 | + // (3) Successful transaction -> Show confirmation or thank you message |
| 81 | + // Or go to another URL: actions.redirect('thank_you.html'); |
| 82 | + resultMessage( |
| 83 | + `Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`, |
| 84 | + ); |
| 85 | + console.log( |
| 86 | + "Capture result", |
| 87 | + orderData, |
| 88 | + JSON.stringify(orderData, null, 2), |
| 89 | + ); |
| 90 | + } |
| 91 | + } catch (error) { |
| 92 | + console.error(error); |
| 93 | + resultMessage( |
| 94 | + `Sorry, your transaction could not be processed...<br><br>${error}`, |
| 95 | + ); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +window.paypal |
| 100 | + .Buttons({ |
| 101 | + createOrder: createOrderCallback, |
| 102 | + onApprove: onApproveCallback, |
| 103 | + }) |
| 104 | + .render("#paypal-button-container"); |
| 105 | + |
| 106 | +const cardField = window.paypal.CardFields({ |
| 107 | + createOrder: createOrderCallback, |
| 108 | + onApprove: onApproveCallback, |
| 109 | +}); |
| 110 | + |
| 111 | +// Render each field after checking for eligibility |
| 112 | +if (cardField.isEligible()) { |
| 113 | + const nameField = cardField.NameField(); |
| 114 | + nameField.render("#card-name-field-container"); |
| 115 | + |
| 116 | + const numberField = cardField.NumberField(); |
| 117 | + numberField.render("#card-number-field-container"); |
| 118 | + |
| 119 | + const cvvField = cardField.CVVField(); |
| 120 | + cvvField.render("#card-cvv-field-container"); |
| 121 | + |
| 122 | + const expiryField = cardField.ExpiryField(); |
| 123 | + expiryField.render("#card-expiry-field-container"); |
| 124 | + |
| 125 | + // Add click listener to submit button and call the submit function on the CardField component |
| 126 | + document |
| 127 | + .getElementById("multi-card-field-button") |
| 128 | + .addEventListener("click", () => { |
| 129 | + cardField.submit().catch((error) => { |
| 130 | + resultMessage( |
| 131 | + `Sorry, your transaction could not be processed...<br><br>${error}`, |
| 132 | + ); |
| 133 | + }); |
| 134 | + }); |
| 135 | +} else { |
| 136 | + // Hides card fields if the merchant isn't eligible |
| 137 | + document.querySelector("#card-form").style = "display: none"; |
| 138 | +} |
| 139 | + |
| 140 | +// Example function to show a result to the user. Your site's UI library can be used instead. |
| 141 | +function resultMessage(message) { |
| 142 | + const container = document.querySelector("#result-message"); |
| 143 | + container.innerHTML = message; |
| 144 | +} |
0 commit comments