Payment Handler API

W3C Working Draft

This version:
https://www.w3.org/TR/2021/WD-payment-handler-20211004/
Latest published version:
https://www.w3.org/TR/payment-handler/
Latest editor's draft:
https://w3c.github.io/payment-handler/
Test suite:
https://wpt.live/payment-handler/
Previous version:
https://www.w3.org/TR/2021/WD-payment-handler-20210714/
Editors:
Adrian Hope-Bailie (Coil)
Ian Jacobs (W3C)
Rouslan Solomakhin (Google)
Jinho Bang (Samsung)
Former editors:
Andre Lyver (Shopify)
Tommy Thorsen (Opera)
Adam Roach (Mozilla)
Participate:
GitHub w3c/payment-handler
File an issue
Commit history
Pull requests

Abstract

This specification defines capabilities that enable Web applications to handle requests for payment.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

The Web Payments Working Group maintains a list of all bug reports that the group has not yet addressed. This draft highlights some of the pending issues that are still to be discussed in the working group. No decision has been taken on the outcome of these issues including whether they are valid. Pull requests with proposed specification text for outstanding issues are strongly encouraged.

This document was published by the Web Payments Working Group as a Working Draft. This document is intended to become a W3C Recommendation.

GitHub Issues are preferred for discussion of this specification.

Publication as a Working Draft does not imply endorsement by the W3C Membership.

This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 1 August 2017 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 15 September 2020 W3C Process Document.

1. Introduction

This section is non-normative.

This specification defines a number of new features to allow web applications to handle requests for payments on behalf of users:

Note

This specification does not address how software built with operating-system specific mechanisms (i.e., "native apps") handle payment requests.

2. Overview of Handling Payment Requests

In this document we envision the following flow:

  1. An origin requests permission from the user to handle payment requests for a set of supported payment methods. For example, a user visiting a retail or bank site may be prompted to register a payment handler from that origin. The origin establishes the scope of the permission but the origin's capabilities may evolve without requiring additional user consent.
  2. Payment handlers are defined in service worker code.
  3. The PaymentManager is used to set a list of payment instruments. Each payment instrument provides data to the user agent to improve the user experience of selecting payment credentials:
    • The method informs the user agent decision whether to display this instrument as a candidate for payment.
    • When the instrument matches what the payee accepts, the user agent may display the name and icon. These provide hints about payment credentials that the user agent will return in the PaymentHandlerResponse if the user selects this instrument.
  4. When the merchant (or other payee) calls the [payment-request] method canMakePayment() or show() (e.g., when the user pushes a button on a checkout page), the user agent computes a list of candidate payment handlers, comparing the payment methods accepted by the merchant with those supported by registered payment handlers. For payment methods that support additional filtering, CanMakePaymentEvent is used as part of determining whether there is a match.
  5. The user agent displays a set of choices to the user: the registered instruments of the candidate payment handlers. The user agent displays these choices using information (labels and icons) provided at registration or otherwise available from the Web app.
  6. When the user (the payer) selects an instrument, the user agent fires a PaymentRequestEvent (cf. the user interaction task source) in the service worker whose PaymentManager the instrument was registered with. The PaymentRequestEvent includes some information from the PaymentRequest (defined in [payment-request]) as well as additional information (e.g., origin and selected instrument).
  7. Once activated, the payment handler performs whatever steps are necessary to handle the payment request, and return an appropriate payment response to the payee. If interaction with the user is necessary, the payment handler can open a window for that purpose.
  8. The user agent receives a response asynchronously once the payment handler has finished handling the request. The response becomes the PaymentResponse (of [payment-request]).
Note

An origin may implement a payment app with more than one service worker and therefore multiple payment handlers may be registered per origin. The handler that is invoked is determined by the selection made by the user of a payment instrument. The service worker which stored the payment instrument with its PaymentManager is the one that will be invoked.

2.1 Handling a Payment Request

This section is non-normative.

A payment handler is a Web application that can handle a request for payment on behalf of the user.

The logic of a payment handler is driven by the payment methods that it supports. Some payment methods expect little to no processing by the payment handler which simply returns payment card details in the response. It is then the job of the payee website to process the payment using the returned data as input.

In contrast, some payment methods, such as a crypto-currency payments or bank originated credit transfers, require that the payment handler initiate processing of the payment. In such cases the payment handler will return a payment reference, endpoint URL or some other data that the payee website can use to determine the outcome of the payment (as opposed to processing the payment itself).

Handling a payment request may include numerous interactions: with the user through a new window or other APIs (such as Web Cryptography API) or with other services and origins through web requests or other means.

This specification does not address these activities that occur between the payment handler accepting the PaymentRequestEvent and the payment handler returning a response. All of these activities which may be required to configure the payment handler and handle the payment request, are left to the implementation of the payment handler, including:

Thus, an origin will rely on many other Web technologies defined elsewhere for lifecycle management, security, user authentication, user interaction, and so on.

2.2 Structure of a Web Payment App

This section is non-normative.

Architecture of a (Web) payment apps as defined in this specification.
Figure 1 A Web payment app is associated with an origin. Payment handlers respond to PaymentRequestEvents. PaymentManager manage the definition, display, and user selection of PaymentInstruments. A PaymentInstrument supports one or more payment methods.

2.3 Relation to Other Types of Payment Apps

This section is non-normative.

This specification does not address how third-party mobile payment apps interact (through proprietary mechanisms) with user agents, or how user agents themselves provide simple payment app functionality.

