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