The Payment Request API: Browser-Native Checkout
How the Payment Request API shows a native payment sheet from JavaScript: methods, details, canMakePayment, shipping options and the server-side steps.

Checkout forms are where sales are lost. Every field a customer has to type, name, address, card number, expiry and security code, is a chance to give up, and on a phone each one is a keyboard fight. The Payment Request API gives the browser a way to take over that part of the flow: the page describes what is being bought and which payment methods it accepts, the browser shows a native sheet populated with the customer's saved details, and the page gets back a response with a payment credential it can send to its payment processor. The customer taps once instead of typing. This post explains how the Payment Request API works: the PaymentRequest constructor and its three parts, payment methods and what they are, canMakePayment() and feature detection, how to show the sheet and read the response, how to complete it, the events for changing shipping and totals, the secure context and user gesture rules, how it relates to Apple Pay and Google Pay, what the server must still do, and how to test it. The API is specified by the W3C Web Payments Working Group and documented on MDN. It is available in Chromium browsers and Safari, with support for the payment methods varying by browser and region, and it needs HTTPS. It is a progressive enhancement: keep your regular checkout form as the fallback.
The three arguments
A PaymentRequest is built from a list of payment methods, the details of the transaction and optional options.
const methods = [
{
supportedMethods: "https://google.com/pay",
data: { environment: "TEST", apiVersion: 2, apiVersionMinor: 0 },
},
{ supportedMethods: "basic-card" },
];
const details = {
total: {
label: "Order total",
amount: { currency: "USD", value: "42.50" },
},
displayItems: [
{ label: "Keyboard", amount: { currency: "USD", value: "39.00" } },
{ label: "Tax", amount: { currency: "USD", value: "3.50" } },
],
};
const options = { requestPayerEmail: true, requestShipping: false };
const request = new PaymentRequest(methods, details, options);
console.log(request.id.length > 0);trueThe supportedMethods value is a payment method identifier, which is a URL for the payment handler that processes it, such as the one for Google Pay or Apple Pay, or the legacy basic-card string, which is deprecated and removed from most browsers, so do not build on it. The data is specific to each method. The details.total is required and is what the user is asked to pay, and displayItems are the lines that explain it. Amounts are strings, to avoid floating point errors, and must be valid decimal numbers for the currency. Compute them on the server and pass them to the page, since a price computed only in the browser is a price the user can change.
Check support first
PaymentRequest exists in a browser that supports the API, and canMakePayment() tells whether the user has a method that can pay. Use both to decide whether to show the one-tap button.
async function canPayWithBrowser(methods, details) {
if (!("PaymentRequest" in window)) return false;
try {
const request = new PaymentRequest(methods, details);
return await request.canMakePayment();
} catch {
return false;
}
}
canPayWithBrowser(methods, details).then((ok) => {
document.querySelector("#pay-button").hidden = !ok;
console.log("native payment available:", ok);
});native payment available: truecanMakePayment() is meant to answer a narrow question and not to fingerprint the user, so browsers may rate-limit or give less detail. A false result is not an error: it means to use the ordinary form. The constructor throws a TypeError for invalid input, such as a malformed amount, and a SecurityError outside a secure context, which the try block above treats as "not available".
Showing the sheet
show() opens the browser's payment interface. It must be called from a user gesture, such as a click, because opening a payment dialog is something the user has to ask for, and it can be called only once per request object. It returns a promise that resolves with a PaymentResponse when the user confirms, and rejects with an AbortError if they cancel.
document.querySelector("#pay-button").addEventListener("click", async () => {
const request = new PaymentRequest(methods, details, options);
try {
const response = await request.show();
const result = await fetch("/api/pay", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
method: response.methodName,
details: response.details,
email: response.payerEmail,
}),
});
await response.complete(result.ok ? "success" : "fail");
console.log(result.ok ? "paid" : "declined");
} catch (error) {
if (error.name === "AbortError") {
console.log("user canceled");
} else {
console.log("error:", error.name);
}
}
});paidThe response carries methodName and details, which hold the payment credential in a form that depends on the method, for example a token from Google Pay or Apple Pay, plus the contact details you asked for, in payerEmail, payerName, payerPhone and shippingAddress. Send them to your server, which passes the token to your payment processor and returns the result. Then call response.complete("success") or complete("fail"), which closes the sheet with the matching animation. The sheet stays in a processing state until you call complete(), so do it as soon as the server answers, and never leave it hanging.
Never trust the browser alone
The page produces a token, and the server does the actual charging. Treat everything from the browser as untrusted input: recompute the amount from the order on the server, check that the currency and the items match, verify the token with the processor, and make the request idempotent, so a retry cannot charge twice. The Payment Request API does not move money by itself. It standardizes how details and credentials are collected, and the payment handler and your processor do the rest.
// pseudo-code for the server endpoint
app.post("/api/pay", async (req, res) => {
const order = await orders.findPending(req.session.orderId);
const amount = order.totalFor(req.session);
const charge = await processor.charge({
token: req.body.details.token,
amount,
currency: order.currency,
idempotencyKey: order.id,
});
res.status(charge.ok ? 200 : 402).json({ ok: charge.ok });
});(the amount comes from the stored order, never from the request body)Shipping and changing totals
When you ask for shipping, the sheet lets the user pick an address and a shipping option, and the page must update the total in response. The request fires shippingaddresschange and shippingoptionchange events, and your handler passes a promise to event.updateWith() that resolves with updated details.
const details = {
total: { label: "Total", amount: { currency: "USD", value: "39.00" } },
shippingOptions: [
{ id: "standard", label: "Standard (5 days)", amount: { currency: "USD", value: "4.00" }, selected: true },
{ id: "express", label: "Express (1 day)", amount: { currency: "USD", value: "14.00" } },
],
};
const request = new PaymentRequest(methods, details, { requestShipping: true });
request.addEventListener("shippingaddresschange", (event) => {
event.updateWith(
(async () => {
const country = request.shippingAddress.country;
if (country !== "US") {
return { error: "We only ship within the US", total: details.total };
}
return details;
})(),
);
});
request.addEventListener("shippingoptionchange", (event) => {
const selected = details.shippingOptions.find((o) => o.id === request.shippingOption);
const total = (39 + Number(selected.amount.value)).toFixed(2);
event.updateWith({
total: { label: "Total", amount: { currency: "USD", value: total } },
shippingOptions: details.shippingOptions.map((o) => ({ ...o, selected: o.id === selected.id })),
});
});(choosing Express updates the total to 53.00 in the sheet)For privacy, the address in shippingaddresschange is redacted: the browser withholds the street and name until the user confirms the payment, giving only the country, region, city and postal code so you can compute tax and shipping. Return an error string in the update to tell the user that an address cannot be served, and the sheet shows it.
Cancelling and timeouts
request.abort() closes a pending sheet, for instance if the page decides the cart changed. A sheet does not time out by itself, but a processing state that never completes is a bug. Use try and finally so complete() is always called, and handle InvalidStateError, which is thrown if you call show() twice or complete() twice.
Payment methods in practice
The identifiers you use decide which wallets appear. Apple Pay in Safari is available through https://apple.com/apple-pay with a merchant session, and Google Pay through https://google.com/pay with the parameters from its documentation, which include the gateway and your merchant ID. Processors such as Stripe publish helpers on top, for example a Payment Request Button, that wrap the API and handle the method data, and in many cases the helper is the easiest and safest way to adopt it. Region matters: which methods a user sees depends on their browser, device, wallet setup and country.
Compared with the wallet's own buttons
Apple Pay JS and the Google Pay API each have their own JavaScript interface and branded button. The Payment Request API is the standard layer that those can plug into, with a single code path for several wallets. In practice, many sites use the wallet's button for the branding and the strict design rules it requires, or a processor's wrapper, and keep Payment Request for cases where one standard interface across browsers is valuable.
Accessibility and fallbacks
The sheet is browser UI, so accessibility is handled by the browser. Your part is the button and the fallback. Show the "Pay" button only when canMakePayment() is true, label it clearly, and keep the regular form on the same page, reachable by keyboard, because users may decline the sheet, have no wallet or prefer typing. Never remove the form for browsers that support the API.
Testing
Test in a browser with a wallet set up, using the test environment of each method, such as Google Pay's TEST environment, which accepts test cards. In unit tests, stub window.PaymentRequest with a class whose show() resolves to a fake response, and check that your code posts the right body and calls complete() with the right status.
class FakeResponse {
methodName = "https://google.com/pay";
details = { token: "tok_test" };
payerEmail = "[email protected]";
completed = null;
async complete(status) {
this.completed = status;
}
}
globalThis.PaymentRequest = class {
async canMakePayment() {
return true;
}
async show() {
return new FakeResponse();
}
};
const response = await new PaymentRequest([], {}).show();
await response.complete("success");
console.log(response.completed);successPitfalls
Calling show() without a user gesture. Calling it twice on one object. Computing totals only in the browser. Skipping complete(). Relying on the deprecated basic-card method. Removing the normal checkout form. Using floating point numbers for amounts instead of strings. Not handling cancel as a normal outcome. And forgetting that canMakePayment() can be false in browsers that support the API.


