Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 32 additions & 32 deletions advanced-integration/public/app.js
Original file line number Diff line number Diff line change
@@ -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",
},
],
}),
Expand All @@ -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",
},
});

Expand All @@ -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()
Expand All @@ -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;
Expand All @@ -88,7 +88,7 @@ async function onApproveCallback(data, actions) {
`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,
);
console.log(
'Capture result',
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
Expand All @@ -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;
}

Expand All @@ -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,
},
})
Expand All @@ -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";
}
64 changes: 32 additions & 32 deletions advanced-integration/server.js
Original file line number Diff line number Diff line change
@@ -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());
Expand All @@ -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}`,
},
Expand All @@ -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);
}
};

Expand All @@ -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",
},
});

Expand All @@ -65,35 +65,35 @@ 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",
},
},
],
};

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/
// "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',
method: "POST",
body: JSON.stringify(payload),
});

Expand All @@ -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/
Expand All @@ -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,
});
Expand All @@ -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." });
}
});

Expand Down
22 changes: 11 additions & 11 deletions standard-integration/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
],
}),
Expand Down Expand Up @@ -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",
},
},
);
Expand All @@ -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();
Expand All @@ -92,7 +92,7 @@
`Transaction ${transaction.status}: ${transaction.id}<br><br>See console for all available details`,
);
console.log(
'Capture result',
"Capture result",
orderData,
JSON.stringify(orderData, null, 2),
);
Expand All @@ -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;
}
</script>
Expand Down
Loading