|
| 1 | +import express from "express"; |
| 2 | +import fetch from "node-fetch"; |
| 3 | +import "dotenv/config"; |
| 4 | +import path from "path"; |
| 5 | + |
| 6 | +const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PORT = 8888 } = process.env; |
| 7 | +const base = "https://api-m.sandbox.paypal.com"; |
| 8 | +const app = express(); |
| 9 | + |
| 10 | +// host static files |
| 11 | +app.use(express.static("client")); |
| 12 | + |
| 13 | +// parse post params sent in body in json format |
| 14 | +app.use(express.json()); |
| 15 | + |
| 16 | +/** |
| 17 | + * Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs. |
| 18 | + * @see https://developer.paypal.com/api/rest/authentication/ |
| 19 | + */ |
| 20 | +const generateAccessToken = async () => { |
| 21 | + try { |
| 22 | + if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) { |
| 23 | + throw new Error("MISSING_API_CREDENTIALS"); |
| 24 | + } |
| 25 | + const auth = Buffer.from( |
| 26 | + PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET, |
| 27 | + ).toString("base64"); |
| 28 | + const response = await fetch(`${base}/v1/oauth2/token`, { |
| 29 | + method: "POST", |
| 30 | + body: "grant_type=client_credentials", |
| 31 | + headers: { |
| 32 | + Authorization: `Basic ${auth}`, |
| 33 | + }, |
| 34 | + }); |
| 35 | + |
| 36 | + const data = await response.json(); |
| 37 | + return data.access_token; |
| 38 | + } catch (error) { |
| 39 | + console.error("Failed to generate Access Token:", error); |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * Create an order to start the transaction. |
| 45 | + * @see https://developer.paypal.com/docs/api/orders/v2/#orders_create |
| 46 | + */ |
| 47 | +const createOrder = async (cart) => { |
| 48 | + // use the cart information passed from the front-end to calculate the purchase unit details |
| 49 | + console.log( |
| 50 | + "shopping cart information passed from the frontend createOrder() callback:", |
| 51 | + cart, |
| 52 | + ); |
| 53 | + |
| 54 | + const accessToken = await generateAccessToken(); |
| 55 | + const url = `${base}/v2/checkout/orders`; |
| 56 | + const payload = { |
| 57 | + intent: "CAPTURE", |
| 58 | + purchase_units: [ |
| 59 | + { |
| 60 | + amount: { |
| 61 | + currency_code: "USD", |
| 62 | + value: "100.00", |
| 63 | + }, |
| 64 | + }, |
| 65 | + ], |
| 66 | + }; |
| 67 | + |
| 68 | + const response = await fetch(url, { |
| 69 | + headers: { |
| 70 | + "Content-Type": "application/json", |
| 71 | + Authorization: `Bearer ${accessToken}`, |
| 72 | + // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: |
| 73 | + // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ |
| 74 | + // "PayPal-Mock-Response": '{"mock_application_codes": "MISSING_REQUIRED_PARAMETER"}' |
| 75 | + // "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}' |
| 76 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' |
| 77 | + }, |
| 78 | + method: "POST", |
| 79 | + body: JSON.stringify(payload), |
| 80 | + }); |
| 81 | + |
| 82 | + return handleResponse(response); |
| 83 | +}; |
| 84 | + |
| 85 | +/** |
| 86 | + * Capture payment for the created order to complete the transaction. |
| 87 | + * @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture |
| 88 | + */ |
| 89 | +const captureOrder = async (orderID) => { |
| 90 | + const accessToken = await generateAccessToken(); |
| 91 | + const url = `${base}/v2/checkout/orders/${orderID}/capture`; |
| 92 | + |
| 93 | + const response = await fetch(url, { |
| 94 | + method: "POST", |
| 95 | + headers: { |
| 96 | + "Content-Type": "application/json", |
| 97 | + Authorization: `Bearer ${accessToken}`, |
| 98 | + // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: |
| 99 | + // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ |
| 100 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INSTRUMENT_DECLINED"}' |
| 101 | + // "PayPal-Mock-Response": '{"mock_application_codes": "TRANSACTION_REFUSED"}' |
| 102 | + // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' |
| 103 | + }, |
| 104 | + }); |
| 105 | + |
| 106 | + return handleResponse(response); |
| 107 | +}; |
| 108 | + |
| 109 | +async function handleResponse(response) { |
| 110 | + try { |
| 111 | + const jsonResponse = await response.json(); |
| 112 | + return { |
| 113 | + jsonResponse, |
| 114 | + httpStatusCode: response.status, |
| 115 | + }; |
| 116 | + } catch (err) { |
| 117 | + const errorMessage = await response.text(); |
| 118 | + throw new Error(errorMessage); |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +app.post("/api/orders", async (req, res) => { |
| 123 | + try { |
| 124 | + // use the cart information passed from the front-end to calculate the order amount detals |
| 125 | + const { cart } = req.body; |
| 126 | + const { jsonResponse, httpStatusCode } = await createOrder(cart); |
| 127 | + res.status(httpStatusCode).json(jsonResponse); |
| 128 | + } catch (error) { |
| 129 | + console.error("Failed to create order:", error); |
| 130 | + res.status(500).json({ error: "Failed to create order." }); |
| 131 | + } |
| 132 | +}); |
| 133 | + |
| 134 | +app.post("/api/orders/:orderID/capture", async (req, res) => { |
| 135 | + try { |
| 136 | + const { orderID } = req.params; |
| 137 | + const { jsonResponse, httpStatusCode } = await captureOrder(orderID); |
| 138 | + res.status(httpStatusCode).json(jsonResponse); |
| 139 | + } catch (error) { |
| 140 | + console.error("Failed to create order:", error); |
| 141 | + res.status(500).json({ error: "Failed to capture order." }); |
| 142 | + } |
| 143 | +}); |
| 144 | + |
| 145 | +// serve index.html |
| 146 | +app.get("/", (req, res) => { |
| 147 | + res.sendFile(path.resolve("./client/checkout.html")); |
| 148 | +}); |
| 149 | + |
| 150 | +app.listen(PORT, () => { |
| 151 | + console.log(`Node server listening at http://localhost:${PORT}/`); |
| 152 | +}); |
0 commit comments