This specification standardizes an API to allow merchants (i.e. web sites selling physical or digital goods) to utilize one or more payment methods with minimal integration. User agents (e.g., browsers) facilitate the payment flow between merchant and user.
The working group maintains a list of all bug reports that the group has not yet addressed. Pull requests with proposed specification text for outstanding issues are strongly encouraged.
This specification was derived from a report published previously by the Web Platform Incubator Community Group.
Sending comments on this document
If you wish to make comments regarding this document, please raise them as GitHub issues. Only send comments by email if you are unable to raise issues on GitHub (see links below). All comments are welcome.
Buying things on the web, particularly on mobile, can be a frustrating experience for users. Every web site has its own flow and its own validation rules, and most require users to manually type in the same set of information over and over again. Likewise, it is difficult and time consuming for developers to create good checkout flows that support various payment schemes.
This specification describes an API that allows user agents (e.g., browsers) to act as an intermediary between three systems in every transaction: the merchant (e.g., an online web store), the buyer represented by the user agent (e.g., the user buying from the online web store), and the payment method (e.g., credit card). Information necessary to process and confirm a transaction is passed between the payment method and the merchant via the user agent with the buyer confirming and authorizing as necessary across the flow.
The details of how to fulfill a payment request for a given payment method are handled by payment apps. In this specification, these details are left up to the user agent, but future specifications may expand on the processing model in more detail.
In addition to better, more consistent user experiences, this also enables web sites to take advantage of more secure payment schemes (e.g., tokenization and system-level authentication) that are not possible with standard JavaScript libraries. This has the potential to reduce liability for the merchant and helps protect sensitive user information.
A string is a valid decimal monetary value if it consists of the following components in the given order:
^-?[0-9]+(\.[0-9]+)?$
[Constructor(sequence<PaymentMethodData> methodData, PaymentDetails details, optional PaymentOptions options), SecureContext] interface PaymentRequest : EventTarget { Promise<PaymentResponse> show(); Promise<void> abort(); Promise<boolean> canMakePayment(); readonly attribute DOMString? paymentRequestID; readonly attribute PaymentAddress? shippingAddress; readonly attribute DOMString? shippingOption; readonly attribute PaymentShippingType? shippingType; attribute EventHandler onshippingaddresschange; attribute EventHandler onshippingoptionchange; };
A web page creates a PaymentRequest to make a payment request. This is typically associated with the user initiating a payment process (e.g., selecting a "Power Up" in an interactive game, pulling up to an automated kiosk in a parking structure, or activating a "Buy", "Purchase", or "Checkout" button). The PaymentRequest allows the web page to exchange information with the user agent while the user is providing input before approving or denying a payment request.
The shippingAddress, shippingOption, and shippingType attributes are populated during processing if the requestShipping flag is set.
The [SecureContext]
extended attribute means that
the PaymentRequest is only exposed within a secure
context and won't be accessible elsewhere.
The following example shows how to construct a PaymentRequest and begin the user interaction:
function validateResponse(response){ // check that the response is ok... throw if bad, for example. } async function doPaymentRequest() { const payment = new PaymentRequest(methodData, details, options); payment.addEventListener("shippingaddresschange", event => { // Process shipping address change }); let paymentResponse; try { paymentResponse = await payment.show(); // paymentResponse.methodName contains the selected payment method. // paymentResponse.details contains a payment method specific // response. validateResponse(paymentResponse); paymentResponse.complete("success"); } catch (err) { console.error("Uh oh, bad payment response!", err.message); paymentResponse.complete("fail"); } } doPaymentRequest();
The PaymentRequest is constructed using the supplied methodData list including any payment method specific data, the payment details, and the payment options. The methodData supplied to the PaymentRequest constructor SHOULD be in the order of preference of the caller.
The methodData sequence contains PaymentMethodData dictionaries containing the payment method identifiers for the payment methods that the web site accepts and any associated payment method specific data.
const methodData = [{ supportedMethods: ["basic-card"], data: { supportedNetworks: ['aFamousBrand', 'aDebitNetwork'], supportedTypes: ['debit'] } }, { supportedMethods: ["bobpay.com"], data: { merchantIdentifier: "XXXX", bobPaySpecificField: true } }]; const request = new PaymentRequest(methodData, details, options);
The details object contains information about the transaction that the user is being asked to complete such as the line items in an order.
const details = { displayItems: [ { label: "Sub-total", amount: { currency: "USD", value : "55.00" }, // US$55.00 }, { label: "Sales Tax", amount: { currency: "USD", value : "5.00" }, // US$5.00 } ], total: { label: "Total due", amount: { currency: "USD", value : "60.00" }, // US$60.00 } } const request = new PaymentRequest(methodData, details, options);
The options object contains information about what options the web page wishes to use from the payment request system.
const options = { requestShipping: true } const request = new PaymentRequest(methodData, details, options);
The PaymentRequest constructor MUST act as follows:
paymentRequestID
was not provided during
construction, generate a paymentRequestID
.
sequence
<PaymentShippingOption>.
sequence
<PaymentDetailsModifier>.
shipping
".
The show() method is called when the page wants to begin user interaction for the payment request. The show() method returns a Promise that will be resolved when the user accepts the payment request. Some kind of user interface will be presented to the user to facilitate the payment request after the show() method returns.
The show() method MUST act as follows:
Otherwise, show a user interface to allow the user to interact with the payment request process, using those payment apps and payment methods which the above step identified as feasible. The user agent MAY show payment methods in the order given by supportedMethods, but SHOULD prioritize the preference of the user when presenting payment methods and applications.
The acceptPromise will later be resolved by the user accepts the payment request algorithm through interaction with the user interface.
The abort() method may be called if the web page wishes to tell the user agent to abort the payment request and to tear down any user interface that might be shown. abort() can only be called after the show() method has been called and before this instance's [[\acceptPromise]] has been resolved. For example, a web page might choose to do this if the goods they are selling are only available for a limited amount of time. If the user does not accept the payment request within the allowed time period, then the request will be aborted.
A user agent might not always be able to abort a request. For example, if the user agent has delegated responsibility for the request to another app. In this situation, abort() will reject the returned Promise.
The abort() method MUST act as follows:
The canMakePayment() method can be used by the developer to determine if the PaymentRequest object can be used to make a payment, before they call show(). It returns a Promise that will be fulfilled with true if the user agent supports any of the desired payment methods supplied to the PaymentRequest constructor, and false if none are supported. If the method is called too often, the user agent might instead return a promise rejected with a "QuotaExceededError" DOMException, at its discretion.
The canMakePayment() method MUST act as follows:
This allows user agents to apply heuristics to detect and prevent abuse of the canMakePayment() method for fingerprinting purposes, such as creating PaymentRequest objects with a variety of supported payment methods and calling canMakePayment() on them one after the other. For example, a user agent may restrict the number of successful calls that can be made based on the top-level browsing context or the time period in which those calls were made.
The internal slot [[\state]] follows the following state transitions:
shippingAddress is populated when the user provides a shipping address. It is null by default. When a user provides a shipping address, the shipping address changed algorithm runs.
onshippingaddresschange is an EventHandler
for an Event
named shippingaddresschange
.
shippingOption is populated when the user chooses a shipping option. It is null by default. When a user chooses a shipping option, the shipping option changed algorithm runs.
onshippingoptionchange is an EventHandler
for
an Event
named shippingoptionchange
.
Instances of PaymentRequest are created with the internal slots in the following table:
Internal Slot | Description (non-normative) |
---|---|
[[\parsedMethodData]] |
The methodData supplied to the constructor, but
represented as tuples containing supported methods and a string
or null for data (instead of the original object form).
|
[[\details]] | The current PaymentDetails for the payment request initially supplied to the constructor and then updated with calls to updateWith(). |
[[\options]] | The PaymentOptions supplied to the constructor. |
[[\state]] | The current state of the payment request. |
[[\updating]] | true is there is a pending updateWith() call to update the payment request and false otherwise. |
[[\acceptPromise]] | The pending Promise created during show that will be resolved if the user accepts the payment request. |
dictionary PaymentMethodData { required sequence<DOMString> supportedMethods; object data; };
A PaymentMethodData dictionary is used to indicate a set of supported payment methods and any associated payment method specific data for those methods.
The following fields are part of the PaymentMethodData dictionary:
dictionary PaymentCurrencyAmount { required DOMString currency; required DOMString value; DOMString currencySystem = "urn:iso:std:iso:4217"; };
A PaymentCurrencyAmount dictionary is used to supply monetary amounts.
The following fields are required:
urn:iso:std:iso:4217
indicating that currency is
defined by [[ISO4217]] (for example, USD
for US
Dollars).
The following example shows how to represent US$55.00.
{ "currency": "USD", "value" : "55.00" }
dictionary PaymentDetails { PaymentItem total; sequence<PaymentItem> displayItems; sequence<PaymentShippingOption> shippingOptions; sequence<PaymentDetailsModifier> modifiers; DOMString error; };
The PaymentDetails dictionary is passed to the PaymentRequest constructor and provides information about the requested transaction. The PaymentDetails dictionary is also used to update the payment request using updateWith().
The following fields are part of the PaymentDetails dictionary:
total
MUST be a non-negative value. This means that
the total.amount.value
field MUST NOT begin with a
U+002D HYPHEN-MINUS character.
It is the developer's responsibility to verify that the total amount is the sum of these items.
If the sequence is empty, then this indicates that the merchant cannot ship to the current shippingAddress.
If an item in the sequence has the selected
field set
to true, then this is the shipping option that will be used by
default and shippingOption will be set to
the id
of this option without running the shipping
option changed algorithm. Authors SHOULD NOT set
selected
to true on more than one item. If more than
one item in the sequence has selected
set to true,
then user agents MUST select the last one in the sequence.
The shippingOptions
field is only used if the
PaymentRequest was constructed with PaymentOptions
requestShipping set
to true.
If the sequence has an item with the selected
field
set to true, then authors are responsible for ensuring that the
total
field includes the cost of the shipping option.
This is because no shippingoptionchange event will be fired
for this option unless the user selects an alternative option
first.
error
field that will be displayed to the user. For example, this might
commonly be used to explain why goods cannot be shipped to the chosen
shipping address.
The error
field cannot be passed to the
PaymentRequest constructor. Doing so will cause a
TypeError to be thrown.
dictionary PaymentDetailsModifier { required sequence<DOMString> supportedMethods; PaymentItem total; sequence<PaymentItem> additionalDisplayItems; object data; };
The PaymentDetailsModifier dictionary provides details that modify the PaymentDetails based on payment method identifier. It contains the following fields:
total
field
in the PaymentDetails dictionary for the payment method
identifiers in the supportedMethods
field.
displayItems
field in the PaymentDetails dictionary for the payment
method identifiers in the supportedMethods
field.
This field is commonly used to add a discount or surcharge line item
indicating the reason for the different total
amount for
the selected payment method that the user agent MAY display.
It is the developer's responsibility to verify that the total amount is the sum of the displayItems and the additionalDisplayItems.
data
is a JSON-serializable object that provides
optional information that might be needed by the supported payment
methods.
enum PaymentShippingType { "shipping", "delivery", "pickup" };
dictionary PaymentOptions { boolean requestPayerName = false; boolean requestPayerEmail = false; boolean requestPayerPhone = false; boolean requestShipping = false; DOMString shippingType = "shipping"; };
The PaymentOptions dictionary is passed to the PaymentRequest constructor and provides information about the options desired for the payment request.
The following fields MAY be passed to the PaymentRequest constructor:
requestShipping
is set to true, then the
shippingType
field may be used to influence the way the
user agent presents the user interface for gathering the
shipping address.
The shippingType
field only affects the user interface
for the payment request.
dictionary PaymentItem { required DOMString label; required PaymentCurrencyAmount amount; boolean pending = false; };
A sequence of one or more PaymentItem dictionaries is included in the PaymentDetails dictionary to indicate what the payment request is for and the value asked for.
The following fields are required:
amount
field
is not final. This is commonly used to show items such as shipping or
tax amounts that depend upon selection of shipping address or
shipping option. User agents MAY indicate pending fields in
the user interface for the payment request.
[SecureContext] interface PaymentAddress { serializer = { attribute }; readonly attribute DOMString country; readonly attribute FrozenArray<DOMString> addressLine; readonly attribute DOMString region; readonly attribute DOMString city; readonly attribute DOMString dependentLocality; readonly attribute DOMString postalCode; readonly attribute DOMString sortingCode; readonly attribute DOMString languageCode; readonly attribute DOMString organization; readonly attribute DOMString recipient; readonly attribute DOMString phone; };
If the requestShipping
flag was set to true in the PaymentOptions passed to the
PaymentRequest constructor, then the user agent will
populate the shippingAddress
field of the
PaymentRequest and ultimately the PaymentResponse object
with the user's selected shipping address after the user has accepted
the payment.
dictionary PaymentShippingOption { required DOMString id; required DOMString label; required PaymentCurrencyAmount amount; boolean selected = false; };
The PaymentShippingOption dictionary has fields describing a shipping option. A web page can provide the user with one or more shipping options by calling the updateWith() method in response to a change event.
The following fields are required:
enum PaymentComplete { "fail", "success", "unknown", };
[SecureContext] interface PaymentResponse { serializer = { attribute }; readonly attribute DOMString paymentRequestID; readonly attribute DOMString methodName; readonly attribute object details; readonly attribute PaymentAddress? shippingAddress; readonly attribute DOMString? shippingOption; readonly attribute DOMString? payerName; readonly attribute DOMString? payerEmail; readonly attribute DOMString? payerPhone; Promise<void> complete(optional PaymentComplete result = "unknown"); };
A PaymentResponse is returned when a user has selected a payment method and approved a payment request. It contains the following fields:
id
attribute of the selected shipping option.
The complete() method is called after the user has accepted the payment request and the [[\acceptPromise]] has been resolved. Calling the complete() method tells the user agent that the user interaction is over (and SHOULD cause any remaining user interface to be closed).
After the payment request has been accepted and the PaymentResponse returned to the page but before the page calls complete() the payment request user interface remains in a pending state. At this point the user interface ought not offer a cancel command because acceptance of the payment request has been returned. However, if something goes wrong and the page never calls complete() then the user interface is blocked.
For this reason, implementations may choose to impose a timeout for the page to call complete(). If the timeout expires then the implementation will behave as if complete() was called with no arguments.
The complete(result) method MUST act as follows:
Instances of PaymentResponse are created with the internal slots in the following table:
Internal Slot | Description (non-normative) |
---|---|
[[\completeCalled]] | true if the complete method has been called and false otherwise. |
iframe
elements
To indicate that a cross-origin iframe
is allowed
to invoke the payment request API, the
allowpaymentrequest
attribute can be specified on
the iframe
element.
Event name | Interface | Dispatched when... |
---|---|---|
shippingaddresschange
|
PaymentRequestUpdateEvent | The user provides a new shipping address. |
shippingoptionchange
|
PaymentRequestUpdateEvent | The user chooses a new shipping option. |
[Constructor(DOMString type, optional PaymentRequestUpdateEventInit eventInitDict),SecureContext] interface PaymentRequestUpdateEvent : Event { void updateWith(Promise<PaymentDetails> detailsPromise); };
The PaymentRequestUpdateEvent enables the web page to update the details of the payment request in response to a user interaction.
If the web page wishes to update the payment request then it should call updateWith() and provide a promise that will resolve with a PaymentDetails dictionary containing changed values that the user agent SHOULD present to the user.
The PaymentRequestUpdateEvent constructor MUST set the internal slot [[\waitForUpdate]] to false.
The updateWith(detailsPromise) method MUST act as follows:
target
attribute.
The user agent SHOULD disable any part of the user interface that could cause another update event to be fired. Only one update may be processed at a time.
Return from the method and perform the remaining steps in parallel.
The remaining steps are conditional on the detailsPromise settling. If detailsPromise never settles then the payment request is blocked. Users should always be able to cancel a payment request. Implementations may choose to implement a timeout for pending updates if detailsPromise doesn't settle in a reasonable amount of time. If an implementation chooses to implement a timeout, they must execute the steps listed below in the "upon rejection" path. Such a timeout is a fatal error for the payment request.
User agents might show an error message to the user when this occurs.
Instances of PaymentRequestUpdateEvent are created with the internal slots in the following table:
Internal Slot | Description (non-normative) |
---|---|
[[\waitForUpdate]] | A boolean indicating whether an updateWith()-initiated update is currently in progress. |
dictionary PaymentRequestUpdateEventInit : EventInit {};
When the internal slot [[\state]] of a PaymentRequest object is set to interactive, the user agent will trigger the following algorithms based on user interaction.
The shipping address changed algorithm runs when the user provides a new shipping address. It MUST run the following steps:
The shipping option changed algorithm runs when the user chooses a new shipping option. It MUST run the following steps:
id
string of the
PaymentShippingOption provided by the user.
The PaymentRequest updated algorithm is run by other algorithms above to fire an event to indicate that a user has made a change to a PaymentRequest called request with an event name of name.
It MUST run the following steps:
The user accepts the payment request algorithm runs when the user accepts the payment request and confirms that they want to pay. It MUST run the following steps:
requestShipping
value of
request.[[\options]] is true, then copy the
shippingAddress
attribute of request to the
shippingAddress
attribute of response, or to null
if none
was provided.
requestShipping
value of
request.[[\options]] is true, then copy the
shippingOption
attribute of request to the
shippingOption
attribute of response, or to null
if none
was provided.
requestPayerName
value of
request.[[\options]] is true, then set the
payerName attribute of
response to the payer's name provided by the user, or to
null
if none was provided.
null
if none was provided.
payerPhone
attribute of response to the
payer's phone number selected by the user, or to null
if
none was provided. When setting the payerPhone value, the user agent
SHOULD format the phone number to adhere to [[!E.164]].
This section is a placeholder to record security considerations as we gather them through working group discussion.
The PaymentRequest API does not directly support encryption of data fields. Individual payment methods may choose to include support for encrypted data but it is not mandatory that all payment methods support this.
This section is a placeholder to record privacy considerations as we gather them through working group discussion.
The user agent MUST NOT share information about the user to the web page (such as the shipping address) without user consent.
A page might try to call the payment request API repeatedly with only one payment method identifier to try to determine what payment methods a user agent has installed. There may be legitimate scenarios for calling repeatedly (for example, to control the order of payment method selection). The fact that a successful match to a payment method causes a user interface to be displayed mitigates the disclosure risk. Implementations may also require a user action to initiate a payment request or they may choose to rate limit the calls to the API to prevent too many repeated calls.
This specification relies on several other underlying specifications.
TypeError
, JSON.stringify, and
JSON.parse are defined by [[!ECMA-262-2015]].
The term JSON-serializable object used in this specification is not well defined; see issue #307.
The term JSON-serialize applied to a given object means to run the algorithm specified by the original value of the JSON.stringify function on the supplied object, passing the supplied object as the sole argument, and return the resulting string. This can throw an exception.
The term extended attribute is defined by [[!WEBIDL-2]].
The algorithm for converting an ECMAScript value to a dictionary and for converting a dictionary to an ECMAScript value is defined by [[!WEBIDL-2]].
DOMException
and the
following DOMException types from [[!WEBIDL-2]] are used:
Type | Message (optional) |
---|---|
AbortError
|
The payment request was aborted |
InvalidStateError
|
The object is in an invalid state |
NotSupportedError
|
The payment method was not supported |
QuotaExceededError
|
The canMakePayment() method was called too often according to the user agent's heuristics. |
SecurityError
|
The operation is only supported in a secure context |
There is only one class of product that can claim conformance to this specification: a user agent.
Although this specification is primarily targeted at web browsers, it is feasible that other software could also implement this specification in a conforming manner.
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.