diff --git a/advanced-integration/public/app.js b/advanced-integration/public/app.js index b26369c7..02f484f6 100644 --- a/advanced-integration/public/app.js +++ b/advanced-integration/public/app.js @@ -1,17 +1,17 @@ async function createOrderCallback() { try { - const response = await fetch('/api/orders', { - method: 'POST', + const response = await fetch("/api/orders", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "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', + id: "YOUR_PRODUCT_ID", + quantity: "YOUR_PRODUCT_QUANTITY", }, ], }), @@ -38,9 +38,9 @@ async function createOrderCallback() { async function onApproveCallback(data, actions) { try { const response = await fetch(`/api/orders/${data.orderID}/capture`, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, }); @@ -55,11 +55,11 @@ async function onApproveCallback(data, actions) { orderData?.purchase_units?.[0]?.payments?.authorizations?.[0]; const errorDetail = orderData?.details?.[0]; - const isHostedFieldsComponent = typeof data.card === 'object'; + const isHostedFieldsComponent = typeof data.card === "object"; // this actions.restart() behavior only applies to the Buttons component if ( - errorDetail?.issue === 'INSTRUMENT_DECLINED' && + errorDetail?.issue === "INSTRUMENT_DECLINED" && isHostedFieldsComponent === false ) { // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart() @@ -68,7 +68,7 @@ async function onApproveCallback(data, actions) { } else if ( errorDetail || !transaction || - transaction.status === 'DECLINED' + transaction.status === "DECLINED" ) { // (2) Other non-recoverable errors -> Show a failure message let errorMessage; @@ -88,7 +88,7 @@ async function onApproveCallback(data, actions) { `Transaction ${transaction.status}: ${transaction.id}

See console for all available details`, ); console.log( - 'Capture result', + "Capture result", orderData, JSON.stringify(orderData, null, 2), ); @@ -106,11 +106,11 @@ paypal createOrder: createOrderCallback, onApprove: onApproveCallback, }) - .render('#paypal-button-container'); + .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'); + const container = document.querySelector("#result-message"); container.innerHTML = message; } @@ -121,55 +121,55 @@ if (paypal.HostedFields.isEligible()) { // Call your server to set up the transaction createOrder: createOrderCallback, styles: { - '.valid': { - color: 'green', + ".valid": { + color: "green", }, - '.invalid': { - color: 'red', + ".invalid": { + color: "red", }, }, fields: { number: { - selector: '#card-number', - placeholder: '4111 1111 1111 1111', + selector: "#card-number", + placeholder: "4111 1111 1111 1111", }, cvv: { - selector: '#cvv', - placeholder: '123', + selector: "#cvv", + placeholder: "123", }, expirationDate: { - selector: '#expiration-date', - placeholder: 'MM/YY', + selector: "#expiration-date", + placeholder: "MM/YY", }, }, }).then((cardFields) => { - document.querySelector('#card-form').addEventListener('submit', (event) => { + document.querySelector("#card-form").addEventListener("submit", (event) => { event.preventDefault(); cardFields .submit({ // Cardholder's first and last name - cardholderName: document.getElementById('card-holder-name').value, + cardholderName: document.getElementById("card-holder-name").value, // Billing Address billingAddress: { // Street address, line 1 streetAddress: document.getElementById( - 'card-billing-address-street', + "card-billing-address-street", ).value, // Street address, line 2 (Ex: Unit, Apartment, etc.) extendedAddress: document.getElementById( - 'card-billing-address-unit', + "card-billing-address-unit", ).value, // State - region: document.getElementById('card-billing-address-state').value, + region: document.getElementById("card-billing-address-state").value, // City - locality: document.getElementById('card-billing-address-city') + locality: document.getElementById("card-billing-address-city") .value, // Postal Code - postalCode: document.getElementById('card-billing-address-zip') + postalCode: document.getElementById("card-billing-address-zip") .value, // Country Code countryCodeAlpha2: document.getElementById( - 'card-billing-address-country', + "card-billing-address-country", ).value, }, }) @@ -188,5 +188,5 @@ if (paypal.HostedFields.isEligible()) { }); } else { // Hides card fields if the merchant isn't eligible - document.querySelector('#card-form').style = 'display: none'; + document.querySelector("#card-form").style = "display: none"; } diff --git a/advanced-integration/server.js b/advanced-integration/server.js index fb2d8c35..d8415e00 100644 --- a/advanced-integration/server.js +++ b/advanced-integration/server.js @@ -1,13 +1,13 @@ -import express from 'express'; -import fetch from 'node-fetch'; -import 'dotenv/config'; -import path from 'path'; +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 base = "https://api-m.sandbox.paypal.com"; const app = express(); -app.set('view engine', 'ejs'); -app.use(express.static('public')); +app.set("view engine", "ejs"); +app.use(express.static("public")); // parse post params sent in body in json format app.use(express.json()); @@ -19,14 +19,14 @@ app.use(express.json()); const generateAccessToken = async () => { try { if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) { - throw new Error('MISSING_API_CREDENTIALS'); + throw new Error("MISSING_API_CREDENTIALS"); } const auth = Buffer.from( - PAYPAL_CLIENT_ID + ':' + PAYPAL_CLIENT_SECRET, - ).toString('base64'); + PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET, + ).toString("base64"); const response = await fetch(`${base}/v1/oauth2/token`, { - method: 'POST', - body: 'grant_type=client_credentials', + method: "POST", + body: "grant_type=client_credentials", headers: { Authorization: `Basic ${auth}`, }, @@ -35,7 +35,7 @@ const generateAccessToken = async () => { const data = await response.json(); return data.access_token; } catch (error) { - console.error('Failed to generate Access Token:', error); + console.error("Failed to generate Access Token:", error); } }; @@ -47,11 +47,11 @@ const generateClientToken = async () => { const accessToken = await generateAccessToken(); const url = `${base}/v1/identity/generate-token`; const response = await fetch(url, { - method: 'POST', + method: "POST", headers: { Authorization: `Bearer ${accessToken}`, - 'Accept-Language': 'en_US', - 'Content-Type': 'application/json', + "Accept-Language": "en_US", + "Content-Type": "application/json", }, }); @@ -65,19 +65,19 @@ const generateClientToken = async () => { 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:', + "shopping cart information passed from the frontend createOrder() callback:", cart, ); const accessToken = await generateAccessToken(); const url = `${base}/v2/checkout/orders`; const payload = { - intent: 'CAPTURE', + intent: "CAPTURE", purchase_units: [ { amount: { - currency_code: 'USD', - value: '0.02', + currency_code: "USD", + value: "0.02", }, }, ], @@ -85,7 +85,7 @@ const createOrder = async (cart) => { const response = await fetch(url, { headers: { - 'Content-Type': 'application/json', + "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/ @@ -93,7 +93,7 @@ const createOrder = async (cart) => { // "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}' // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' }, - method: 'POST', + method: "POST", body: JSON.stringify(payload), }); @@ -109,9 +109,9 @@ const captureOrder = async (orderID) => { const url = `${base}/v2/checkout/orders/${orderID}/capture`; const response = await fetch(url, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json', + "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/ @@ -138,10 +138,10 @@ async function handleResponse(response) { } // render checkout page with client id & unique client token -app.get('/', async (req, res) => { +app.get("/", async (req, res) => { try { const { jsonResponse } = await generateClientToken(); - res.render('checkout', { + res.render("checkout", { clientId: PAYPAL_CLIENT_ID, clientToken: jsonResponse.client_token, }); @@ -150,26 +150,26 @@ app.get('/', async (req, res) => { } }); -app.post('/api/orders', async (req, res) => { +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.' }); + 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) => { +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.' }); + console.error("Failed to create order:", error); + res.status(500).json({ error: "Failed to capture order." }); } }); diff --git a/standard-integration/index.html b/standard-integration/index.html index 2bdc9a4b..6a355374 100644 --- a/standard-integration/index.html +++ b/standard-integration/index.html @@ -15,18 +15,18 @@ .Buttons({ createOrder: async () => { try { - const response = await fetch('/api/orders', { - method: 'POST', + const response = await fetch("/api/orders", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "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', + id: "YOUR_PRODUCT_ID", + quantity: "YOUR_PRODUCT_QUANTITY", }, ], }), @@ -56,9 +56,9 @@ const response = await fetch( `/api/orders/${data.orderID}/capture`, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, }, ); @@ -71,7 +71,7 @@ const errorDetail = orderData?.details?.[0]; - if (errorDetail?.issue === 'INSTRUMENT_DECLINED') { + 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(); @@ -92,7 +92,7 @@ `Transaction ${transaction.status}: ${transaction.id}

See console for all available details`, ); console.log( - 'Capture result', + "Capture result", orderData, JSON.stringify(orderData, null, 2), ); @@ -105,11 +105,11 @@ } }, }) - .render('#paypal-button-container'); + .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'); + const container = document.querySelector("#result-message"); container.innerHTML = message; } diff --git a/standard-integration/server.js b/standard-integration/server.js index 7b7310f0..76f99226 100644 --- a/standard-integration/server.js +++ b/standard-integration/server.js @@ -1,10 +1,10 @@ -import express from 'express'; -import fetch from 'node-fetch'; -import 'dotenv/config'; -import path from 'path'; +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 base = "https://api-m.sandbox.paypal.com"; const app = express(); // parse post params sent in body in json format @@ -17,14 +17,14 @@ app.use(express.json()); const generateAccessToken = async () => { try { if (!PAYPAL_CLIENT_ID || !PAYPAL_CLIENT_SECRET) { - throw new Error('MISSING_API_CREDENTIALS'); + throw new Error("MISSING_API_CREDENTIALS"); } const auth = Buffer.from( - PAYPAL_CLIENT_ID + ':' + PAYPAL_CLIENT_SECRET, - ).toString('base64'); + PAYPAL_CLIENT_ID + ":" + PAYPAL_CLIENT_SECRET, + ).toString("base64"); const response = await fetch(`${base}/v1/oauth2/token`, { - method: 'POST', - body: 'grant_type=client_credentials', + method: "POST", + body: "grant_type=client_credentials", headers: { Authorization: `Basic ${auth}`, }, @@ -33,7 +33,7 @@ const generateAccessToken = async () => { const data = await response.json(); return data.access_token; } catch (error) { - console.error('Failed to generate Access Token:', error); + console.error("Failed to generate Access Token:", error); } }; @@ -44,19 +44,19 @@ const generateAccessToken = async () => { 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:', + "shopping cart information passed from the frontend createOrder() callback:", cart, ); const accessToken = await generateAccessToken(); const url = `${base}/v2/checkout/orders`; const payload = { - intent: 'CAPTURE', + intent: "CAPTURE", purchase_units: [ { amount: { - currency_code: 'USD', - value: '0.02', + currency_code: "USD", + value: "0.02", }, }, ], @@ -64,7 +64,7 @@ const createOrder = async (cart) => { const response = await fetch(url, { headers: { - 'Content-Type': 'application/json', + "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/ @@ -72,7 +72,7 @@ const createOrder = async (cart) => { // "PayPal-Mock-Response": '{"mock_application_codes": "PERMISSION_DENIED"}' // "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}' }, - method: 'POST', + method: "POST", body: JSON.stringify(payload), }); @@ -88,9 +88,9 @@ const captureOrder = async (orderID) => { const url = `${base}/v2/checkout/orders/${orderID}/capture`; const response = await fetch(url, { - method: 'POST', + method: "POST", headers: { - 'Content-Type': 'application/json', + "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/ @@ -116,32 +116,32 @@ async function handleResponse(response) { } } -app.post('/api/orders', async (req, res) => { +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.' }); + 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) => { +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.' }); + 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('./index.html')); +app.get("/", (req, res) => { + res.sendFile(path.resolve("./index.html")); }); app.listen(PORT, () => {