Abstract

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.

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 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.

Note

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.

This document was published by the Web Payments Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-payments-wg@w3.org (subscribe, archives). All comments are welcome.

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 5 February 2004 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 1 September 2015 W3C Process Document.

1. Introduction

This section is non-normative.

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.

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.

1.1 Goals

1.1.1 Out of scope

  • Create a new payment method
  • Integrate directly with payment processors

2. Definitions

A string is a valid decimal monetary value if it consists of the following components in the given order:

  1. Optionally, a single U+002D HYPHEN-MINUS character (-), to indicate that the amount is negative
  2. One or more characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)
  3. Optionally, a single U+002E FULL STOP character (.) followed by one or more characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)
Note
The following regular expression is an implementation of the above definition.
^-?[0-9]+(\.[0-9]+)?$

3. PaymentRequest interface

[Constructor(sequence<PaymentMethodData> methodData, PaymentDetails details, optional PaymentOptions options),
 SecureContext]
interface PaymentRequest : EventTarget {
    Promise<PaymentResponse> show();
    Promise<void>            abort();

    readonly attribute PaymentAddress?      shippingAddress;
    readonly attribute DOMString?           shippingOption;
    readonly attribute PaymentShippingType? shippingType;

    // Supports "shippingaddresschange" event 
             attribute EventHandler         onshippingaddresschange;

    // Supports "shippingoptionchange" event 
             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.

Note

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:

Example 1: Constructing a PaymentRequest object
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();

3.1 Constructor

The PaymentRequest is constructed using the supplied methodData list including any payment method specific data, the payment details, and the payment options.

Note

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.

Example 2: The 'methodData' argument
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.

Example 3: The 'details' argument
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.

Example 4: The 'options' argument
const options = {
  requestShipping: true
}
const request = new PaymentRequest(methodData, details, options);

The PaymentRequest constructor MUST act as follows:

  1. If the length of the methodData sequence is zero, then throw a TypeError; optionally informing the developer that at least one payment method is required.
  2. For each paymentMethod of methodData:
    1. If the length of the supportedMethods sequence is zero, then throw a TypeError; optionally informing the developer that each payment method needs to include at least one payment method identifier.
  3. If the constructor is called from a nested browsing context, then
    1. Let context be the nested browsing context.
    2. Let origin be the origin of the active document of context.
    3. If any ancestor browsing context of context has an active document with an origin that is not the same as origin and context's browsing context container's node document is not allowed to use the feature indicated by attribute name allowpaymentrequest, then throw a SecurityError.
  4. If the details argument does not contain a value for total, then throw a TypeError; optionally informing the developer that including a total is required.
  5. If details.total.amount.value is not a valid decimal monetary value, then throw a TypeError; optionally informing the developer that the value is invalid.
  6. If the first character of details.total.amount.value is U+002D HYPHEN-MINUS, then throw a TypeError; optionally informing the developer that total can't be a negative amount value.
  7. If the sequence of details.displayItems contains any PaymentItem objects with an amount that is not a valid decimal monetary value, then throw a TypeError; optionally informing the developer that the value is invalid.
  8. If the sequence of details.shippingOptions contains any PaymentShippingOption objects with an amount that is not a valid decimal monetary value, then throw a TypeError; optionally informing the developer that the value is invalid.
  9. If details contains a value for error, then throw a TypeError.
  10. For each paymentMethod in the methodData argument, if the data field is supplied but is not a JSON-serializable object, then throw a TypeError.
  11. For each paymentDetailsModifier in details.modifiers:
    1. If the total field is supplied and is not a valid decimal monetary value, then throw a TypeError; optionally informing the developer that the value is invalid.
    2. If the total field is supplied and the first character of total.amount.value is U+002D HYPHEN-MINUS, then throw a TypeError; optionally informing the developer that the value can't be non-negative amount.
    3. If the sequence of additionalDisplayItems contains any PaymentItem objects with an amount that is not a valid decimal monetary value, then throw a TypeError; optionally informing the developer that the value is invalid.
  12. Let request be a new PaymentRequest.
  13. Store methodData into request@[[methodData]].