Different types of payment apps. Payment Handler API is for Web apps.
Figure 2 Payment Handler API enables Web apps to handle payments. Other types of payment apps may use other (proprietary) mechanisms.

3. Registration

One registers a payment handler with the user agent when assigning the first PaymentInstrument to it through the set() method.

3.1 Extension to the ServiceWorkerRegistration interface

WebIDLpartial interface ServiceWorkerRegistration {
  [SameObject] readonly attribute PaymentManager paymentManager;
};

The paymentManager attribute exposes payment handler functionality in the service worker.

3.2 PaymentManager interface

WebIDL[SecureContext, Exposed=(Window,Worker)]
interface PaymentManager {
  [SameObject] readonly attribute PaymentInstruments instruments;
  attribute DOMString userHint;
};

The PaymentManager is used by payment handlers to manage their associated instruments as well as supported payment methods.

3.2.1 instruments attribute

This attribute allows manipulation of payment instruments associated with a service worker (and therefore its payment handler). To be a candidate payment handler, a handler must have at least one registered payment instrument to present to the user. That instrument needs to match the payment methods specified by the payment request.

3.2.2 userHint attribute

When displaying payment handler name and icon, the user agent may use this string to improve the user experience. For example, a user hint of "**** 1234" can remind the user that a particular card is available through this payment handler. When a agent displays all payment instruments available through a payment handler, it may cause confusion to display the additional hint.

3.3 PaymentInstruments interface

WebIDL[SecureContext, Exposed=(Window,Worker)]
interface PaymentInstruments {
  Promise<boolean> delete(DOMString instrumentKey);
  Promise<any> get(DOMString instrumentKey);
  Promise<sequence<DOMString>>  keys();
  Promise<boolean> has(DOMString instrumentKey);
  Promise<undefined> set(DOMString instrumentKey, PaymentInstrument details);
  Promise<undefined> clear();
};

The PaymentInstruments interface represents a collection of payment instruments, each uniquely identified by an instrumentKey. The instrumentKey identifier will be passed to the payment handler to indicate the PaymentInstrument selected by the user, if any.

3.3.1 delete() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a PaymentInstrument with a matching instrumentKey, remove it from the collection and resolve p with true.
  4. Otherwise, resolve p with false.

3.3.2 get() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a PaymentInstrument with a matching instrumentKey, resolve p with that PaymentInstrument.
  4. Otherwise, resolve p with undefined.

3.3.3 keys() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. Resolve p with a Sequence that contains all the instrumentKeys for the PaymentInstruments contained in the collection, in original insertion order.

3.3.4 has() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a PaymentInstrument with a matching instrumentKey, resolve p with true.
  4. Otherwise, resolve p with false.

3.3.5 set() method

When called, this method executes the following steps:

  1. Let registration be the PaymentInstrument's associated service worker registration.
  2. If registration has no active worker, then reject a Promise with an "InvalidStateError" DOMException and terminate these steps.
  3. Upon user agent discretion and depending on user consent, optionally return a Promise rejected with a NotAllowedError.
  4. If the icons member of details is present, then:
    1. Let convertedIcons be the result of running the convert image objects algorithm passing details.icons as the argument.
    2. If the convertedIcons is an empty Sequence, then return a Promise rejected with a TypeError.
    3. Set details.icons to convertedIcons.
  5. Let p be a new promise.
  6. Return p and perform the remaining steps in parallel:
  7. If the icons member of details is present, then for each icon in details.icons:
    1. If the user agent wants to display the icon, then:
      1. Let fetchedImage be the result of steps to fetch an image resource passing icon as the argument.
      2. Set icon.[[fetchedImage]] to fetchedImage.
  8. If the collection contains a PaymentInstrument with a matching instrumentKey, replace it with the PaymentInstrument in details.
  9. Otherwise, insert the PaymentInstrument in details as a new member of the collection and associate it with the key instrumentKey.
  10. Resolve p.

3.3.6 clear() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. Remove all PaymentInstruments from the collection and resolve p.

3.3.7 PaymentInstrument dictionary

WebIDLdictionary PaymentInstrument {
  required DOMString name;
  sequence<ImageObject> icons;
  DOMString method;
};
name member
The name member is a string that represents the label for this PaymentInstrument as it is usually displayed to the user.
icons member
The icons member is an array of image objects that can serve as iconic representations of the payment instrument when presented to the user for selection.
method member
The method member is the payment method identifier of the payment method supported by this instrument.

3.3.8 ImageObject dictionary

WebIDLdictionary ImageObject {
    required USVString src;
    DOMString sizes;
    DOMString type;
};
src member
The src member is used to specify the ImageObject's source. It is a URL from which the user agent can fetch the image’s data.
sizes member
The sizes member is used to specify the ImageObject's sizes. It follows the spec of sizes member in HTML link element, which is a string consisting of an unordered set of unique space-separated tokens which are ASCII case-insensitive that represents the dimensions of an image. Each keyword is either an ASCII case-insensitive match for the string "any", or a value that consists of two valid non-negative integers that do not have a leading U+0030 DIGIT ZERO (0) character and that are separated by a single U+0078 LATIN SMALL LETTER X or U+0058 LATIN CAPITAL LETTER X character. The keywords represent icon sizes in raw pixels (as opposed to CSS pixels). When multiple image objects are available, a user agent MAY use the value to decide which icon is most suitable for a display context (and ignore any that are inappropriate). The parsing steps for the sizes member MUST follow the parsing steps for HTML link element sizes attribute.
type member
The type member is used to specify the ImageObject's MIME type. It is a hint as to the media type of the image. The purpose of this member is to allow a user agent to ignore images of media types it does not support.

