|
| 1 | +import express from "express"; |
| 2 | +import fetch from "node-fetch"; |
| 3 | +import "dotenv/config"; |
| 4 | + |
| 5 | +const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PORT = 8888 } = process.env; |
| 6 | +const base = "https://api-m.sandbox.paypal.com"; |
| 7 | +const app = express(); |
| 8 | + |
| 9 | +app.set("view engine", "ejs"); |
| 10 | +app.set("views", "./server/views"); |
| 11 | + |
| 12 | +// host static files |
| 13 | +app.use(express.static("client")); |
| 14 | + |
| 15 | +// parse post params sent in body in json format |
| 16 | +app.use(express.json()); |
| 17 | + |
| 18 | +/** |
| 19 | + * Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs. |
| 20 | + * @see https://developer.paypal.com/api/rest/authentication/ |
| 21 | + */ |
| 22 | +const authenticate = async (bodyParams) => { |
| 23 | + const params = { |
| 24 | + grant_type: "client_credentials", |
| 25 | + response_type: "id_token", |
| 26 | + ...bodyParams, |
| 27 | + }; |
| 28 | + |
| 29 | + // pass the url encoded value as the body of the post call |
| 30 | + const urlEncodedParams = new URLSearchParams(params).toString(); |
| 31 | + try { |
| 32 | + if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) { |
| 33 | + throw new Error("MISSING_API_CREDENTIALS"); |
| 34 | + } |
| 35 | + const auth = Buffer.from( |
| 36 | + PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET, |
| 37 | + ).toString("base64"); |
| 38 | + |
| 39 | + const response = await fetch(`${base}/v1/oauth2/token`, { |
| 40 | + method: "POST", |
| 41 | + body: urlEncodedParams, |
| 42 | + headers: { |
| 43 | + Authorization: `Basic ${auth}`, |
| 44 | + }, |
| 45 | + }); |
| 46 | + return handleResponse(response); |
| 47 | + } catch (error) { |
| 48 | + console.error("Failed to generate Access Token:", error); |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +const generateAccessToken = async () => { |
| 53 | + const { jsonResponse } = await authenticate(); |
| 54 | + return jsonResponse.access_token; |
| 55 | +}; |
| 56 | + |
| 57 | +/** |
| 58 | + * Create an order to start the transaction. |
| 59 | + * @see https://developer.paypal.com/docs/api/orders/v2/#orders_create |
| 60 | + */ |
| 61 | +const createOrder = async (cart) => { |
| 62 | + // use the cart information passed from the front-end to calculate the purchase unit details |
| 63 | + console.log( |
| 64 | + "shopping cart information passed from the frontend createOrder() callback:", |
| 65 | + cart, |
| 66 | + ); |
| 67 | + |
| 68 | + const accessToken = await generateAccessToken(); |
| 69 | + const url = `${base}/v2/checkout/orders`; |
| 70 | + const payload = { |
| 71 | + intent: "CAPTURE", |
| 72 | + purchase_units: [ |
| 73 | + { |
| 74 | + amount: { |
| 75 | + currency_code: "USD", |
| 76 | + value: "110.00", |
| 77 | + }, |
| 78 | + }, |
| 79 | + ], |
| 80 | + payment_source: { |
| 81 | + paypal: { |
| 82 | + attributes: { |
| 83 | + vault: { |
| 84 | + store_in_vault: "ON_SUCCESS", |
| 85 | + usage_type: "MERCHANT", |
| 86 | + customer_type: "CONSUMER", |
| 87 | + }, |
| 88 | + }, |
| 89 | + experience_context: { |
| 90 | + return_url: "http://example.com", |
| 91 | + cancel_url: "http://example.com", |
| 92 | + shipping_preference: "NO_SHIPPING", |
| 93 | + }, |
| 94 | + }, |
| 95 | + }, |
| 96 | + }; |
| 97 | + |
| 98 | + const response = await fetch(url, { |
| 99 | + headers: { |
| 100 | + "Content-Type": "application/json", |
| 101 | + Authorization: `Bearer ${accessToken}`, |
| 102 | + // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: |
| 103 | + // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ |
| 104 | + // "PayPal-Mock-Response": '{"mock_application_codes": "MISSING_REQUIRED_PARAMETER"}' |
| 105 | + // "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}' |
| 106 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' |
| 107 | + }, |
| 108 | + method: "POST", |
| 109 | + body: JSON.stringify(payload), |
| 110 | + }); |
| 111 | + |
| 112 | + return handleResponse(response); |
| 113 | +}; |
| 114 | + |
| 115 | +/** |
| 116 | + * Capture payment for the created order to complete the transaction. |
| 117 | + * @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture |
| 118 | + */ |
| 119 | +const captureOrder = async (orderID) => { |
| 120 | + const accessToken = await generateAccessToken(); |
| 121 | + const url = `${base}/v2/checkout/orders/${orderID}/capture`; |
| 122 | + |
| 123 | + const response = await fetch(url, { |
| 124 | + method: "POST", |
| 125 | + headers: { |
| 126 | + "Content-Type": "application/json", |
| 127 | + Authorization: `Bearer ${accessToken}`, |
| 128 | + // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: |
| 129 | + // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ |
| 130 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INSTRUMENT_DECLINED"}' |
| 131 | + // "PayPal-Mock-Response": '{"mock_application_codes": "TRANSACTION_REFUSED"}' |
| 132 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' |
| 133 | + }, |
| 134 | + }); |
| 135 | + |
| 136 | + return handleResponse(response); |
| 137 | +}; |
| 138 | + |
| 139 | +async function handleResponse(response) { |
| 140 | + try { |
| 141 | + const jsonResponse = await response.json(); |
| 142 | + return { |
| 143 | + jsonResponse, |
| 144 | + httpStatusCode: response.status, |
| 145 | + }; |
| 146 | + } catch (err) { |
| 147 | + const errorMessage = await response.text(); |
| 148 | + throw new Error(errorMessage); |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +app.post("/api/orders", async (req, res) => { |
| 153 | + try { |
| 154 | + // use the cart information passed from the front-end to calculate the order amount detals |
| 155 | + const { cart } = req.body; |
| 156 | + const { jsonResponse, httpStatusCode } = await createOrder(cart); |
| 157 | + res.status(httpStatusCode).json(jsonResponse); |
| 158 | + } catch (error) { |
| 159 | + console.error("Failed to create order:", error); |
| 160 | + res.status(500).json({ error: "Failed to create order." }); |
| 161 | + } |
| 162 | +}); |
| 163 | + |
| 164 | +app.post("/api/orders/:orderID/capture", async (req, res) => { |
| 165 | + try { |
| 166 | + const { orderID } = req.params; |
| 167 | + const { jsonResponse, httpStatusCode } = await captureOrder(orderID); |
| 168 | + console.log("capture response", jsonResponse); |
| 169 | + res.status(httpStatusCode).json(jsonResponse); |
| 170 | + } catch (error) { |
| 171 | + console.error("Failed to create order:", error); |
| 172 | + res.status(500).json({ error: "Failed to capture order." }); |
| 173 | + } |
| 174 | +}); |
| 175 | + |
| 176 | +// render checkout page with client id & user id token |
| 177 | +app.get("/", async (req, res) => { |
| 178 | + try { |
| 179 | + const { jsonResponse } = await authenticate({ |
| 180 | + target_customer_id: req.query.customerID, |
| 181 | + }); |
| 182 | + res.render("checkout", { |
| 183 | + clientId: PAYPAL_CLIENT_ID, |
| 184 | + userIdToken: jsonResponse.id_token, |
| 185 | + }); |
| 186 | + } catch (err) { |
| 187 | + res.status(500).send(err.message); |
| 188 | + } |
| 189 | +}); |
| 190 | + |
| 191 | +app.listen(PORT, () => { |
| 192 | + console.log(`Node server listening at http://localhost:${PORT}/`); |
| 193 | +}); |
0 commit comments