    The methodData supplied to the PaymentRequest constructor SHOULD be in the order of preference of the caller. Implementations MAY show payment methods in this order if possible but SHOULD prioritize the preference of the user when presenting payment methods.

  14. Store details into request@[[details]].
  15. Store options into request@[[options]].
  16. Set the value request@[[state]] to created.
  17. Set the value of the shippingAddress attribute on request to null.
  18. Set the value of the shippingOption attribute on request to null.
  19. Set the value of the shippingType attribute on request to null.
  20. If options.requestShipping is set to true, then set the value of the shippingType attribute on request to options.shippingType. If options.shippingType is not a valid PaymentShippingType value then set the shippingType attribute on request to "shipping".
    Note
    This behavior allows a page to detect if it supplied an unsupported shipping type. This will be important if new shipping types are added to a future version of this specification but a page is run in a user agent supporting an earlier version.
  21. If the details.shippingOptions sequence contains multiple PaymentShippingOption objects that have the same id, then set the shippingOptions field of request@[[details]] to an empty sequence.
  22. If request@[[details]] contains a shippingOptions sequence and if any PaymentShippingOption in the sequence has the selected field set to true, then set shippingOption to the id of the last PaymentShippingOption in the sequence with selected set to true.
  23. Set the value request@[[updating]] to false.
  24. Return request.

3.2 show() method

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:

