-
Notifications
You must be signed in to change notification settings - Fork 530
Add Save Payment Method #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3c41808
Add Save Payment Method
jshawl f2c113a
Use test client-id
jshawl 849759c
npm run format
jshawl d581019
Use ejs to render data-user-id-token
jshawl dcffe7f
Update save-payment-method/server/server.js
jshawl 8b9ba5d
Link to return buyer experience
jshawl d4ea5c3
Add &vault=true to SDK script
jshawl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| # Create an application to obtain credentials at | ||
| # https://developer.paypal.com/dashboard/applications/sandbox | ||
|
|
||
| PAYPAL_CLIENT_ID=YOUR_CLIENT_ID_GOES_HERE | ||
| PAYPAL_CLIENT_SECRET=YOUR_SECRET_GOES_HERE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| .env |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # Save Payment Method Example | ||
|
|
||
| This folder contains example code for a PayPal Save Payment Method integration using both the JS SDK and Node.js to complete transactions with the PayPal REST API. | ||
|
|
||
| ## Instructions | ||
|
|
||
| 1. [Create an application](https://developer.paypal.com/dashboard/applications/sandbox/create) | ||
| 2. Rename `.env.example` to `.env` and update `PAYPAL_CLIENT_ID` and `PAYPAL_CLIENT_SECRET` | ||
| 3. Replace `test` in [client/app.js](client/app.js) with your app's client-id | ||
| 4. Run `npm install` | ||
| 5. Run `npm start` | ||
| 6. Open http://localhost:8888 | ||
| 7. Click "PayPal" and log in with one of your [Sandbox test accounts](https://developer.paypal.com/dashboard/accounts) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| const main = async () => { | ||
| const user = localStorage.getItem("user"); | ||
| const response = await fetch(`/api/id-token?user=${user}`); | ||
| const data = await response.json(); | ||
| const script = document.createElement("script"); | ||
| script.src = "https://www.paypal.com/sdk/js?client-id=test"; | ||
| script.setAttribute("data-user-id-token", data.id_token); | ||
| script.addEventListener("load", () => renderButtons()); | ||
| document.head.appendChild(script); | ||
| }; | ||
|
|
||
| main(); | ||
|
|
||
| const renderButtons = () => | ||
| window.paypal | ||
| .Buttons({ | ||
| async createOrder() { | ||
| try { | ||
| const response = await fetch("/api/orders", { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| }, | ||
| // use the "body" param to optionally pass additional order information | ||
| // like product ids and quantities | ||
| body: JSON.stringify({ | ||
| cart: [ | ||
| { | ||
| id: "YOUR_PRODUCT_ID", | ||
| quantity: "YOUR_PRODUCT_QUANTITY", | ||
| }, | ||
| ], | ||
| }), | ||
| }); | ||
|
|
||
| const orderData = await response.json(); | ||
|
|
||
| if (orderData.id) { | ||
| return orderData.id; | ||
| } else { | ||
| const errorDetail = orderData?.details?.[0]; | ||
| const errorMessage = errorDetail | ||
| ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})` | ||
| : JSON.stringify(orderData); | ||
|
|
||
| throw new Error(errorMessage); | ||
| } | ||
| } catch (error) { | ||
| console.error(error); | ||
| resultMessage( | ||
| `Could not initiate PayPal Checkout...<br><br>${error}`, | ||
| ); | ||
| } | ||
| }, | ||
| async onApprove(data, actions) { | ||
| try { | ||
| const response = await fetch(`/api/orders/${data.orderID}/capture`, { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| }, | ||
| }); | ||
|
|
||
| const orderData = await response.json(); | ||
| // Three cases to handle: | ||
| // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() | ||
| // (2) Other non-recoverable errors -> Show a failure message | ||
| // (3) Successful transaction -> Show confirmation or thank you message | ||
|
|
||
| const errorDetail = orderData?.details?.[0]; | ||
|
|
||
| if (errorDetail?.issue === "INSTRUMENT_DECLINED") { | ||
| // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() | ||
| // recoverable state, per https://developer.paypal.com/docs/checkout/standard/customize/handle-funding-failures/ | ||
| return actions.restart(); | ||
| } else if (errorDetail) { | ||
| // (2) Other non-recoverable errors -> Show a failure message | ||
| throw new Error( | ||
| `${errorDetail.description} (${orderData.debug_id})`, | ||
| ); | ||
| } else if (!orderData.purchase_units) { | ||
| throw new Error(JSON.stringify(orderData)); | ||
| } else { | ||
| // (3) Successful transaction -> Show confirmation or thank you message | ||
| // Or go to another URL: actions.redirect('thank_you.html'); | ||
| const transaction = | ||
| orderData?.purchase_units?.[0]?.payments?.captures?.[0] || | ||
| orderData?.purchase_units?.[0]?.payments?.authorizations?.[0]; | ||
| resultMessage( | ||
| `Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`, | ||
| ); | ||
|
|
||
| localStorage.setItem( | ||
| "user", | ||
| orderData.payment_source.paypal.attributes.vault.customer.id, | ||
| ); | ||
|
|
||
| console.log( | ||
| "Capture result", | ||
| orderData, | ||
| JSON.stringify(orderData, null, 2), | ||
| ); | ||
| } | ||
| } catch (error) { | ||
| console.error(error); | ||
| resultMessage( | ||
| `Sorry, your transaction could not be processed...<br><br>${error}`, | ||
| ); | ||
| } | ||
| }, | ||
| }) | ||
| .render("#paypal-button-container"); | ||
|
|
||
| // Example function to show a result to the user. Your site's UI library can be used instead. | ||
| function resultMessage(message) { | ||
| const container = document.querySelector("#result-message"); | ||
| container.innerHTML = message; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <!doctype html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8" /> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
| <title>PayPal JS SDK Standard Integration</title> | ||
| </head> | ||
| <body> | ||
| <div id="paypal-button-container"></div> | ||
| <p id="result-message"></p> | ||
| <script src="app.js"></script> | ||
| </body> | ||
| </html> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| { | ||
| "name": "paypal-save-payment-method", | ||
| "description": "Sample Node.js web app to integrate PayPal Save Payment Method for online payments", | ||
| "version": "1.0.0", | ||
| "main": "server/server.js", | ||
| "type": "module", | ||
| "scripts": { | ||
| "test": "echo \"Error: no test specified\" && exit 1", | ||
| "start": "nodemon server/server.js", | ||
| "format": "npx prettier --write **/*.{js,md}", | ||
| "format:check": "npx prettier --check **/*.{js,md}", | ||
| "lint": "npx eslint server/*.js --env=node && npx eslint client/*.js --env=browser" | ||
| }, | ||
| "license": "Apache-2.0", | ||
| "dependencies": { | ||
| "dotenv": "^16.3.1", | ||
| "express": "^4.18.2", | ||
| "node-fetch": "^3.3.2" | ||
| }, | ||
| "devDependencies": { | ||
| "nodemon": "^3.0.1" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| import express from "express"; | ||
| import fetch from "node-fetch"; | ||
| import "dotenv/config"; | ||
| import path from "path"; | ||
|
|
||
| const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PORT = 8888 } = process.env; | ||
| const base = "https://api-m.sandbox.paypal.com"; | ||
| const app = express(); | ||
|
|
||
| // host static files | ||
| app.use(express.static("client")); | ||
|
|
||
| // parse post params sent in body in json format | ||
| app.use(express.json()); | ||
|
|
||
| /** | ||
| * Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs. | ||
| * @see https://developer.paypal.com/api/rest/authentication/ | ||
| */ | ||
| const authenticate = async (targetCustomerId) => { | ||
|
jshawl marked this conversation as resolved.
Outdated
|
||
| try { | ||
| if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) { | ||
| throw new Error("MISSING_API_CREDENTIALS"); | ||
| } | ||
| const auth = Buffer.from( | ||
| PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET, | ||
| ).toString("base64"); | ||
|
|
||
| let body = "grant_type=client_credentials&response_type=id_token"; | ||
| if (targetCustomerId) { | ||
| body += `&target_customer_id=${targetCustomerId}`; | ||
| } | ||
|
|
||
| const response = await fetch(`${base}/v1/oauth2/token`, { | ||
| method: "POST", | ||
| body, | ||
| headers: { | ||
| Authorization: `Basic ${auth}`, | ||
| }, | ||
| }); | ||
| return handleResponse(response); | ||
| } catch (error) { | ||
| console.error("Failed to generate Access Token:", error); | ||
| } | ||
| }; | ||
|
|
||
| const generateAccessToken = async () => { | ||
| const { jsonResponse } = await authenticate(); | ||
| return jsonResponse.access_token; | ||
| }; | ||
|
|
||
| /** | ||
| * Create an order to start the transaction. | ||
| * @see https://developer.paypal.com/docs/api/orders/v2/#orders_create | ||
| */ | ||
| const createOrder = async (cart) => { | ||
| // use the cart information passed from the front-end to calculate the purchase unit details | ||
| console.log( | ||
| "shopping cart information passed from the frontend createOrder() callback:", | ||
| cart, | ||
| ); | ||
|
|
||
| const accessToken = await generateAccessToken(); | ||
| const url = `${base}/v2/checkout/orders`; | ||
| const payload = { | ||
| intent: "CAPTURE", | ||
| purchase_units: [ | ||
| { | ||
| amount: { | ||
| currency_code: "USD", | ||
| value: "110.00", | ||
| }, | ||
| }, | ||
| ], | ||
| payment_source: { | ||
| paypal: { | ||
| attributes: { | ||
| vault: { | ||
| store_in_vault: "ON_SUCCESS", | ||
| usage_type: "MERCHANT", | ||
| customer_type: "CONSUMER", | ||
| }, | ||
| }, | ||
| experience_context: { | ||
| return_url: "http://example.com", | ||
| cancel_url: "http://example.com", | ||
| }, | ||
| }, | ||
| }, | ||
| }; | ||
|
|
||
| const response = await fetch(url, { | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| Authorization: `Bearer ${accessToken}`, | ||
| // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: | ||
| // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "MISSING_REQUIRED_PARAMETER"}' | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}' | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' | ||
| }, | ||
| method: "POST", | ||
| body: JSON.stringify(payload), | ||
| }); | ||
|
|
||
| return handleResponse(response); | ||
| }; | ||
|
|
||
| /** | ||
| * Capture payment for the created order to complete the transaction. | ||
| * @see https://developer.paypal.com/docs/api/orders/v2/#orders_capture | ||
| */ | ||
| const captureOrder = async (orderID) => { | ||
| const accessToken = await generateAccessToken(); | ||
| const url = `${base}/v2/checkout/orders/${orderID}/capture`; | ||
|
|
||
| const response = await fetch(url, { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| Authorization: `Bearer ${accessToken}`, | ||
| // Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation: | ||
| // https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/ | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "INSTRUMENT_DECLINED"}' | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "TRANSACTION_REFUSED"}' | ||
| // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' | ||
| }, | ||
| }); | ||
|
|
||
| return handleResponse(response); | ||
| }; | ||
|
|
||
| async function handleResponse(response) { | ||
| try { | ||
| const jsonResponse = await response.json(); | ||
| return { | ||
| jsonResponse, | ||
| httpStatusCode: response.status, | ||
| }; | ||
| } catch (err) { | ||
| const errorMessage = await response.text(); | ||
| throw new Error(errorMessage); | ||
| } | ||
| } | ||
|
|
||
| app.get("/api/id-token", async (req, res) => { | ||
| const { jsonResponse } = await authenticate(req.query.user); | ||
| res.json(jsonResponse); | ||
| }); | ||
|
|
||
| app.post("/api/orders", async (req, res) => { | ||
| try { | ||
| // use the cart information passed from the front-end to calculate the order amount detals | ||
| const { cart } = req.body; | ||
| const { jsonResponse, httpStatusCode } = await createOrder(cart); | ||
| res.status(httpStatusCode).json(jsonResponse); | ||
| } catch (error) { | ||
| console.error("Failed to create order:", error); | ||
| res.status(500).json({ error: "Failed to create order." }); | ||
| } | ||
| }); | ||
|
|
||
| app.post("/api/orders/:orderID/capture", async (req, res) => { | ||
| try { | ||
| const { orderID } = req.params; | ||
| const { jsonResponse, httpStatusCode } = await captureOrder(orderID); | ||
| res.status(httpStatusCode).json(jsonResponse); | ||
| } catch (error) { | ||
| console.error("Failed to create order:", error); | ||
| res.status(500).json({ error: "Failed to capture order." }); | ||
| } | ||
| }); | ||
|
|
||
| // serve index.html | ||
| app.get("/", (req, res) => { | ||
| res.sendFile(path.resolve("./client/checkout.html")); | ||
| }); | ||
|
|
||
| app.listen(PORT, () => { | ||
| console.log(`Node server listening at http://localhost:${PORT}/`); | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would you be open to converting this file to .ejs? Wondering if that would make things easier with setting the
data-user-id-token.For the standard integration we have kept it as plain html to keep it as simple as possible. But for other examples we have been leveraging ejs for server-side templating. That way you can embed values that the data-user-id from the server-side and still the load the JS SDK script in it too. Here's an example of how v2 card fields does this to set the clientID: https://github.com/paypal-examples/docs-examples/blob/main/advanced-integration/v2/server/views/checkout.ejs#L20
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah great idea!! yes - I really like this approach!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Converted in d581019