|
| 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 | +// Example function to show a result to the user. Your site's UI library can be used instead. |
| 107 | +function resultMessage(message) { |
| 108 | + const container = document.querySelector("#result-message"); |
| 109 | + container.innerHTML = message; |
| 110 | +} |
| 111 | + |
| 112 | +// If this returns false or the card fields aren't visible, see Step #1. |
| 113 | +if (window.paypal.HostedFields.isEligible()) { |
| 114 | + // Renders card fields |
| 115 | + window.paypal.HostedFields.render({ |
| 116 | + // Call your server to set up the transaction |
| 117 | + createOrder: createOrderCallback, |
| 118 | + styles: { |
| 119 | + ".valid": { |
| 120 | + color: "green", |
| 121 | + }, |
| 122 | + ".invalid": { |
| 123 | + color: "red", |
| 124 | + }, |
| 125 | + }, |
| 126 | + fields: { |
| 127 | + number: { |
| 128 | + selector: "#card-number", |
| 129 | + placeholder: "4111 1111 1111 1111", |
| 130 | + }, |
| 131 | + cvv: { |
| 132 | + selector: "#cvv", |
| 133 | + placeholder: "123", |
| 134 | + }, |
| 135 | + expirationDate: { |
| 136 | + selector: "#expiration-date", |
| 137 | + placeholder: "MM/YY", |
| 138 | + }, |
| 139 | + }, |
| 140 | + }).then((cardFields) => { |
| 141 | + document.querySelector("#card-form").addEventListener("submit", (event) => { |
| 142 | + event.preventDefault(); |
| 143 | + cardFields |
| 144 | + .submit({ |
| 145 | + // Cardholder's first and last name |
| 146 | + cardholderName: document.getElementById("card-holder-name").value, |
| 147 | + // Billing Address |
| 148 | + billingAddress: { |
| 149 | + // Street address, line 1 |
| 150 | + streetAddress: document.getElementById( |
| 151 | + "card-billing-address-street", |
| 152 | + ).value, |
| 153 | + // Street address, line 2 (Ex: Unit, Apartment, etc.) |
| 154 | + extendedAddress: document.getElementById( |
| 155 | + "card-billing-address-unit", |
| 156 | + ).value, |
| 157 | + // State |
| 158 | + region: document.getElementById("card-billing-address-state").value, |
| 159 | + // City |
| 160 | + locality: document.getElementById("card-billing-address-city") |
| 161 | + .value, |
| 162 | + // Postal Code |
| 163 | + postalCode: document.getElementById("card-billing-address-zip") |
| 164 | + .value, |
| 165 | + // Country Code |
| 166 | + countryCodeAlpha2: document.getElementById( |
| 167 | + "card-billing-address-country", |
| 168 | + ).value, |
| 169 | + }, |
| 170 | + }) |
| 171 | + .then((data) => { |
| 172 | + return onApproveCallback(data); |
| 173 | + }) |
| 174 | + .catch((orderData) => { |
| 175 | + resultMessage( |
| 176 | + `Sorry, your transaction could not be processed...<br><br>${JSON.stringify( |
| 177 | + orderData, |
| 178 | + )}`, |
| 179 | + ); |
| 180 | + }); |
| 181 | + }); |
| 182 | + }); |
| 183 | +} else { |
| 184 | + // Hides card fields if the merchant isn't eligible |
| 185 | + document.querySelector("#card-form").style = "display: none"; |
| 186 | +} |
0 commit comments