A web-based payment app is a website that handles payments for merchants through the Payment Request API. When a merchant requests payment with your payment method, Chrome sends the request to your service worker, which opens your payment page in a modal window over the merchant's site. Users don't need to install anything.
Before you start, set up your payment method identifier, payment method
manifest, and web app manifest as described in
Set up a payment method for your payment app. Chrome
registers your service worker
just-in-time from the
serviceworker field of your web app manifest, so you don't need to register it
yourself.
To see complete working examples, check out the Payment Handler API demo, the BobBucks web-based payment app, and the Payment Request API merchant samples.
How a web-based payment app works
A web-based payment app has two parts that communicate with postMessage():
- Service worker: Receives the payment request from the merchant, opens the payment window, relays changes to the merchant, and returns the result.
- Payment window: A page on your origin where the user signs in, chooses how to pay, and authorizes the payment.
A transaction follows these steps:
- The merchant calls
show(), and Chrome sends apaymentrequestevent to your service worker. - The service worker calls
respondWith()with a promise, then opens the payment window withopenWindow(). - The payment window tells the service worker that it's ready, and the service worker sends it the transaction details.
- If the user changes their payment method, shipping address, or shipping option in the payment window, the window messages the service worker, which notifies the merchant. If the merchant returns updated details, the service worker forwards them back to the payment window.
- When the user authorizes or cancels the payment, the service worker resolves or rejects the promise, and Chrome returns the result to the merchant.
Receive the payment request
When the merchant calls show(), your service worker receives a
PaymentRequestEvent.
Pass a promise to respondWith() so that you can resolve or reject it when the
user finishes, then open your payment page with openWindow().
When a merchant constructs a PaymentRequest (before calling show()), Chrome
may also send a
CanMakePaymentEvent
to your service worker. Only listen for this event if you check whether the user
is ready to pay (for example, whether they have a saved account or payment
instrument); if you always return true, omit the listener.
Keep these CanMakePaymentEvent rules in mind:
- Affects
hasEnrolledInstrument(), notcanMakePayment(). Your response controls the merchant'sPaymentRequest.hasEnrolledInstrument()result;canMakePayment()staystruewhenever your payment app is available. - Not always sent. Chrome skips the event if your service worker isn't installed yet (including before just-in-time registration), in Incognito mode, or if the user turned off the setting allowing sites to check for saved payment methods.
- No merchant context. The event exposes only
respondWith()—no merchant origin ormethodData—so the response can't depend on the merchant.
[payment handler] service-worker.js:
const activeRequests = new Map();
self.addEventListener('canmakepayment', (event) => {
// Check whether the user has a saved payment instrument (Promise<boolean>).
event.respondWith(hasSavedPaymentInstrument());
});
self.addEventListener('paymentrequest', (event) => {
// Track each request by ID so concurrent payment requests don't collide
// and stale messages from earlier windows are ignored.
const id = crypto.randomUUID();
const {promise, resolve, reject} = Promise.withResolvers();
activeRequests.set(id, {event, resolve, reject});
event.respondWith(promise);
event.openWindow(`/pay/checkout.html?id=${id}`).then((client) => {
if (!client) {
activeRequests.delete(id);
reject(new DOMException('Failed to open payment window', 'AbortError'));
}
}).catch((error) => {
activeRequests.delete(id);
reject(error);
});
});
Use the following PaymentRequestEvent properties to identify the merchant and
build your UI:
| Property | Description |
|---|---|
topOrigin |
The origin of the top-level page, usually the merchant. |
paymentRequestOrigin |
The origin that called the Payment Request API. This differs from
topOrigin when a third party, such as a payment service
provider, calls the API from an iframe.
|
paymentRequestId |
The id the merchant set in the payment details, or an ID
that the browser generates.
|
methodData |
The payment-method-specific data the merchant passed for your payment method, such as a transaction ID. |
total |
The total amount and currency to display to the user. |
paymentOptions |
The shipping and contact information the merchant requested, populated only for fields your app declared in its supported delegations. See Provide shipping and contact information. |
shippingOptions |
The shipping options the merchant offers, populated only if the
merchant requested shipping and your app declared the
shippingAddress delegation.
|
Exchange messages with the payment window
openWindow() resolves when the page loads, which can be before your page's
scripts are ready to receive messages. To avoid losing messages, have the payment
window tell the service worker when it's ready, then send the transaction details
in response.
In the payment window, send a ready message to the service worker and listen for its replies:
[payment handler] checkout.html:
const requestId = new URLSearchParams(location.search).get('id');
navigator.serviceWorker.addEventListener('message', (event) => {
switch (event.data.type) {
case 'PAYMENT_DETAILS':
// Render the total and the merchant origin.
renderPaymentUI(event.data);
break;
case 'PAYMENT_DETAILS_UPDATED':
// Render the updated total, shipping options, or errors.
updatePaymentUI(event.data.details);
break;
}
});
navigator.serviceWorker.controller?.postMessage({
id: requestId,
type: 'WINDOW_IS_READY',
});
In the service worker, reply with the details the payment window needs:
[payment handler] service-worker.js:
self.addEventListener('message', async (event) => {
const id = event.data?.id;
const request = activeRequests.get(id);
if (!request) return;
const {event: paymentRequestEvent, resolve, reject} = request;
switch (event.data.type) {
case 'WINDOW_IS_READY': {
const {topOrigin, total, paymentOptions, shippingOptions} =
paymentRequestEvent;
event.source.postMessage({
type: 'PAYMENT_DETAILS',
topOrigin,
total,
paymentOptions,
shippingOptions,
});
break;
}
// Handle other messages as shown in the following sections.
}
});
Return the payment result
When the user authorizes the payment, send a message from the payment window to the service worker:
[payment handler] checkout.html:
navigator.serviceWorker.controller?.postMessage({
id: requestId,
type: 'PAYMENT_AUTHORIZED',
details: {token: paymentToken},
});
Then resolve the promise you passed to respondWith() with a methodName and
payment-method-specific details. The merchant receives these values in the
PaymentResponse.
To let the user cancel the payment and close the payment window, reject the
promise you passed to respondWith()—as a best practice, reject with an
AbortError DOMException. Chrome closes the payment window and remaps all
rejections to a generic AbortError for the merchant, so any custom error type
or message you pass to reject() isn't forwarded. Don't resolve the promise
with null or an empty object, because Chrome requires methodName and
details when the promise resolves and returns an OperationError if they're
missing.
[payment handler] service-worker.js:
case 'PAYMENT_AUTHORIZED':
activeRequests.delete(id);
resolve({
methodName: 'https://bobbucks.dev/pay',
details: event.data.details,
});
break;
case 'PAYMENT_CANCELED':
activeRequests.delete(id);
reject(new DOMException('Payment canceled by user', 'AbortError'));
break;
Provide shipping and contact information
If users store their shipping address and contact details with your payment app, merchants can delegate collecting them to you. Chrome can then skip its own Payment Request UI and launch your app directly.
To support delegation, list the information you can provide in the
payment.supported_delegations field of your
web app manifest
(or call
enableDelegations()
on the service worker registration from your website).
Check paymentRequestEvent.paymentOptions to see which delegated fields the
merchant requested, such as requestShipping or requestPayerEmail. Any
requested field that your app supports using delegation is mandatory in the
response—if you omit it (or return an empty value or invalid shipping address),
Chrome rejects the merchant's show() promise with an OperationError:
const response = {
methodName: 'https://bobbucks.dev/pay',
details: event.data.details,
};
const {paymentOptions} = paymentRequestEvent;
if (paymentOptions?.requestShipping) {
response.shippingAddress = event.data.shippingAddress;
response.shippingOption = event.data.shippingOptionId;
}
if (paymentOptions?.requestPayerName) {
response.payerName = event.data.payerName;
}
if (paymentOptions?.requestPayerEmail) {
response.payerEmail = event.data.payerEmail;
}
if (paymentOptions?.requestPayerPhone) {
response.payerPhone = event.data.payerPhone;
}
activeRequests.delete(id);
resolve(response);
Handle shipping and payment method changes
The merchant may change the total depending on the user's choices, for example
to add shipping costs or a discount for a specific card. When the user changes
their shipping address, shipping option, or payment method in your payment
window, notify the merchant from the service worker with one of the following
PaymentRequestEvent methods:
changeShippingAddress(address): Firesshippingaddresschangeon the merchant'sPaymentRequest.changeShippingOption(shippingOptionId): Firesshippingoptionchange.changePaymentMethod(methodName, methodDetails): Firespaymentmethodchange.
Each method returns a promise that resolves with the details the merchant
passes to updateWith(), or null if the merchant makes no changes. Forward
updated details to the payment window so it can refresh the total and shipping
options:
[payment handler] service-worker.js:
async function notifyMerchantChange(source, runChange) {
try {
const details = await runChange();
// details is null if the merchant made no changes; still reply so the
// payment window knows the update settled.
source.postMessage({type: 'PAYMENT_DETAILS_UPDATED', details});
} catch (error) {
// Tell the payment window so it can clear loading state, revert, or retry
// (for example, on InvalidStateError when another change is in flight).
source.postMessage({type: 'PAYMENT_CHANGE_FAILED', error});
}
}
case 'SHIPPING_ADDRESS_CHANGED':
await notifyMerchantChange(
event.source,
() => paymentRequestEvent.changeShippingAddress(
event.data.shippingAddress),
);
break;
case 'SHIPPING_OPTION_CHANGED':
await notifyMerchantChange(
event.source,
() => paymentRequestEvent.changeShippingOption(
event.data.shippingOptionId),
);
break;
case 'PAYMENT_METHOD_CHANGED':
await notifyMerchantChange(
event.source,
() => paymentRequestEvent.changePaymentMethod(
event.data.methodName, event.data.methodDetails),
);
break;
On the merchant's side, the corresponding event handler calculates the new
details and passes them to updateWith():
[merchant]:
request.addEventListener('shippingaddresschange', (event) => {
const address = request.shippingAddress;
event.updateWith(calculateDetailsForAddress(address));
});
Keep the following in mind:
- Send one change at a time. Only one
changeShippingAddress(),changeShippingOption(), orchangePaymentMethod()call can be in flight perPaymentRequestEvent. Calling any of them while a previous change is pending rejects with anInvalidStateError, so wait for the change promise to settle (for example, disable selection controls in the payment window until the service worker reports completion, or queue updates) before sending another. - Chrome redacts the address. Before the merchant receives a
shippingaddresschangeevent, Chrome removes theorganization,phone,recipient, andaddressLinefields. The merchant receives the full address only after the user authorizes the payment. - Share only what the merchant needs.
methodDetailsinchangePaymentMethod()reaches the merchant before the user authorizes the payment, so omit sensitive information. - Display merchant errors. The updated details can include the following
fields:
totalandshippingOptions: The new values to display.error: A message to show the user, for example when the merchant can't ship to the selected address.shippingAddressErrors: Errors for individual address fields, which you can show next to the relevant fields.paymentMethodErrors: A payment-method-specific error.
- Document what merchants should return. The updated details contain exactly
what the merchant passes to
updateWith(). Tell merchants what you expect in your integration guide or SDK.
Understand the payment window
Chrome opens your payment page in a modal window over the merchant's page. Most web APIs work as they do in a top-level page, with the following differences:
- Same-origin URL: The URL you pass to
openWindow()must be on the same origin as your service worker, and you can callopenWindow()only once perpaymentrequestevent. - Closing the window:
window.close()has no effect. The payment window closes only when the user dismisses the dialog, or when your service worker resolves or rejects the promise passed torespondWith(). - User interaction required: The user must interact with the payment window
before the payment can complete. If you resolve
respondWith()before the user interacts with the window, Chrome waits for user interaction before returning the response to the merchant. - Opening new windows:
window.open()or links withtarget="_blank"triggered by a user gesture open in a new browser tab or window outside the payment window. Calls without a user gesture are blocked. - HTTPS and no mixed content: The page must be served over HTTPS without mixed content. Otherwise, Chrome cancels the payment.
You can use WebAuthn in the payment window, for example to sign users in with a passkey.
Debug your payment app
Use the following techniques to test your payment app during development.
Test on a development server
The Payment Request API and web-based payment apps require a secure context.
Chrome treats http://localhost as secure, so you can test there without a
certificate.
To test on another development origin without a valid certificate, launch a separate Chrome instance with the following flags. Only use these flags with a test profile, because they weaken security for the origins you list.
google-chrome --user-data-dir=/tmp/payment-test-profile \
--ignore-certificate-errors \
--unsafely-treat-insecure-origin-as-secure=http://dev.example.com
For more information, see Run Chromium with flags.
To test on Android, use port forwarding to access your development server from the device, and remote debugging to inspect the merchant page and payment window from desktop DevTools.
Log payment events in DevTools
Chrome DevTools can record the events sent to your service worker:
- Open DevTools on the merchant page.
- In the Application panel, under Background services, select Payment handler.
- Select Show events from other domains, then click Start recording events.
Next steps
- Learn how merchants call your payment app in the Web Payments overview.
- For the full API, see the Web-Based Payment Handler API on MDN.