  1. Let request be the PaymentRequest object on which the method is called.
  2. If the value of request@[[state]] is not created then throw an InvalidStateError.
  3. Set the value of request@[[state]] to interactive.
  4. Let acceptPromise be a new Promise.
  5. Store acceptPromise in request@[[acceptPromise]].
  6. Return acceptPromise and asynchronously perform the remaining steps.
  7. Let supportedMethods be the union of all the supportedMethods sequences from each PaymentMethodData in the request@[[methodData]] sequence.
  8. Let acceptedMethods be supportedMethods with all identifiers removed that the user agent does not accept.
  9. If the length of acceptedMethods is zero, then reject acceptPromise with a NotSupportedError.
  10. Show a user interface to allow the user to interact with the payment request process. The acceptPromise will later be resolved by the user accepts the payment request algorithm through interaction with the user interface.

3.3 abort() method

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 the request@[[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:

  1. Let request be the PaymentRequest object on which the method is called.
  2. If the value of request@[[state]] is not interactive then throw an InvalidStateError.
  3. Let promise be a new Promise.
  4. Return promise and asynchronously perform the remaining steps.
  5. Try to abort the current user interaction and close down any remaining user interface.
  6. If it is not possible to abort the current user interaction, then reject promise with InvalidStateError and abort this algorithm.
  7. Set the value of the internal slot request@[[state]] to closed.
  8. Reject the promise request@[[acceptPromise]] with an AbortError.
  9. Resolve promise with undefined.

3.4 State transitions

The internal slot [[state]] follows the following state transitions:

Transition diagram for internal slot state of a PaymentRequest object

3.5 shippingAddress attribute

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.

3.6 shippingOption attribute

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.

3.7 Internal Slots

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

Internal Slot Description (non-normative)
[[methodData]] The methodData supplied to the constructor.
[[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.

4. PaymentMethodData dictionary

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:

supportedMethods
supportedMethods is a required sequence of strings containing payment method identifiers for payment methods that the merchant web site accepts.
data
data is a JSON-serializable object that provides optional information that might be needed by the supported payment methods.

5. PaymentCurrencyAmount 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:

currencySystem
A URL that indicates the currency system that the currency identifier belongs to. By default, the value is urn:iso:std:iso:4217 indicating that currency is defined by [ISO4217] (for example, USD for US Dollars).
currency
A string containing a currency identifier. The value of currency can be any string that is valid within the currency system indicated by currencySystem.
value
A valid decimal monetary value containing a monetary amount.

The following example shows how to represent US$55.00.

Example 5
{
  "currency": "USD",
  "value" : "55.00"
}

6. PaymentDetails dictionary

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
This PaymentItem contains the total amount of the payment request.

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.

displayItems
This sequence of PaymentItem dictionaries contains line items for the payment request that the user agent MAY display. For example, it might include details of products or breakdown of tax and shipping. It is optional to provide this information.
Note

It is the developer's responsibility to verify that the total amount is the sum of these items.

shippingOptions
A sequence containing the different shipping options for the user to choose from.

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.

Note

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.

modifiers
This sequence of PaymentDetailsModifier dictionaries contains modifiers for particular payment method identifiers. For example, it allows you to adjust the total amount based on payment method.
error
When the payment request is updated using updateWith, the PaymentDetails can contain a message in the 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.

7. PaymentDetailsModifier dictionary

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:

supportedMethods
The supportedMethods field contains a sequence of payment method identifiers. The remaining fields in the PaymentDetailsModifier apply only if the user selects a payment method included in this sequence.
total
This PaymentItem value overrides the total field in the PaymentDetails dictionary for the payment method identifiers in the supportedMethods field.
additionalDisplayItems
This sequence of PaymentItem dictionaries provides additional display items that are appended to the 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.
Note

It is the developer's responsibility to verify that the total amount is the sum of the displayItems and the additionalDisplayItems.

data
data is a JSON-serializable object that provides optional information that might be needed by the supported payment methods.

8. PaymentOptions dictionary

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:

requestPayerName
This boolean value indicates whether the user agent should collect and return the payer's name as part of the payment request. For example, this would be set to true to allow a merchant to make a booking in the payer's name.
requestPayerEmail
This boolean value indicates whether the user agent should collect and return the payer's email address as part of the payment request. For example, this would be set to true to allow a merchant to email a receipt.
requestPayerPhone
This boolean value indicates whether the user agent should collect and return the payer's phone number as part of the payment request. For example, this would be set to true to allow a merchant to phone a customer with a billing enquiry.
requestShipping
This boolean value indicates whether the user agent should collect and return a shipping address as part of the payment request. For example, this would be set to true when physical goods need to be shipped by the merchant to the user. This would be set to false for an online-only electronic purchase transaction.
shippingType
Some transactions require an address for delivery but the term "shipping" isn't appropriate. For example, "pizza delivery" not "pizza shipping" and "laundry pickup" not "laundry shipping". If 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 PaymentShippingType supports the following values:

shipping
This is the default and refers to the address being collected as the destination for shipping.
delivery
This refers to the address being collected as being used for delivery. This is commonly faster than shipping. For example, it might be used for food delivery.
pickup
This refers to the address being collected as part of a service pickup. For example, this could be the address for laundry pickup.

The shippingType field only affects the user interface for the payment request.

9. PaymentItem dictionary

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:

label
This is a human-readable description of the item. The user agent may display this to the user.
amount
A PaymentCurrencyAmount containing the monetary amount for the item.
pending
When set to true this flag means that the 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.

10. PaymentAddress interface

[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;
};
country
This is the [CLDR] (Common Locale Data Repository) region code. For example, US, GB, CN, or JP.
addressLine
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.
region
This is the top level administrative subdivision of the country. For example, this can be a state, a province, an oblast, or a prefecture.
city
This is the city/town portion of the address.
dependentLocality
This is the dependent locality or sublocality within a city. For example, used for neighborhoods, boroughs, districts, or UK dependent localities.
postalCode
This is the postal code or ZIP code, also known as PIN code in India.
sortingCode
This is the sorting code as used in, for example, France.
languageCode
This is the BCP-47 language code for the address. It's used to determine the field separators and the order of fields when formatting the address for display.
organization
This is the organization, firm, company, or institution at this address.
recipient
This is the name of the recipient or contact person. This field may, under certain circumstances, contain multiline information. For example, it might contain "care of" information.
phone
This is the phone number of the recipient or contact person.

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.

11. PaymentShippingOption dictionary

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:

id
This is a string identifier used to reference this PaymentShippingOption. It MUST be unique for a given PaymentRequest.
label
This is a human-readable description of the item. The user agent SHOULD use this string to display the shipping option to the user.
amount
A PaymentCurrencyAmount containing the monetary amount for the item.
selected
This is set to true to indicate that this is the default selected PaymentShippingOption in a sequence. User agents SHOULD display this option by default in the user interface.

12. PaymentResponse interface

enum PaymentComplete {
    "success",
    "fail",
    "unknown"
};

[SecureContext]
interface PaymentResponse {
    serializer = {attribute};

    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:

methodName
The payment method identifier for the payment method that the user selected to fulfil the transaction.
details
A JSON-serializable 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.
shippingAddress
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.
shippingOption
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.
payerName
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.
payerEmail
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.
payerPhone
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.

12.1 complete() method

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).

The complete method takes a string argument from the PaymentComplete enum (result). These values are used to influence the user experience provided by the user agent when the user interface is dismissed. The value of result has the following meaning:

"success"
Indicates the payment was successfully processed. The user agent MAY display UI indicating success.
"fail"
Indicates that processing of the payment failed. The user agent MAY display UI indicating failure.
"unknown"
The web page did not indicate success or failure and the user agent SHOULD NOT display UI indicating success or failure. This is the default value if the web page does not supply a value for result.
Note

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 method MUST act as follows:

  1. Let promise be a new Promise.
  2. If the value of the internal slot [[completeCalled]] is true, then throw an InvalidStateError.
  3. Set the value of the internal slot [[completeCalled]] to true.
  4. Return promise and asynchronously perform the remaining steps.
  5. Close down any remaining user interface. The user agent MAY use the value result to influence the user experience. User agents SHOULD treat unrecognized result values as the value " unknown".
  6. Resolve promise with undefined.

12.2 Internal Slots

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.

13. PaymentRequest and iframe elements

This section is non-normative.

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.

14. Events

14.1 Summary

This section is non-normative.

Event name Interface Dispatched when...
shippingaddresschange PaymentRequestUpdateEvent The user provides a new shipping address.
shippingoptionchange PaymentRequestUpdateEvent The user chooses a new shipping option.

14.2 PaymentRequestUpdateEvent interface

[Constructor(DOMString type, optional PaymentRequestUpdateEventInit eventInitDict),
 SecureContext]
interface PaymentRequestUpdateEvent : Event {
    void updateWith(Promise<PaymentDetails> d);
};

dictionary PaymentRequestUpdateEventInit : EventInit {
};

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.

14.2.1 updateWith() method

The updateWith method MUST act as follows:

  1. Let target be the PaymentRequest object that is the target of the event.
  2. If the dispatch flag is unset, then throw an InvalidStateError.
  3. If [[waitForUpdate]] is true, then throw an InvalidStateError.
  4. If target@[[state]] is not interactive, then throw an InvalidStateError.
  5. If target@[[updating]] is true, then throw an InvalidStateError.
  6. Set the stop propagation flag and stop immediate propagation flag.
  7. Set [[waitForUpdate]] to true.
  8. Set target@[[updating]] to true.
  9. The user agent SHOULD disable the user interface that allows the user to accept the payment request. This is to ensure that the payment is not accepted until the web page has made changes required by the change. The web page MUST settle the promise d to indicate that the payment request is valid again.

    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.

  10. Return from the method and asynchronously perform the remaining steps.
  11. Wait until d settles.
    Note
    If d 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 d doesn't settle in a reasonable amount of time. If an implementation chooses to implement a timeout, d should be rejected when the timeout expires. Such a timeout is a fatal error for the payment request.
  12. If d is rejected, then:
    1. Abort the current user interaction and close down any remaining user interface.
    2. Set the value of the internal slot target@[[state]] to closed.
    3. Reject the promise target@[[acceptPromise]] with an AbortError.
    4. Abort this algorithm.
    Note
    If the promise d is rejected then this is a fatal error for the payment request. This would potentially leave the payment request in an inconsistent state since the web page hasn't successfully handled the change event. Consequently, if d is rejected then the payment request is aborted.

    User agents might show an error message to the user when this occurs.

  13. If d is resolved with details and details is a PaymentDetails dictionary, then:
    1. If details contains a total value and total.amount.value is a valid decimal monetary value and the first character of total.amount.value is NOT U+002D HYPHEN-MINUS, then copy total value to the total field of target@[[details]] (total MUST be a non-negative amount).
    2. If details contains a displayItems value and every PaymentItem in the displayItems has an amount.value containing a valid decimal monetary value, then copy details.displayItems to the displayItems field of target@[[details]].
    3. If details contains a modifiers value, then:
      1. Let modifiers be the sequence details.modifiers.
      2. For each PaymentDetailsModifier in modifiers, if the total field is supplied and is not a valid decimal monetary value, then set modifiers to an empty sequence.
      3. For each PaymentDetailsModifier in modifiers, if the additionalDisplayItems sequence contains any PaymentItem objects with an amount that is not a valid decimal monetary value, then set modifiers to an empty sequence.
      4. Copy modifiers to the modifiers field of target@[[details]].
    4. If details contains a shippingOptions sequence, then:
      1. Let shippingOptions be the sequence details.shippingOptions.
      2. If the shippingOptions sequence contains multiple PaymentShippingOption objects that have the same id, then set shippingOptions to the empty sequence.
      3. If the shippingOptions sequence contains a PaymentShippingOption that has an amount.value that is not a valid decimal monetary value, then set shippingOptions to the empty sequence.
      4. Copy shippingOptions to the shippingOptions field of target@[[details]].
      5. Let newOption be null.
      6. If target@[[details]] contains a shippingOptions sequence and if any PaymentShippingOption in the sequence has the selected field set to true, then set newOption to the id of the last PaymentShippingOption in the sequence with selected set to true.
      7. Set the value of shippingOption on target to newOption.
    5. If details contains an error value, then the user agent should update the user interface to display the error message contained in error.
  14. Set [[waitForUpdate]] to false.
  15. Set target@[[updating]] to false.
  16. The user agent should update the user interface based on any changed values in target. The user agent SHOULD re-enable user interface elements that might have been disabled in the steps above if appropriate.

15. Algorithms

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.

15.1 Shipping address changed algorithm

The shipping address changed algorithm runs when the user provides a new shipping address. It MUST run the following steps:

  1. Let request be the PaymentRequest object that the user is interacting with.
  2. Let name be shippingaddresschange.
  3. Set the shippingAddress attribute on request to the shipping address provided by the user.
  4. Run the PaymentRequest updated algorithm with request and name.

15.2 Shipping option changed algorithm

The shipping option changed algorithm runs when the user chooses a new shipping option. It MUST run the following steps:

  1. Let request be the PaymentRequest object that the user is interacting with.
  2. Let name be shippingoptionchange.
  3. Set the shippingOption attribute on request to the id string of the PaymentShippingOption provided by the user.
  4. Run the PaymentRequest updated algorithm with request and name.

15.3 PaymentRequest updated algorithm

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:

  1. If the request@[[updating]] is true, then terminate this algorithm and take no further action. Only one update may take place at a time. This should never occur.
  2. If the request@[[state]] is not set to interactive, then terminate this algorithm and take no further action. The user agent user interface should ensure that this never occurs.
  3. Let event be a new PaymentRequestUpdateEvent.
  4. Queue a task to fire an event named name of type event at request.

15.4 User accepts the payment request algorithm

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:

  1. Let request be the PaymentRequest object that the user is interacting with.
  2. If the request@[[updating]] is true, then terminate this algorithm and take no further action. The user agent user interface should ensure that this never occurs.
  3. If request@[[state]] is not interactive, then terminate this algorithm and take no further action. The user agent user interface should ensure that this never occurs.
  4. If the requestShipping value of request@[[options]] is true, then if the shippingAddress attribute of request is null or if the shippingOption attribute of request is null, then terminate this algorithm and take no further action. This should never occur.
  5. Let response be a new PaymentResponse.
  6. Set the methodName attribute value of response to the payment method identifier for the payment method that the user selected to accept the payment.
  7. Set the details attribute value of response to a JSON-serializable object containing the payment method specific message that will be used by the merchant to process the transaction. The format of this response will be defined for each payment method.
  8. If the requestShipping value of request@[[options]] is true, then copy the shippingAddress attribute of request to the shippingAddress attribute of response.
  9. If the requestShipping value of request@[[options]] is true, then copy the shippingOption attribute of request to the shippingOption attribute of response.
  10. If the requestPayerName value of request@[[options]] is true, then set the payerName attribute of response to the payer's name provided by the user.
  11. If the requestPayerEmail value of request@[[options]] is true, then set the payerEmail attribute of response to the payer's email address selected by the user.
  12. If the requestPayerPhone value of request@[[options]] is true, then set the payerPhone attribute of response to the payer's phone number selected by the user.
  13. Set response@[[completeCalled]] to false.
  14. Set request@[[state]] to closed.
  15. Resolve the pending promise request@[[acceptPromise]] with response.

16. Security Considerations

This section is non-normative.

Editor's Note

This section is a placeholder to record security considerations as we gather them through working group discussion.

16.1 Encryption of data fields

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.

17. Privacy Considerations

This section is non-normative.

Editor's Note

This section is a placeholder to record privacy considerations as we gather them through working group discussion.

17.1 Exposing user information

The user agent should never share information about the user to the web page (such as the shipping address) without user consent.

17.2 Exposing available payment methods

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.

18. Dependencies

This specification relies on several other underlying specifications.

Payment Method Identifiers
The term Payment Method Identifier is defined by the Payment Method Identifiers specification [METHOD-IDENTIFIERS].
HTML 5.1
The following are defined by [HTML51]:
  • queue a task
  • node document
  • browsing context
  • browsing context container
  • nested browsing context
  • ancestor browsing context
  • top-level browsing context
  • allowed to use
  • active document
  • the iframe element
  • the allowpaymentrequest attribute
ECMA-262 6th Edition, The ECMAScript 2015 Language Specification
The terms Promise, internal slot, TypeError, JSON.stringify, and JSON.parse are defined by [ECMA-262-2015].

This document uses the format object@[[slotname]] to mean the internal slot [[slotname]] of the object object.

The term JSON-serializable object used in this specification means an object that can be serialized to a string using JSON.stringify and later deserialized back to an object using JSON.parse with no loss of data.

DOM4
The Event type and the terms fire an event, dispatch flag, stop propagation flag, and stop immediate propagation flag are defined by [DOM4].

DOMException and the following DOMException types from [ DOM4] 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
SecurityError The operation is only supported in a secure context
WebIDL
When this specification says to throw an error, the user agent must throw an error as described in [WEBIDL-2]. 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 term extended attribute is defined by [WEBIDL-2].

Secure Contexts
The term secure context is defined by the Secure Contexts specification [SECURE-CONTEXTS].

19. 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, MUST NOT, SHOULD, and SHOULD NOT are to be interpreted as described in [RFC2119].

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

Note

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.

A. References

A.1 Normative references

[DOM4]
Anne van Kesteren; Aryeh Gregor; Ms2ger; Alex Russell; Robin Berjon. W3C. W3C DOM4. 19 November 2015. W3C Recommendation. URL: https://www.w3.org/TR/dom/
[ECMA-262-2015]
Allen Wirfs-Brock. Ecma International. ECMA-262 6th Edition, The ECMAScript 2015 Language Specification. June 2015. Standard. URL: http://www.ecma-international.org/ecma-262/6.0/index.html
[HTML51]
Steve Faulkner; Arron Eicholz; Travis Leithead; Alex Danilo. W3C. HTML 5.1. 1 November 2016. W3C Recommendation. URL: https://www.w3.org/TR/html51/
[METHOD-IDENTIFIERS]
Adrian Bateman; Zach Koch; Roy McElmurry. Payment Method Identifiers. W3C Working Draft. URL: https://www.w3.org/TR/payment-method-id/
[RFC2119]
S. Bradner. IETF. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WEBIDL-2]
Cameron McCormack; Boris Zbarsky; Tobie Langel. W3C. Web IDL. 15 September 2016. W3C Working Draft. URL: https://www.w3.org/TR/WebIDL-1/

A.2 Informative references

[CLDR]
Unicode Consortium. Unicode Common Locale Data Repository. URL: http://cldr.unicode.org/
[ISO4217]
ISO 4217: Codes for the representation of currencies and funds. ISO.
[SECURE-CONTEXTS]
Mike West. W3C. Secure Contexts. 15 September 2016. W3C Candidate Recommendation. URL: https://www.w3.org/TR/secure-contexts/