3.3.9 Convert image objects

When this algorithm with inputImages parameter is invoked, the user agent must run the following steps:

  1. Let outputImages be an empty Sequence of ImageObject.
  2. For each image in inputImages:
    1. If image.type is not a valid MIME type string or the value of type is not a supported media format, then return an empty Sequence of ImageObject.
    2. If image.sizes is not a valid value, then return an empty Sequence of ImageObject.
    3. Let url be the result of parsing image.src with the this's relevant settings object's api base url.
    4. If url is failure, then return an empty Sequence of ImageObject.
    5. If url's scheme is not "https", then return an empty Sequence of ImageObject.
    6. Set image.src to url.
    7. Append image to outputImages
  3. Return outputImages.

According to the step 2.3, it is also possible to use the relative url for image.src. The following examples illustrate how relative URL resolution works in different execution contexts.

Example 1: Resolving the relative URL of image.src in window context.
<-- In this example, code is located in https://www.example.com/bobpay/index.html -->
<script>

const instrumentKey = "c8126178-3bba-4d09-8f00-0771bcfd3b11";
navigator.serviceWorker.register("/register/sw.js");
const registration = await navigator.serviceWorker.ready;
await registration.paymentManager.paymentInstruments.set({
  instrumentKey,
  {
    name: "My Bob Pay Account: john@example.com",
    method: "https://bobpay.com",
    icons: [{
      src: "icon/lowres.webp",
      sizes: "48x48",
      type: "image/webp"
    }]
  });

const storedInstrument =
  await registration.paymentManager.paymentInstruments.get(instrumentKey);

// storedInstrument.icons[0].src == "https://www.example.com/bobpay/icon/lowres.webp";

</script>
Example 2: Resolving the relative URL of image.src in service worker context.
// In this example, code is located in https://www.example.com/register/sw.js

const instrumentKey = "c8126178-3bba-4d09-8f00-0771bcfd3b11";
await self.registration.paymentManager.paymentInstruments.set({
  instrumentKey,
  {
    name: "My Bob Pay Account: john@example.com",
    method: "https://bobpay.com",
    icons: [{
      src: "../bobpay/icon/lowres.webp",
      sizes: "48x48",
      type: "image/webp"
    }]
  });

const storedInstrument =
  await registration.paymentManager.paymentInstruments.get(instrumentKey);

// storedInstrument.icons[0].src == "https://www.example.com/bobpay/icon/lowres.webp";

3.3.10 Registration Example

This section is non-normative.

The following example shows how to register a payment handler:

Example 3: Payment Handler Registration
button.addEventListener("click", async() => {
  if (!window.PaymentManager) {
    return; // not supported, so bail out.
  }

  navigator.serviceWorker.register("/sw.js");
  const registration = await navigator.serviceWorker.ready;

  // Excellent, we got it! Let's now set up the user's payment
  // instruments.
  await addInstruments(registration);
}, { once: true });

function addInstruments(registration) {
  return Promise.all([
    registration.paymentManager.instruments.set(
      "dc2de27a-ca5e-4fbd-883e-b6ded6c69d4f",
      {
        name: "My Example Pay Account: max@example.com",
        method: "https://example.com/pay",
      }),

    registration.paymentManager.instruments.set(
      "c8126178-3bba-4d09-8f00-0771bcfd3b11",
      {
        name: "My Bob Pay Account: john@bobpay.com",
        method: "https://bobpay.com"
      }),
    ]);
  };

4. Can make payment

If the payment handler supports CanMakePaymentEvent, the user agent may use it to help with filtering of the available payment handlers.

Implementations may impose a timeout for developers to respond to the CanMakePaymentEvent. If the timeout expires, then the implementation will behave as if respondWith() was called with false.

4.1 Extension to ServiceWorkerGlobalScope

WebIDLpartial interface ServiceWorkerGlobalScope {
  attribute EventHandler oncanmakepayment;
};

4.1.1 oncanmakepayment attribute

The oncanmakepayment attribute is an event handler whose corresponding event handler event type is "canmakepayment".

4.2 The CanMakePaymentEvent

The CanMakePaymentEvent is used to check whether the payment handler is able to respond to a payment request.

WebIDL[Exposed=ServiceWorker]
interface CanMakePaymentEvent : ExtendableEvent {
  constructor(DOMString type, optional CanMakePaymentEventInit eventInitDict = {});
  readonly attribute USVString topOrigin;
  readonly attribute USVString paymentRequestOrigin;
  readonly attribute FrozenArray<PaymentMethodData> methodData;
  undefined respondWith(Promise<boolean> canMakePaymentResponse);
};

The topOrigin, paymentRequestOrigin, methodData, and modifiers members share their definitions with those defined for PaymentRequestEvent.

4.2.1 respondWith() method

This method is used by the payment handler to indicate whether it can respond to a payment request.

4.2.2 CanMakePaymentEventInit dictionary

WebIDLdictionary CanMakePaymentEventInit : ExtendableEventInit {
  USVString topOrigin;
  USVString paymentRequestOrigin;
  sequence<PaymentMethodData> methodData;
};

The topOrigin, paymentRequestOrigin, and methodData members share their definitions with those defined for PaymentRequestEvent.

4.3 Handling a CanMakePaymentEvent

Upon receiving a PaymentRequest, the user agent MUST run the following steps:

  1. If user agent settings prohibit usage of CanMakePaymentEvent (e.g., in private browsing mode), terminate these steps.
  2. Let registration be a ServiceWorkerRegistration.
  3. If registration is not found, terminate these steps.
  4. Fire Functional Event "canmakepayment" using CanMakePaymentEvent on registration with the following properties:

    topOrigin
    the serialization of an origin of the top level payee web page.
    paymentRequestOrigin
    the serialization of an origin of the context where PaymentRequest was initialized.
    methodData
    The result of executing the MethodData Population Algorithm.
    modifiers
    The result of executing the Modifiers Population Algorithm.

4.4 Example of handling the CanMakePaymentEvent

This section is non-normative.

This example shows how to write a service worker that listens to the CanMakePaymentEvent. When a CanMakePaymentEvent is received, the service worker always returns true.

Example 4: Handling the CanMakePaymentEvent
self.addEventListener("canmakepayment", function(e) {
  e.respondWith(true);
});

4.5 Filtering of Payment Instruments

Given a PaymentMethodData and a PaymentInstrument that match on payment method identifier, this algorithm returns true if this instrument can be used for payment:

  1. Let instrument be the given PaymentInstrument.
  2. Let methodName be the payment method identifier string specified in the PaymentMethodData.
  3. Let methodData be the payment method specific data of PaymentMethodData.
  4. Let paymentHandlerOrigin be the origin of the ServiceWorkerRegistration scope URL of the payment handler with this instrument.
  5. Let paymentMethodManifest be the ingested and parsed payment method manifest for the methodName.
  6. If methodName is a standardized payment method identifier or is a URL-based payment method identifier with the "*" string supported origins in paymentMethodManifest, return true.
  7. Otherwise, if the URL-based payment method identifier methodName has the same origin as paymentHandlerOrigin, fire the CanMakePaymentEvent in the payment handler and return the result.
  8. Otherwise, if supported origins in paymentMethodManifest is an ordered set of origin that contains the paymentHandlerOrigin, fire the CanMakePaymentEvent in the payment handler and return the result.
  9. Otherwise, return false.

5. Invocation

Once the user has selected an Instrument, the user agent fires a PaymentRequestEvent and uses the subsequent PaymentHandlerResponse to create a PaymentReponse for [payment-request].

Issue 117: Support for Abort() being delegated to Payment Handler

Payment Request API supports delegation of responsibility to manage an abort to a payment app. There is a proposal to add a paymentRequestAborted event to the Payment Handler interface. The event will have a respondWith method that takes a boolean parameter indicating if the paymentRequest has been successfully aborted.

5.1 Extension to ServiceWorkerGlobalScope

This specification extends the ServiceWorkerGlobalScope interface.

WebIDLpartial interface ServiceWorkerGlobalScope {
  attribute EventHandler onpaymentrequest;
};

5.1.1 onpaymentrequest attribute

The onpaymentrequest attribute is an event handler whose corresponding event handler event type is PaymentRequestEvent.

5.2 The PaymentRequestDetailsUpdate

The PaymentRequestDetailsUpdate contains the updated total (optionally with modifiers) and possible errors resulting from user selection of a payment method.

WebIDLdictionary PaymentRequestDetailsUpdate {
  DOMString error;
  PaymentCurrencyAmount total;
  sequence<PaymentDetailsModifier> modifiers;
  object paymentMethodErrors;
};

5.2.1 error member

A human readable string that explains why the user selected payment method cannot be used.

5.2.2 total member

Updated total based on the changed payment method. The total can change, for example, because the billing address of the payment method selected by the user changes the Value Added Tax (VAT).

5.2.3 modifiers member

Updated modifiers based on the changed payment method. For example, if the overall total has increased by €1.00 based on the billing or shipping address, then the totals specified in each of the modifiers should also increase by €1.00.

5.2.4 paymentMethodErrors member

Validation errors for the payment method, if any.

5.3 The PaymentRequestEvent

The PaymentRequestEvent represents the data and methods available to a Payment Handler after selection by the user. The user agent communicates a subset of data available from the PaymentRequest to the Payment Handler.

WebIDL[Exposed=ServiceWorker]
interface PaymentRequestEvent : ExtendableEvent {
  constructor(DOMString type, optional PaymentRequestEventInit eventInitDict = {});
  readonly attribute USVString topOrigin;
  readonly attribute USVString paymentRequestOrigin;
  readonly attribute DOMString paymentRequestId;
  readonly attribute FrozenArray<PaymentMethodData> methodData;
  readonly attribute object total;
  readonly attribute FrozenArray<PaymentDetailsModifier> modifiers;
  Promise<WindowClient?> openWindow(USVString url);
  Promise<PaymentRequestDetailsUpdate?> changePaymentMethod(DOMString methodName, optional object? methodDetails = null);
  undefined respondWith(Promise<PaymentHandlerResponse> handlerResponsePromise);
};

5.3.1 topOrigin attribute

Returns a string that indicates the origin of the top level payee web page. This attribute is initialized by Handling a PaymentRequestEvent.

5.3.2 paymentRequestOrigin attribute

Returns a string that indicates the origin where a PaymentRequest was initialized. When a PaymentRequest is initialized in the topOrigin, the attributes have the same value, otherwise the attributes have different values. For example, when a PaymentRequest is initialized within an iframe from an origin other than topOrigin, the value of this attribute is the origin of the iframe. This attribute is initialized by Handling a PaymentRequestEvent.

5.3.3 paymentRequestId attribute

When getting, the paymentRequestId attribute returns the [[details]].id from the PaymentRequest that corresponds to this PaymentRequestEvent.

5.3.4 methodData attribute

This attribute contains PaymentMethodData dictionaries containing the payment method identifiers for the payment methods that the web site accepts and any associated payment method specific data. It is populated from the PaymentRequest using the MethodData Population Algorithm defined below.

5.3.5 total attribute

This attribute indicates the total amount being requested for payment. It is of type PaymentCurrencyAmount dictionary as defined in [payment-request], and initialized with a copy of the total field of the PaymentDetailsInit provided when the corresponding PaymentRequest object was instantiated.

5.3.6 modifiers attribute

This sequence of PaymentDetailsModifier dictionaries contains modifiers for particular payment method identifiers (e.g., if the payment amount or currency type varies based on a per-payment-method basis). It is populated from the PaymentRequest using the Modifiers Population Algorithm defined below.

5.3.7 openWindow() method

This method is used by the payment handler to show a window to the user. When called, it runs the open window algorithm.

5.3.8 changePaymentMethod() method

This method is used by the payment handler to get updated total given such payment method details as the billing address. When called, it runs the change payment method algorithm.

5.3.9 respondWith() method

This method is used by the payment handler to provide a PaymentHandlerResponse when the payment successfully completes. When called, it runs the Respond to PaymentRequest Algorithm with event and handlerResponsePromise as arguments.

Issue 123: Share user data with payment app?

Should payment apps receive user data stored in the user agent upon explicit consent from the user? The payment app could request permission either at installation or when the payment app is first invoked.

5.3.10 PaymentRequestEventInit dictionary

WebIDLdictionary PaymentRequestEventInit : ExtendableEventInit {
  USVString topOrigin;
  USVString paymentRequestOrigin;
  DOMString paymentRequestId;
  sequence<PaymentMethodData> methodData;
  PaymentCurrencyAmount total;
  sequence<PaymentDetailsModifier> modifiers;
};

The topOrigin, paymentRequestOrigin, paymentRequestId, methodData, total, and modifiers members share their definitions with those defined for PaymentRequestEvent

5.3.11 MethodData Population Algorithm

To initialize the value of the methodData, the user agent MUST perform the following steps or their equivalent:

  1. Set registeredMethods to an empty set.
  2. For each PaymentInstrument instrument in the payment handler's PaymentManager.instruments, add the value of instrument.method to registeredMethods.
  3. Create a new empty Sequence.
  4. Set dataList to the newly created Sequence.
  5. For each item in PaymentRequest@[[methodData]] in the corresponding payment request, perform the following steps:
    1. Set inData to the item under consideration.
    2. Set commonMethods to the set intersection of inData.supportedMethods and registeredMethods.
    3. If commonMethods is empty, skip the remaining substeps and move on to the next item (if any).
    4. Create a new PaymentMethodData object.
    5. Set outData to the newly created PaymentMethodData.
    6. Set outData.supportedMethods to a list containing the members of commonMethods.
    7. Set outData.data to a copy of inData.data.
    8. Append outData to dataList.
  6. Set methodData to dataList.

5.3.12 Modifiers Population Algorithm

To initialize the value of the modifiers, the user agent MUST perform the following steps or their equivalent:

  1. Set registeredMethods to an empty set.
  2. For each PaymentInstrument instrument in the payment handler's PaymentManager.instruments, add the value of instrument.method to registeredMethods.
  3. Create a new empty Sequence.
  4. Set modifierList to the newly created Sequence.
  5. For each item in PaymentRequest@[[paymentDetails]].modifiers in the corresponding payment request, perform the following steps:
    1. Set inModifier to the item under consideration.
    2. Set commonMethods to the set intersection of inModifier.supportedMethods and registeredMethods.
    3. If commonMethods is empty, skip the remaining substeps and move on to the next item (if any).
    4. Create a new PaymentDetailsModifier object.
    5. Set outModifier to the newly created PaymentDetailsModifier.
    6. Set outModifier.supportedMethods to a list containing the members of commonMethods.
    7. Set outModifier.total to a copy of inModifier.total.
    8. Append outModifier to modifierList.
  6. Set modifiers to modifierList.

5.4 Internal Slots

Instances of PaymentRequestEvent are created with the internal slots in the following table:

Internal Slot Default Value Description (non-normative)
[[windowClient]] null The currently active WindowClient. This is set if a payment handler is currently showing a window to the user. Otherwise, it is null.
[[fetchedImage]] undefined This value is a result of steps to fetch an image resource or a fallback image provided by the user agent.
[[respondWithCalled]] false YAHO

5.5 Handling a PaymentRequestEvent

Upon receiving a PaymentRequest by way of PaymentRequest.show() and subsequent user selection of a payment instrument, the user agent MUST run the following steps:

  1. Let registration be the ServiceWorkerRegistration corresponding to the PaymentInstrument selected by the user.
  2. If registration is not found, reject the Promise that was created by PaymentRequest.show() with an "InvalidStateError" DOMException and terminate these steps.
  3. Fire Functional Event "paymentrequest" using PaymentRequestEvent on registration with the following properties:

    topOrigin
    the serialization of an origin of the top level payee web page.
    paymentRequestOrigin
    the serialization of an origin of the context where PaymentRequest was initialized.
    methodData
    The result of executing the MethodData Population Algorithm.
    modifiers
    The result of executing the Modifiers Population Algorithm.
    total
    A copy of the total field on the PaymentDetailsInit from the corresponding PaymentRequest.
    paymentRequestId
    \[\[details\]\].id from the PaymentRequest.

    Then run the following steps in parallel, with dispatchedEvent:

    1. Wait for all of the promises in the extend lifetime promises of dispatchedEvent to resolve.
    2. If the payment handler has not provided a PaymentHandlerResponse, reject the Promise that was created by PaymentRequest.show() with an "OperationError" DOMException.

6. Windows

An invoked payment handler may or may not need to display information about itself or request user input. Some examples of potential payment handler display include:

A payment handler that requires visual display and user interaction, may call openWindow() to display a page to the user.

Note

Since user agents know that this method is connected to the PaymentRequestEvent, they SHOULD render the window in a way that is consistent with the flow and not confusing to the user. The resulting window client is bound to the tab/window that initiated the PaymentRequest. A single payment handler SHOULD NOT be allowed to open more than one client window using this method.

6.1 Open Window Algorithm

Issue 115: The Open Window Algorithm

This algorithm resembles the Open Window Algorithm in the Service Workers specification.

Issue 115: Open Window Algorithm

Should we refer to the Service Workers specification instead of copying their steps?

  1. Let event be this PaymentRequestEvent.
  2. If event's isTrusted attribute is false, return a Promise rejected with a "InvalidStateError" DOMException.
  3. Let request be the PaymentRequest that triggered this PaymentRequestEvent.
  4. Let url be the result of parsing the url argument.
  5. If the url parsing throws an exception, return a Promise rejected with that exception.
  6. If url is about:blank, return a Promise rejected with a TypeError.
  7. If url's origin is not the same as the service worker's origin associated with the payment handler, return a Promise resolved with null.
  8. Let promise be a new Promise.
  9. Return promise and perform the remaining steps in parallel:
  10. If event.[[windowClient]] is not null, then:
    1. If event.[[windowClient]].visibilityState is not "unloaded", reject promise with an "InvalidStateError" DOMException and abort these steps.
  11. Let newContext be a new top-level browsing context.
  12. Navigate newContext to url, with exceptions enabled and replacement enabled.
  13. If the navigation throws an exception, reject promise with that exception and abort these steps.
  14. If the origin of newContext is not the same as the service worker client origin associated with the payment handler, then:
    1. Resolve promise with null.
    2. Abort these steps.
  15. Let client be the result of running the create window client algorithm with newContext as the argument.
  16. Set event.[[windowClient]] to client.
  17. Resolve promise with client.

6.2 Example of handling the PaymentRequestEvent

This section is non-normative.

This example shows how to write a service worker that listens to the PaymentRequestEvent. When a PaymentRequestEvent is received, the service worker opens a window to interact with the user.

Example 5: Handling the PaymentRequestEvent
async function getPaymentResponseFromWindow() {
  return new Promise((resolve, reject) => {
    self.addEventListener("message", listener = e => {
      self.removeEventListener("message", listener);
      if (!e.data || !e.data.methodName) {
        reject();
        return;
      }
      resolve(e.data);
    });
  });
}

self.addEventListener("paymentrequest", e => {
  e.respondWith((async() => {
    // Open a new window for providing payment UI to user.
    const windowClient = await e.openWindow("payment_ui.html");

    // Send data to the opened window.
    windowClient.postMessage({
      total: e.total,
      modifiers: e.modifiers
    });

    // Wait for a payment response from the opened window.
    return await getPaymentResponseFromWindow();
  })());
});

Using the simple scheme described above, a trivial HTML page that is loaded into the payment handler window might look like the following:

Example 6: Simple Payment Handler Window
<form id="form">
<table>
  <tr><th>Cardholder Name:</th><td><input name="cardholderName"></td></tr>
  <tr><th>Card Number:</th><td><input name="cardNumber"></td></tr>
  <tr><th>Expiration Month:</th><td><input name="expiryMonth"></td></tr>
  <tr><th>Expiration Year:</th><td><input name="expiryYear"></td></tr>
  <tr><th>Security Code:</th><td><input name="cardSecurityCode"></td></tr>
  <tr><th></th><td><input type="submit" value="Pay"></td></tr>
</table>
</form>

<script>
navigator.serviceWorker.addEventListener("message", e => {
  /* Note: message sent from payment app is available in e.data */
});

document.getElementById("form").addEventListener("submit", e => {
  const details = {};
  ["cardholderName", "cardNumber", "expiryMonth", "expiryYear", "cardSecurityCode"]
  .forEach(field => {
    details[field] = form.elements[field].value;
  });

  const paymentAppResponse = {
    methodName: "https://example.com/pay",
    details
  };

  navigator.serviceWorker.controller.postMessage(paymentAppResponse);
  window.close();
});
</script>

7. Response

7.1 PaymentHandlerResponse dictionary

The PaymentHandlerResponse is conveyed using the following dictionary:
WebIDLdictionary PaymentHandlerResponse {
DOMString methodName;
object details;
};

7.1.1 methodName attribute

The payment method identifier for the payment method that the user selected to fulfil the transaction.

7.1.2 details attribute

A JSON-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer.

The user agent receives a successful response from the payment handler through resolution of the Promise provided to the respondWith function of the corresponding PaymentRequestEvent interface. The application is expected to resolve the Promise with a PaymentHandlerResponse instance containing the payment response. In case of user cancellation or error, the application may signal failure by rejecting the Promise.

If the Promise is rejected, the user agent MUST run the payment app failure algorithm. The exact details of this algorithm are left to implementers. Acceptable behaviors include, but are not limited to:

  • Letting the user try again, with the same payment handler or with a different one.
  • Rejecting the Promise that was created by PaymentRequest.show().

7.2 Change Payment Method Algorithm

When this algorithm is invoked with methodName and methodDetails parameters, the user agent MUST run the following steps:

  1. Run the payment method changed algorithm with PaymentMethodChangeEvent event constructed using the given methodName and methodDetails parameters.
  2. If event.updateWith(detailsPromise) is not run, return null.
  3. If event.updateWith(detailsPromise) throws, rethrow the error.
  4. If event.updateWith(detailsPromise) times out (optional), throw "InvalidStateError" DOMException.
  5. Construct and return a PaymentRequestDetailsUpdate from the detailsPromise in event.updateWith(detailsPromise).

7.3 Respond to PaymentRequest Algorithm

When this algorithm is invoked with event and handlerResponsePromise parameters, the user agent MUST run the following steps:

  1. If event's isTrusted is false, then throw an "InvalidStateError" DOMException and abort these steps.
  2. If event's dispatch flag is unset, then throw an "InvalidStateError" DOMException and abort these steps.
  3. If event.[[respondWithCalled]] is true, throw an "InvalidStateError" DOMException and abort these steps.
  4. Set event.[[respondWithCalled]] to true.
  5. Set the event's stop propagation flag and event's stop immediate propagation flag.
  6. Add handlerResponsePromise to the event's extend lifetime promises
  7. Increment the event's pending promises count by one.
  8. Upon rejection of handlerResponsePromise:
    1. Run the payment app failure algorithm and terminate these steps.
  9. Upon fulfillment of handlerResponsePromise:
    1. Let handlerResponse be value converted to an IDL value PaymentHandlerResponse. If this throws an exception, run the payment app failure algorithm and terminate these steps.
    2. Validate that all required members exist in handlerResponse and are well formed.
      1. If handlerResponse.methodName is not present or not set to one of the values from event.methodData, run the payment app failure algorithm and terminate these steps.
      2. If handlerResponse.details is not present or not JSON-serializable, run the payment app failure algorithm and terminate these steps.
    3. Serialize required members of handlerResponse ( methodName and details are always required.):
      1. For each memberin handlerResponseLet serializeMemberbe the result of StructuredSerializewith handlerResponse.member. Rethrow any exceptions.
    4. The user agent MUST run the user accepts the payment request algorithm as defined in [payment-request], replacing steps 9-15 with these steps or their equivalent.
      1. Deserialize serialized members:
        1. For each serializeMemberlet memberbe the result of StructuredDeserializewith serializeMember. Rethrow any exceptions.
      2. If any exception occurs in the above step, then run the payment app failure algorithm and terminate these steps.
      3. Assign methodName to associated PaymentRequest's response.methodName.
      4. Assign details to associated PaymentReqeust's response.details.
  10. Upon fulfillment or upon rejection of handlerResponsePromise, queue a microtask to perform the following steps:
    1. Decrement the event's pending promises count by one.
    2. Let registration be the this's relevant global object's associated service worker's containing service worker registration.
    3. If registration’s uninstalling flag is set, invoke Try Clear Registration with registration.
    4. If registration is not null, invoke Try Activate with registration.

The following example shows how to respond to a payment request:

Example 7: Sending a Payment Response
paymentRequestEvent.respondWith(new Promise(function(accept,reject) {
  /* ... processing may occur here ... */
  accept({
    methodName: "https://example.com/pay",
    details: {
      cardHolderName:   "John Smith",
      cardNumber:       "1232343451234",
      expiryMonth:      "12",
      expiryYear :      "2020",
      cardSecurityCode: "123"
     },
  });
}));
Note

[payment-request] defines an ID that parties in the ecosystem (including payment app providers and payees) can use for reconciliation after network or other failures.

8. Security and Privacy Considerations

8.1 Information about the User Environment

8.4 User Awareness about Sharing Data Cross-Origin

8.5 Secure Communications

8.6 Authorized Payment Apps

8.7 Supported Origin

8.8 Data Validation

8.9 Private Browsing Mode

9. Payment Handler Display Considerations

This section is non-normative.

When ordering payment handlers and payment instruments, the user agent is expected to honor user preferences over other preferences. User agents are expected to permit manual configuration options, such as setting a preferred payment handler or instrument display order for an origin, or for all origins.

User experience details are left to implementers.

10. Dependencies

This specification relies on several other underlying specifications.

Payment Request API
The terms payment method, PaymentRequest, PaymentResponse, supportedMethods, PaymentCurrencyAmount, paymentDetailsModifier, paymentDetailsInit, paymentDetailsBase, PaymentMethodData, PaymentMethodChangeEvent, PaymentRequestUpdateEvent, ID, canMakePayment(), show(), updateWith(detailsPromise), user accepts the payment request algorithm, payment method changed algorithm, PaymentRequest updated algorithm, and JSON-serializable are defined by the Payment Request API specification [payment-request].
ECMAScript
The terms internal slot and JSON.stringify are defined by [ECMASCRIPT].
Payment Method Manifest
The terms payment method manifest, ingest payment method manifest, parsed payment method manifest, and supported origins are defined by the Payment Method Manifest specification [payment-method-manifest].
Service Workers
The terms service worker, service worker registration, active worker, service worker client, ServiceWorkerRegistration, ServiceWorkerGlobalScope, fire functional event, extend lifetime promises,pending promises count, containing service worker registration, uninstalling flag, Try Clear Registration, Try Activate, ExtendableEvent, ExtendableEventInit, and scope URL are defined in [SERVICE-WORKERS].

11. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words MAY, MUST, SHOULD, and SHOULD NOT in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

There is only one class of product that can claim conformance to this specification: a user agent.

User agents MAY implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

User agents MAY impose implementation-specific limits on otherwise unconstrained inputs, e.g., to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations. When an input exceeds implementation-specific limit, the user agent MUST throw, or, in the context of a promise, reject with, a TypeError optionally informing the developer of how a particular input exceeded an implementation-specific limit.

A. IDL Index

WebIDLpartial interface ServiceWorkerRegistration {
  [SameObject] readonly attribute PaymentManager paymentManager;
};

[SecureContext, Exposed=(Window,Worker)]
interface PaymentManager {
  [SameObject] readonly attribute PaymentInstruments instruments;
  attribute DOMString userHint;
};

[SecureContext, Exposed=(Window,Worker)]
interface PaymentInstruments {
  Promise<boolean> delete(DOMString instrumentKey);
  Promise<any> get(DOMString instrumentKey);
  Promise<sequence<DOMString>>  keys();
  Promise<boolean> has(DOMString instrumentKey);
  Promise<undefined> set(DOMString instrumentKey, PaymentInstrument details);
  Promise<undefined> clear();
};

dictionary PaymentInstrument {
  required DOMString name;
  sequence<ImageObject> icons;
  DOMString method;
};

dictionary ImageObject {
    required USVString src;
    DOMString sizes;
    DOMString type;
};

partial interface ServiceWorkerGlobalScope {
  attribute EventHandler oncanmakepayment;
};

[Exposed=ServiceWorker]
interface CanMakePaymentEvent : ExtendableEvent {
  constructor(DOMString type, optional CanMakePaymentEventInit eventInitDict = {});
  readonly attribute USVString topOrigin;
  readonly attribute USVString paymentRequestOrigin;
  readonly attribute FrozenArray<PaymentMethodData> methodData;
  undefined respondWith(Promise<boolean> canMakePaymentResponse);
};

dictionary CanMakePaymentEventInit : ExtendableEventInit {
  USVString topOrigin;
  USVString paymentRequestOrigin;
  sequence<PaymentMethodData> methodData;
};

partial interface ServiceWorkerGlobalScope {
  attribute EventHandler onpaymentrequest;
};

dictionary PaymentRequestDetailsUpdate {
  DOMString error;
  PaymentCurrencyAmount total;
  sequence<PaymentDetailsModifier> modifiers;
  object paymentMethodErrors;
};

[Exposed=ServiceWorker]
interface PaymentRequestEvent : ExtendableEvent {
  constructor(DOMString type, optional PaymentRequestEventInit eventInitDict = {});
  readonly attribute USVString topOrigin;
  readonly attribute USVString paymentRequestOrigin;
  readonly attribute DOMString paymentRequestId;
  readonly attribute FrozenArray<PaymentMethodData> methodData;
  readonly attribute object total;
  readonly attribute FrozenArray<PaymentDetailsModifier> modifiers;
  Promise<WindowClient?> openWindow(USVString url);
  Promise<PaymentRequestDetailsUpdate?> changePaymentMethod(DOMString methodName, optional object? methodDetails = null);
  undefined respondWith(Promise<PaymentHandlerResponse> handlerResponsePromise);
};

dictionary PaymentRequestEventInit : ExtendableEventInit {
  USVString topOrigin;
  USVString paymentRequestOrigin;
  DOMString paymentRequestId;
  sequence<PaymentMethodData> methodData;
  PaymentCurrencyAmount total;
  sequence<PaymentDetailsModifier> modifiers;
};

dictionary PaymentHandlerResponse {
DOMString methodName;
object details;
};

B. References

B.1 Normative references

[appmanifest]
Web Application Manifest. Marcos Caceres; Kenneth Christiansen; Anssi Kostiainen; Matt Giuca; Aaron Gustafson. W3C. 25 August 2021. W3C Working Draft. URL: https://www.w3.org/TR/appmanifest/
[dom]
DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
[ECMASCRIPT]
ECMAScript Language Specification. Ecma International. URL: https://tc39.es/ecma262/multipage/
[HTML]
HTML Standard. Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[infra]
Infra Standard. Anne van Kesteren; Domenic Denicola. WHATWG. Living Standard. URL: https://infra.spec.whatwg.org/
[mimesniff]
MIME Sniffing Standard. Gordon P. Hemsley. WHATWG. Living Standard. URL: https://mimesniff.spec.whatwg.org/
[payment-method-id]
Payment Method Identifiers. Marcos Caceres. W3C. 30 September 2021. W3C Proposed Recommendation. URL: https://www.w3.org/TR/payment-method-id/
[payment-method-manifest]
Payment Method Manifest. Dapeng(Max) Liu; Domenic Denicola; Zach Koch. W3C. 12 December 2017. W3C Working Draft. URL: https://www.w3.org/TR/payment-method-manifest/
[payment-request]
Payment Request API. Marcos Caceres; Rouslan Solomakhin; Ian Jacobs. W3C. 30 September 2021. W3C Proposed Recommendation. URL: https://www.w3.org/TR/payment-request/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc2119
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc8174
[SERVICE-WORKERS]
Service Workers 1. Alex Russell; Jungkee Song; Jake Archibald; Marijn Kruisselbrink. W3C. 19 November 2019. W3C Candidate Recommendation. URL: https://www.w3.org/TR/service-workers-1/
[URL]
URL Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://url.spec.whatwg.org/
[WebIDL]
Web IDL. Boris Zbarsky. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/

B.2 Informative references

[WebCryptoAPI]
Web Cryptography API. Mark Watson. W3C. 26 January 2017. W3C Recommendation. URL: https://www.w3.org/TR/WebCryptoAPI/