Created
March 5, 2021 13:10
-
-
Save deepu105/0b1596acf76e7ab3f670b29d8ed75626 to your computer and use it in GitHub Desktop.
payment-api-checkout.js
This file contains 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
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