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.
The deadline for comments for Candidate Recommendation is 30 September 2017.
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.
As this specification enters the Candidate Recommendation phase of the W3C standardization process, the working group has identified the following feature(s) as being "at risk" of being removed from the specification. The working group seeks input from implementers, developers, and the general public on whether these features should remain in the specification. If no compelling use cases are received, or if there is limited interest from implementers, these features will be removed from the specification before proceeding along the W3C Recommendation track.
This specification describes an API that allows user agents (e.g., browsers) to act as an intermediary between three parties in a transaction:
The details of how to fulfill a payment request for a given payment method are handled by payment handlers. In this specification, these details are left up to the user agent, but future specifications may expand on the processing model in more detail.
This API 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 JavaScript string is a valid decimal monetary value if it consists of the following code points in the given order: [[!INFRA]]
^-?[0-9]+(\.[0-9]+)?$
[Constructor(sequence<PaymentMethodData> methodData, PaymentDetailsInit details, optional PaymentOptions options), SecureContext] interface PaymentRequest : EventTarget { Promise<PaymentResponse> show(); Promise<void> abort(); Promise<boolean> canMakePayment(); readonly attribute DOMString id; readonly attribute PaymentAddress? shippingAddress; readonly attribute DOMString? shippingOption; readonly attribute PaymentShippingType? shippingType; attribute EventHandler onshippingaddresschange; attribute EventHandler onshippingoptionchange; };
A developer creates a PaymentRequest to make a payment request. This is typically associated with the user initiating a payment process (e.g., by activating a "Buy," "Purchase," or "Checkout" button on a web site, selecting a "Power Up" in an interactive game, or paying at a kiosk in a parking structure). The PaymentRequest allows developers to exchange information with the user agent while the user is providing input before approving or denying a payment request.
The user agent as a whole has a single payment request is showing boolean, initially false. This is used to prevent multiple PaymentRequests from being shown, via their show() method, at the same time.
The shippingAddress, shippingOption, and shippingType attributes are populated during processing if the requestShipping flag is set.
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 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: ['visa', 'mastercard'], supportedTypes: ['debit'] } }, { supportedMethods: "https://example.com/bobpay", 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 = { id: "super-store-order-123-12312", 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 the developer needs from the user to perform the payment (e.g., the payer's name and shipping address).
const options = { requestShipping: true } const request = new PaymentRequest(methodData, details, options);
The PaymentRequest(methodData, details, options) constructor MUST act as follows:
sequence
<PaymentShippingOption>.
sequence
<PaymentDetailsModifier>.
When getting, the id attribute returns this PaymentRequest's [[\details]].id.
The show() method is called when a developer 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.
It is not possible to show multiple PaymentRequests at the same time within one user agent. Calling show() if another PaymentRequest is already showing, even due to some other site, will return a promise rejected with an "AbortError" DOMException.
The show() method MUST act as follows:
Optionally, if the user agent wishes to disallow the call to show() to protect the user, then return a promise rejected with a "SecurityError" DOMException. For example, the user agent may require the call to be triggered by user activation, or may limit the rate at which a page can call show(), as described in the the privacy considerations section.
During the Candidate Recommendation phase, implementations are expected to experiment in this area. Developers using this API should investigate and anticipate such experiments and understand under what circumstances a "SecurityError" DOMException might occur. If interoperable behavior emerges amongst user agents, then that behavior will be standardized here before progressing the specification along the W3C Recommendation Track.
Optionally:
This allows the user agent to act as if the user had immediately aborted the payment request, at its discretion. For example, in "private browsing" modes or similar, user agents might take advantage of this step.
Otherwise, show a user interface to allow the user to interact with the payment request process, using those payment handlers and payment methods which the above step identified as feasible. The user agent SHOULD prioritize the preference of the user when presenting payment methods and applications.
The payment handler should be sent the appropriate data from request in order to guide the user through the payment process. This includes the various attributes and internal slots of request.
The acceptPromise will later be resolved or rejected by either the user accepts the payment request algorithm or the user aborts the payment request algorithm, which are triggered through interaction with the user interface.
The abort() method is called if a developer wishes to tell the user agent to abort the payment request and to tear down any user interface that might be shown. The abort() can only be called after the show() method has been called (see states) and before this instance's [[\acceptPromise]] has been resolved. For example, developers 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 "NotAllowedError" 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.
A PaymentRequest's shippingAddress attribute 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.
A PaymentRequest's onshippingaddresschange attribute is an EventHandler for an Event named shippingaddresschange.
A PaymentRequest's shippingOption attribute 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.
A PaymentRequest's onshippingoptionchange attribute 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) |
---|---|
[[\serializedMethodData]] |
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).
|
[[\serializedModifierData]] | A list containing the serialized string form of each data member for each corresponding item in the sequence [[\details]].modifier, or null if no such member was present. |
[[\details]] | The current PaymentDetailsBase for the payment request initially supplied to the constructor and then updated with calls to updateWith(). Note that all data members of PaymentDetailsModifier instances contained in the modifiers member will be removed, as they are instead stored in serialized form in the [[\serializedModifierData]] internal slot. |
[[\options]] | The PaymentOptions supplied to the constructor. |
[[\state]] |
The current state of the payment request, which transitions from:
The state transitions are illustrated in the figure below: |
[[\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 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 members are part of the PaymentMethodData dictionary:
dictionary PaymentCurrencyAmount { required DOMString currency; required DOMString value; // Note: currencySystem is "at risk" of being removed! DOMString currencySystem = "urn:iso:std:iso:4217"; };
A PaymentCurrencyAmount dictionary is used to supply monetary amounts.
This feature has been marked "at risk". If you'd like for this feature to remain in the specification, please describe your use case in issue 490.
The following example shows how to represent US$55.00.
{ "currency": "USD", "value" : "55.00" }
dictionary PaymentDetailsBase { sequence<PaymentItem> displayItems; sequence<PaymentShippingOption> shippingOptions; sequence<PaymentDetailsModifier> modifiers; };
The following members are part of the PaymentDetailsBase dictionary:
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 member 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 member is only used if the PaymentRequest was constructed with PaymentOptions requestShipping set to true.
If the sequence has an item with the selected member set to true, then authors are responsible for ensuring that the total member 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.
dictionary PaymentDetailsInit : PaymentDetailsBase { DOMString id; required PaymentItem total; };
The PaymentDetailsInit dictionary is used in the construction of the payment request.
In addition to the members inherited from the PaymentDetailsBase dictionary, the following members are part of the PaymentDetailsInit dictionary:
If an id member is not present, then the user agent will generate a unique identifier for the payment request during construction.
Algorithms in this specification that accept a PaymentDetailsInit dictionary will throw if the total.amount.value is a negative number.
dictionary PaymentDetailsUpdate : PaymentDetailsBase { DOMString error; PaymentItem total; };
The PaymentDetailsUpdate dictionary is used to update the payment request using updateWith().
In addition to the members inherited from the PaymentDetailsBase dictionary, the following members are part of the PaymentDetailsUpdate dictionary:
Algorithms in this specification that accept a PaymentDetailsUpdate dictionary will throw if the total.amount.value is a negative number.
dictionary PaymentDetailsModifier { required DOMString supportedMethods; PaymentItem total; sequence<PaymentItem> additionalDisplayItems; object data; };
The PaymentDetailsModifier dictionary provides details that modify the PaymentDetailsBase based on a payment method identifier. It contains the following members:
It is the developer's responsibility to verify that the total amount is the sum of the displayItems and the additionalDisplayItems.
enum PaymentShippingType { "shipping", "delivery", "pickup" };
dictionary PaymentOptions { boolean requestPayerName = false; boolean requestPayerEmail = false; boolean requestPayerPhone = false; boolean requestShipping = false; PaymentShippingType shippingType = "shipping"; };
The PaymentOptions dictionary is passed to the PaymentRequest constructor and provides information about the options desired for the payment request.
The shippingType member 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 PaymentDetailsBase dictionary to indicate what the payment request is for and the value asked for.
[SecureContext] interface PaymentAddress { [Default] object toJSON(); 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; };
When called, run [[!WEBIDL]]'s default toJSON operation.
This is the [[!CLDR]] (Common Locale Data Repository) region code. For example, US, GB, CN, or JP.
This is the most specific part of the address. It can include, for example, a street name, a house number, apartment number, a rural delivery route, descriptive instructions, or a post office box number.
This is the top level administrative subdivision of the country. For example, this can be a state, a province, an oblast, or a prefecture.
This is the city/town portion of the address.
This is the dependent locality or sublocality within a city. For example, used for neighborhoods, boroughs, districts, or UK dependent localities.
This is the postal code or ZIP code, also known as PIN code in India.
This is the sorting code as used in, for example, France.
This is the [[!BCP47]] language code for the address. It's used to determine the field separators and the order of fields when formatting the address for display.
This is the organization, firm, company, or institution at this address.
This is the name of the recipient or contact person. This member may, under certain circumstances, contain multiline information. For example, it might contain "care of" information.
This is the phone number of the recipient or contact person.
dictionary PaymentShippingOption { required DOMString id; required DOMString label; required PaymentCurrencyAmount amount; boolean selected = false; };
The PaymentShippingOption dictionary has members describing a shipping option. Developers can provide the user with one or more shipping options by calling the updateWith() method in response to a change event.
enum PaymentComplete { "fail", "success", "unknown" };
[SecureContext] interface PaymentResponse { [Default] object toJSON(); readonly attribute DOMString requestId; 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.
When called, run [[!WEBIDL]]'s default toJSON operation.
The payment method identifier for the payment method that the user selected to fulfill the transaction.
An object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. This data is returned by the payment method specific code that satisfies the payment request.
If the requestShipping flag was set to true in the PaymentOptions passed to the PaymentRequest constructor, then shippingAddress will be the full and final shipping address chosen by the user.
If the requestShipping flag was set to true in the PaymentOptions passed to the PaymentRequest constructor, then shippingOption will be the id attribute of the selected shipping option.
If the requestPayerName flag was set to true in the PaymentOptions passed to the PaymentRequest constructor, then payerName will be the name provided by the user.
If the requestPayerEmail flag was set to true in the PaymentOptions passed to the PaymentRequest constructor, then payerEmail will be the email address chosen by the user.
If the requestPayerPhone flag was set to true in the PaymentOptions passed to the PaymentRequest constructor, then payerPhone will be the phone number chosen by the user.
The corresponding payment request id that spawned this payment response.
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 transaction 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 caller but before the caller 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 developer never calls complete() then the user interface is blocked.
For this reason, implementations MAY impose a timeout for developers 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. |
PaymentRequest
and 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<PaymentDetailsUpdate> detailsPromise); };
The PaymentRequestUpdateEvent enables developers to update the details of the payment request in response to a user interaction.
If a developer wants to update the payment request, then they need to call updateWith() and provide a PaymentDetailsUpdate dictionary, or a promise for one, containing changed values that the user agent SHOULD present to the user.
The PaymentRequestUpdateEvent constructor MUST set the internal slot [[\waitForUpdate]] to false.
If a developer wants to update the payment request, then they need to call updateWith() and provide a PaymentDetailsUpdate dictionary, or a promise for one, containing changed values that the user agent presents to the user.
The updateWith(detailsPromise) method MUST act as follows:
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.
sequence
<PaymentShippingOption>.
If any of the above steps say to abort the update with an exception exception, then:
Aborting the update is performed when there is a fatal error updating the payment request, such as the supplied detailsPromise rejecting, or its fulfillment value containing invalid data. This would potentially leave the payment request in an inconsistent state since the developer hasn't successfully handled the change event. Consequently, the PaymentRequest moves to a "closed" state. The error is signaled to the developer through the rejection of the [[\acceptPromise]], i.e. the promise returned by show().
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 queue a task on the user interaction task source to perform the following steps:
The user aborts the payment request algorithm runs when the user aborts the payment request through the currently interactive user interface. It MUST queue a task on the user interaction task source to perform the following steps:
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 with a developer (e.g., the shipping address) without user consent.
Developers 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 flow 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.
EventHandler
iframe
element
allowpaymentrequest
attribute
TypeError
, and JSON.stringify
are
defined by [[!ECMA-262-2015]].
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.
Event
interface,
The EventInit
dictionary, and the
terms fire an event,
dispatch flag,
stop propagation
flag, isTrusted
attribute, and
stop immediate
propagation flag are defined by [[!DOM]].
When this specification says to throw an error, the user agent must throw an error as described in [[!WEBIDL]]. When this occurs in a sub-algorithm, this results in termination of execution of the sub-algorithm and all ancestor algorithms until one is reached that explicitly describes procedures for catching exceptions.
The algorithm for converting an ECMAScript value to a dictionary is defined by [[!WEBIDL]].
DOMException
and the
following DOMException types from [[!WEBIDL]] are used:
AbortError
"
InvalidStateError
"
NotAllowedError
"
NotSupportedError
"
SecurityError
"
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.
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.
The working group will demonstrate implementation experience by creating a test suite and having at least two independent implementations pass each mandatory test (i.e., each test the corresponds to a MUST requirements of the specification). The working group hopes to demonstrate, in the form of an implementation report, interoperability from two or more vendors on both mobile and desktop web browsers.
There has been no change in dependencies on other workings groups during the development of this specification.
This specification was derived from a report published previously by the Web Platform Incubator Community Group.