Payment Request API
The Payment Request API provides a consistent user experience for payments on the web. It allows the browser to act as an intermediary between the merchant, the user, and the payment method (like Apple Pay, Google Pay, or stored cards).
1. The Concept
Instead of every website building its own checkout form, the Payment Request API delegates this to the browser. The browser displays a native UI where the user can select their saved payment details, shipping address, and contact info.
2. Basic Structure
The process involves creating a PaymentRequest object, showing the UI, and handling the result.
Step 1: Define Payment Methods
This is where you specify supported methods.
Note: The basic-card method (raw credit card entry) has been deprecated in many browsers. This API is now primarily used as the underlying mechanism for Google Pay, Apple Pay, and Samsung Pay.
const supportedInstruments = [
{
supportedMethods: 'https://google.com/pay',
data: {
// Google Pay specific configuration
environment: 'TEST',
apiVersion: 2,
apiVersionMinor: 0,
merchantInfo: {
merchantName: 'Example Merchant'
},
allowedPaymentMethods: [/* ... */]
}
}
];
Step 2: Define Payment Details
Define the total amount and line items.
const details = {
displayItems: [
{
label: 'Original T-Shirt',
amount: { currency: 'USD', value: '25.00' }
}
],
total: {
label: 'Total',
amount: { currency: 'USD', value: '25.00' }
}
};
Step 3: Create and Show Request
// 1. Create the request
const request = new PaymentRequest(supportedInstruments, details);
// 2. Check if payment is possible
request.canMakePayment().then(result => {
if (result) {
// Show the payment button
}
});
// 3. Show the UI (on button click)
async function onCheckout() {
try {
const paymentResponse = await request.show();
// 4. Process payment with your backend
// Send paymentResponse.details to your server
console.log(paymentResponse.details);
// 5. Complete the UI
await paymentResponse.complete('success');
} catch (err) {
console.error('Payment cancelled or failed:', err);
}
}
programming/javascript/vanilla/javascript programming/javascript/vanilla/promises-async-await programming/javascript/vanilla/events