This specification defines capabilities that enable Web applications to handle requests for payment.
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 specification defines a number of new features to allow web applications to handle requests for payments on behalf of users:
This specification does not address how software built with operating-system specific mechanisms (i.e., "native apps") handle payment requests.
In this document we envision the following flow:
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.
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 [[[WebCryptoAPI]]]) 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.
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.
One registers a payment handler with the user agent through a just-in-time (JIT) registration mechanism.
If a payment handler is not registered when a merchant invokes {{PaymentRequest/show()}} method, a user agent may allow the user to register this payment handler during the transaction ("just-in-time").
The remaining content of this section is non-normative.
A user agent may perform just-in-time installation by deriving payment handler information from the payment method manifest that is found through the URL-based payment method identifier that the merchant requested.
This section describes the functionality available to a payment handler to manage its own properties.
partial interface ServiceWorkerRegistration { [SameObject] readonly attribute PaymentManager paymentManager; };
The paymentManager attribute exposes payment handler management functionality.
[SecureContext, Exposed=(Window)] interface PaymentManager { attribute DOMString userHint; Promise<undefined> enableDelegations(sequence<PaymentDelegation> delegations); };
The {{PaymentManager}} is used by payment handlers to manage their supported delegations.
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.
This method allows a payment handler to asynchronously declare its supported PaymentDelegation list.
enum PaymentDelegation { "shippingAddress", "payerName", "payerPhone", "payerEmail" };
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 {{CanMakePaymentEvent/respondWith()}} was called with `false`.
partial interface ServiceWorkerGlobalScope { attribute EventHandler oncanmakepayment; };
The {{ServiceWorkerGlobalScope/oncanmakepayment}} attribute is an event handler whose corresponding event handler event type is "canmakepayment".
The CanMakePaymentEvent is used to as a signal for whether the payment handler is able to respond to a payment request.
[Exposed=ServiceWorker] interface CanMakePaymentEvent : ExtendableEvent { constructor(DOMString type); undefined respondWith(Promise<boolean> canMakePaymentResponse); };
This method is used by the payment handler as a signal for whether it can respond to a payment request.
Upon receiving a PaymentRequest, the user agent MUST run the following steps:
Fire Functional Event "canmakepayment
" using
CanMakePaymentEvent on registration.
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.
self.addEventListener("canmakepayment", function(e) { e.respondWith(new Promise(function(resolve, reject) { resolve(true); })); });
Given a PaymentMethodData and a payment handler that matches on
payment method identifier, this algorithm returns
true
if this payment handler can be used for payment:
"*"
string supported
origins in paymentMethodManifest, return
true
.
Once the user has selected a payment handler, the user agent fires a {{PaymentRequestEvent}} and uses the subsequent PaymentHandlerResponse to create a PaymentResponse for [[!payment-request]].
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.
This specification extends the ServiceWorkerGlobalScope interface.
partial interface ServiceWorkerGlobalScope { attribute EventHandler onpaymentrequest; };
The onpaymentrequest attribute is an event handler whose corresponding event handler event type is {{PaymentRequestEvent}}.
The PaymentRequestDetailsUpdate
contains the updated
total (optionally with modifiers and shipping options) and possible
errors resulting from user selection of a payment method, a shipping
address, or a shipping option within a payment handler.
dictionary PaymentRequestDetailsUpdate { DOMString error; PaymentCurrencyAmount total; sequence<PaymentDetailsModifier> modifiers; sequence<PaymentShippingOption> shippingOptions; object paymentMethodErrors; AddressErrors shippingAddressErrors; };
A human readable string that explains why the user selected payment method, shipping address or shipping option cannot be used.
Updated total based on the changed payment method, shipping address, or shipping option. The total can change, for example, because the billing address of the payment method selected by the user changes the Value Added Tax (VAT); Or because the shipping option/address selected/provided by the user changes the shipping cost.
Updated modifiers based on the changed payment method, shipping address, or shipping option. 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.
Updated shippingOptions based on the changed shipping address. For example, it is possible that express shipping is more expensive or unavailable for the user provided country.
Validation errors for the payment method, if any.
Validation errors for the shipping address, if any.
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.
[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; readonly attribute object? paymentOptions; readonly attribute FrozenArray<PaymentShippingOption>? shippingOptions; Promise<WindowClient?> openWindow(USVString url); Promise<PaymentRequestDetailsUpdate?> changePaymentMethod(DOMString methodName, optional object? methodDetails = null); Promise<PaymentRequestDetailsUpdate?> changeShippingAddress(optional AddressInit shippingAddress = {}); Promise<PaymentRequestDetailsUpdate?> changeShippingOption(DOMString shippingOption); undefined respondWith(Promise<PaymentHandlerResponse> handlerResponsePromise); };
Returns a string that indicates the origin of the top level payee web page. This attribute is initialized by Handling a PaymentRequestEvent.
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.
When getting, the paymentRequestId attribute returns the {{ PaymentRequest/[[details]] }}.id from the PaymentRequest that corresponds to this {{PaymentRequestEvent}}.
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.
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.
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.
The value of PaymentOptions in the PaymentRequest. Available only when shippingAddress and/or any subset of payer's contact information are requested.
The value of ShippingOptions in the PaymentDetailsInit dictionary of the corresponding PaymentRequest.(PaymentDetailsInit inherits ShippingOptions from PaymentDetailsBase). Available only when shipping address is requested.
This method is used by the payment handler to show a window to the user. When called, it runs the open window algorithm.
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.
This method is used by the payment handler to get updated payment details given the shippingAddress. When called, it runs the change payment details algorithm.
This method is used by the payment handler to get updated payment details given the shippingOption identifier. When called, it runs the change payment details algorithm.
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.
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.
dictionary PaymentRequestEventInit : ExtendableEventInit { USVString topOrigin; USVString paymentRequestOrigin; DOMString paymentRequestId; sequence<PaymentMethodData> methodData; PaymentCurrencyAmount total; sequence<PaymentDetailsModifier> modifiers; PaymentOptions paymentOptions; sequence<PaymentShippingOption> shippingOptions; };
The topOrigin, paymentRequestOrigin, paymentRequestId, methodData, total, modifiers, paymentOptions, and shippingOptions members share their definitions with those defined for {{PaymentRequestEvent}}
To initialize the value of the methodData, the user agent MUST perform the following steps or their equivalent:
To initialize the value of the modifiers, the user agent MUST perform the following steps or their equivalent:
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. |
[[\respondWithCalled]] | false | YAHO |
Upon receiving a PaymentRequest by way of PaymentRequest.show() and subsequent user selection of a payment handler, the user agent MUST run the following steps:
Fire Functional Event "paymentrequest
" using
{{PaymentRequestEvent}} on registration with the
following properties:
Then run the following steps in parallel, with dispatchedEvent:
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.
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.
This algorithm resembles the Open Window Algorithm in the Service Workers specification.
Should we refer to the Service Workers specification instead of copying their steps?
about:blank
, return a
{{Promise}} rejected with a {{TypeError}}.
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.
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:
<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>
dictionary PaymentHandlerResponse { DOMString methodName; object details; DOMString? payerName; DOMString? payerEmail; DOMString? payerPhone; AddressInit shippingAddress; DOMString? shippingOption; };
The payment method identifier for the payment method that the user selected to fulfil the transaction.
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 {{PaymentRequestEvent/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:
The user provided payer's name.
The user provided payer's email.
The user provided payer's phone number.
The user provided shipping address.
The identifier of the user selected shipping option.
When this algorithm is invoked with methodName and methodDetails parameters, the user agent MUST run the following steps:
null
.
When this algorithm is invoked with shippingAddress or shippingOption the user agent MUST run the following steps:
null
.
When this algorithm is invoked with |event| and handlerResponsePromise parameters, the user agent MUST run the following steps:
The following example shows how to respond to a payment request:
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" }, shippingAddress: { addressLine: [ "1875 Explorer St #1000", ], city: "Reston", country: "US", dependentLocality: "", organization: "", phone: "+15555555555", postalCode: "20190", recipient: "John Smith", region: "VA", sortingCode: "" }, shippingOption: "express", payerEmail: "[email protected]", }); }));
[[!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.
The Web Payments Working Group removed support for shipping and billing addresses from the original version of Payment Request API due to privacy issues; see issue 842. In order to provide documentation for implementations that continue to support this capability, the Working Group is now restoring the feature with an expectation of addressing privacy issues. In doing so the Working Group may also make changes to Payment Request API based on the evolution of other APIs (e.g., the Content Picker API).
When a payment handler is unavailable for security reasons, the user agent should provide rationale to the payment handler developers (e.g., through console messages) and may also inform the user to help avoid confusion.
When ordering payment handlers, 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 display order for an origin, or for all origins.
User experience details are left to implementers.
This specification relies on several other underlying specifications.
JSON.stringify
are
defined by [[!ECMASCRIPT]].
ServiceWorkerRegistration
,
ServiceWorkerGlobalScope
,
fire
functional event, extend lifetime
promises,pending promises
count, containing
service worker registration,
Try
Clear Registration, Try Activate,
ExtendableEvent,
ExtendableEventInit,
and scope URL
are defined in [[!SERVICE-WORKERS]].
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.