The HTML5 Payment Request API is a modern web standard designed to simplify the payment process on websites. It allows users to make payments using their preferred payment method, such as credit cards, digital wallets, or other supported methods, directly from the browser. This API enhances user experience by reducing friction and providing a seamless payment flow.
In this tutorial, we will explore how to implement the Payment Request API in your web applications. We'll cover the basics of setting up the API, handling different payment methods, and integrating it with existing forms.
Before diving into the implementation, ensure you have the following:
To use the Payment Request API, you need to create a PaymentRequest object. This object requires three main parameters: supported payment methods, details about the transaction, and options for the payment request.
The first parameter is an array of objects representing the payment methods your application supports. Each object should have at least one method identifier, such as "basic-card" for credit cards or specific wallet identifiers like "https://apple.com/apple-pay" for Apple Pay.
const supportedMethods = [
"basic-card",
{
supportedMethods: "https://apple.com/apple-pay",
data: {
merchantIdentifier: "merchant.com.example",
supportedNetworks: ["visa", "mastercard"],
countryCode: "US"
}
}
];
The second parameter is an object that provides details about the transaction, such as the total amount and currency.
const details = {
displayItems: [
{
label: 'T-shirt',
amount: {currency: 'USD', value: '15.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '15.00'}
}
};
The third parameter is an optional object that allows you to specify additional options, such as whether shipping or payment handler details are required.
const options = {
requestPayerName: true,
requestPayerEmail: true,
requestShipping: false
};
With the parameters defined, you can create a PaymentRequest object and display it to the user.
if (window.PaymentRequest) {
const request = new PaymentRequest(supportedMethods, details, options);
// Show the payment request dialog
request.show()
.then(response => {
// Handle successful payment response
return response.complete('success');
})
.catch(error => {
// Handle errors
console.error('Payment failed:', error);
});
} else {
console.log("Payment Request API is not supported in this browser.");
}
Once the user selects a payment method and completes the payment, the show() method resolves with a PaymentResponse object. You can use this object to process the payment on your server.
request.show()
.then(response => {
// Send payment details to the server for processing
return fetch('/process-payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
methodName: response.methodName,
details: response.details
})
}).then(res => {
if (!res.ok) {
throw new Error('Payment processing failed');
}
return res.json();
}).then(data => {
// Handle server response
console.log('Payment processed:', data);
return response.complete('success');
});
})
.catch(error => {
console.error('Payment failed:', error);
request.abort();
});
Here's a complete example of how you might integrate the Payment Request API into an e-commerce website:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Request Example</title>
</head>
<body>
<button id="payButton">Pay with Payment Request API</button>
<script>
const supportedMethods = [
"basic-card",
{
supportedMethods: "https://apple.com/apple-pay",
data: {
merchantIdentifier: "merchant.com.example",
supportedNetworks: ["visa", "mastercard"],
countryCode: "US"
}
}
];
const details = {
displayItems: [
{
label: 'T-shirt',
amount: {currency: 'USD', value: '15.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '15.00'}
}
};
const options = {
requestPayerName: true,
requestPayerEmail: true,
requestShipping: false
};
document.getElementById('payButton').addEventListener('click', () => {
if (window.PaymentRequest) {
const request = new PaymentRequest(supportedMethods, details, options);
request.show()
.then(response => {
return fetch('/process-payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
methodName: response.methodName,
details: response.details
})
}).then(res => {
if (!res.ok) {
throw new Error('Payment processing failed');
}
return res.json();
}).then(data => {
console.log('Payment processed:', data);
return response.complete('success');
});
})
.catch(error => {
console.error('Payment failed:', error);
request.abort();
});
} else {
alert("Payment Request API is not supported in this browser.");
}
});
</script>
</body>
</html>
The HTML5 Payment Request API provides a powerful and user-friendly way to handle payments on the web. By following the steps outlined in this tutorial, you can integrate this API into your applications and offer a seamless payment experience to your users. Remember to test thoroughly and provide fallbacks for unsupported browsers to ensure a robust implementation.