Skip to content

Instantly share code, notes, and snippets.

@deepu105
Created March 5, 2021 13:10
Show Gist options
  • Save deepu105/0b1596acf76e7ab3f670b29d8ed75626 to your computer and use it in GitHub Desktop.
Save deepu105/0b1596acf76e7ab3f670b29d8ed75626 to your computer and use it in GitHub Desktop.
payment-api-checkout.js
async function checkout() {
try {
const adyenPaymentMethods = await callServer("/api/getPaymentMethods");
// create a new payment request
const request = new PaymentRequest(buildSupportedPaymentMethodData(adyenPaymentMethods), buildShoppingCartDetails());
// payment logic goes here
} catch (error) {
console.error(error);
alert(`Error occurred: ${error.message}`);
}
return false;
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: "order-123",
displayItems: [
{ label: "Sunglasses", amount: { currency: "EUR", value: "5.00" } },
{ label: "Headphones", amount: { currency: "EUR", value: "5.00" } },
],
total: { label: "Total", amount: { currency: "EUR", value: "10.00" } },
};
}
function buildSupportedPaymentMethodData(adyenPaymentMethods) {
return [
{
supportedMethods: "basic-card",
data: {
supportedNetworks: getSupportedNetworksFromAdyen(adyenPaymentMethods),
supportedTypes: ["credit"],
},
},
];
}
// compare supported cards between Adyen and Payment Request API and get the intersection
function getSupportedNetworksFromAdyen(adyenPaymentMethods) {
const supportedByPaymentAPI = ["amex", "cartebancaire", "diners", "discover", "jcb", "mc", "mir", "unionpay", "visa"];
// filter supported credit cards
const supportedByAdyen = adyenPaymentMethods.paymentMethods.filter((v) => v.type === "scheme")[0].brands;
// get only the intersection between supportedByPaymentAPI and supportedByAdyen
return supportedByPaymentAPI.reduce((acc, curr) => (supportedByAdyen.includes(curr) ? [...acc, fixMasterCard(curr)] : acc), []);
}
// Mastercard id is not same for Adyen and Payment Request API
function fixMasterCard(v) {
return v === "mc" ? "mastercard" : v;
}
// Calls your server endpoints
async function callServer(url, data) {
const res = await fetch(url, {
method: "POST",
body: data ? JSON.stringify(data) : "",
headers: {
"Content-Type": "application/json",
},
});
return await res.json();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment