Movatterモバイル変換


[0]ホーム

URL:


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

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

Introduction

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

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

Overview

In this document we envision the following flow:

  1. An origin requests permission from the user to handle payment requests for a set of supported payment methods. For example, a user visiting a retail or bank site may be prompted to register a payment handler from that origin. The origin establishes the scope of the permission but the origin's capabilities may evolve without requiring additional user consent.
  2. Payment handlers are defined inservice worker code.
  3. When the merchant (or otherpayee) calls the [[payment-request]] methodcanMakePayment() orshow() (e.g., when the user -- thepayer -- pushes a button on a checkout page), the user agent computes a list of candidate payment handlers, comparing the payment methods accepted by the merchant with those known to the user agent through any number of mechanisms, including, but not limited to:
    • Those previously registered through this API.
    • Those that may be registered through this API during the course of the transaction, e.g., identified through apayment method manifest.
    • Those registered through other mechanisms, e.g., the operating system.
  4. The user agent displays a set of choices to the user: the candidate payment handlers. The user agent displays these choices using information (labels and icons) provided at registration or otherwise available from the Web app.
  5. When thepayer user selects a payment handler, the user agent fires a {{PaymentRequestEvent}} (cf. theuser interaction task source) in theservice worker for the selected payment handler. The {{PaymentRequestEvent}} includes some information from the PaymentRequest (defined in [[!payment-request]]) as well as additional information (e.g., payee's origin).
  6. Once activated, the payment handler performs whatever steps are necessary tohandle the payment request, and return an appropriate payment response to thepayee. If interaction with the user is necessary, thepayment handler can open a window for that purpose.
  7. The user agent receives a response asynchronously once the payment handler has finished handling the request. The response becomes thePaymentResponse (of [[!payment-request]]).

An origin may implement a payment app with more than one service worker and therefore multiplepayment handlers may be registered per origin. The handler that is invoked is determined by the selection made by the user.

Handling a Payment Request

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

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

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

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

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

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

Relation to Other Types of Payment Apps

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

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

Registration

One registers a payment handler with the user agent through a just-in-time (JIT) registration mechanism.

Just-in-time registration

If a payment handler is not registered when a merchant invokes {{PaymentRequest/show()}} method, a user agent may allow the user to register this payment handler during the transaction ("just-in-time").

The remaining content of this section is non-normative.

A user agent may perform just-in-time installation by deriving payment handler information from thepayment method manifest that is found through theURL-based payment method identifier that the merchant requested.

Management

This section describes the functionality available to a payment handler to manage its own properties.

Extension to the `ServiceWorkerRegistration` interface

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

ThepaymentManager attribute exposes payment handler management functionality.

PaymentManager interface

          [SecureContext, Exposed=(Window)]          interface PaymentManager {            attribute DOMString userHint;            Promise<undefined> enableDelegations(sequence<PaymentDelegation> delegations);          };

The {{PaymentManager}} is used bypayment handlers to manage their supported delegations.

userHint attribute

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

enableDelegations() method

This method allows apayment handler to asynchronously declare its supportedPaymentDelegation list.

PaymentDelegation enum

        enum PaymentDelegation {          "shippingAddress",          "payerName",          "payerPhone",          "payerEmail"        };
"shippingAddress"
The payment handler will provide shipping address whenever needed.
"payerName"
The payment handler will provide payer's name whenever needed.
"payerPhone"
The payment handler will provide payer's phone whenever needed.
"payerEmail"
The payment handler will provide payer's email whenever needed.

Can make payment

If thepayment handler supportsCanMakePaymentEvent, theuser agent may use it to help with filtering of the available payment handlers.

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

Extension to `ServiceWorkerGlobalScope`

        partial interface ServiceWorkerGlobalScope {          attribute EventHandler oncanmakepayment;        };

oncanmakepayment attribute

The {{ServiceWorkerGlobalScope/oncanmakepayment}} attribute is anevent handler whose correspondingevent handler event type is "canmakepayment".

TheCanMakePaymentEvent

TheCanMakePaymentEvent is used to as a signal for whether the payment handler is able to respond to a payment request.

          [Exposed=ServiceWorker]          interface CanMakePaymentEvent : ExtendableEvent {            constructor(DOMString type);            undefined respondWith(Promise<boolean> canMakePaymentResponse);          };

respondWith() method

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

Handling a CanMakePaymentEvent

Upon receiving aPaymentRequest, theuser agent MUST run the following steps:

  1. Ifuser agent settings prohibit usage ofCanMakePaymentEvent (e.g., in private browsing mode), terminate these steps.
  2. Letregistration be a {{ServiceWorkerRegistration}}.
  3. Ifregistration is not found, terminate these steps.
  4. Fire Functional Event "canmakepayment" usingCanMakePaymentEvent onregistration.

Example of handling theCanMakePaymentEvent

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

          self.addEventListener("canmakepayment", function(e) {            e.respondWith(new Promise(function(resolve, reject) {              resolve(true);            }));          });

Filtering of Payment Handlers

Given aPaymentMethodData and a payment handler that matches onpayment method identifier, this algorithm returnstrue if this payment handler can be used for payment:

  1. LetmethodName be thepayment method identifier string specified in thePaymentMethodData.
  2. LetmethodData be the payment method specific data ofPaymentMethodData.
  3. LetpaymentHandlerOrigin be theorigin of the {{ServiceWorkerRegistration}} scope URL of the payment handler.
  4. LetpaymentMethodManifest be theingested andparsedpayment method manifest for themethodName.
  5. IfmethodName is aURL-based payment method identifier with the"*" stringsupported origins inpaymentMethodManifest, returntrue.
  6. Otherwise, if theURL-based payment method identifiermethodName has the sameorigin aspaymentHandlerOrigin, fire theCanMakePaymentEvent in the payment handler and return the result.
  7. Otherwise, ifsupported origins inpaymentMethodManifest is an ordered set of [=url/origin=] that contains thepaymentHandlerOrigin, fire theCanMakePaymentEvent in the payment handler and return the result.
  8. Otherwise, return `false`.

Invocation

Once the user has selected a payment handler, the user agent fires a {{PaymentRequestEvent}} and uses the subsequentPaymentHandlerResponse to create aPaymentResponse for [[!payment-request]].

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

Extension toServiceWorkerGlobalScope

This specification extends theServiceWorkerGlobalScope interface.

        partial interface ServiceWorkerGlobalScope {          attribute EventHandler onpaymentrequest;        };

onpaymentrequest attribute

Theonpaymentrequest attribute is anevent handler whose correspondingevent handler event type is {{PaymentRequestEvent}}.

ThePaymentRequestDetailsUpdate

ThePaymentRequestDetailsUpdate contains the updated total (optionally with modifiers and shipping options) and possible errors resulting from user selection of a payment method, a shipping address, or a shipping option within a payment handler.

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

error member

A human readable string that explains why the user selected payment method, shipping address or shipping option cannot be used.

total member

Updated total based on the changed payment method, shipping address, or shipping option. The total can change, for example, because the billing address of the payment method selected by the user changes the Value Added Tax (VAT); Or because the shipping option/address selected/provided by the user changes the shipping cost.

modifiers member

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

shippingOptions member

Updated shippingOptions based on the changed shipping address. For example, it is possible that express shipping is more expensive or unavailable for the user provided country.

paymentMethodErrors member

Validation errors for the payment method, if any.

shippingAddressErrors member

Validation errors for the shipping address, if any.

ThePaymentRequestEvent

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

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

topOrigin attribute

Returns a string that indicates theorigin of the top levelpayee web page. This attribute is initialized byHandling a PaymentRequestEvent.

paymentRequestOrigin attribute

Returns a string that indicates theorigin where aPaymentRequest was initialized. When aPaymentRequest is initialized in thetopOrigin, the attributes have the same value, otherwise the attributes have different values. For example, when aPaymentRequest is initialized within an iframe from an origin other thantopOrigin, the value of this attribute is the origin of the iframe. This attribute is initialized byHandling a PaymentRequestEvent.

paymentRequestId attribute

When getting, thepaymentRequestId attribute returns the {{ PaymentRequest/[[details]] }}.id from thePaymentRequest that corresponds to this {{PaymentRequestEvent}}.

methodData attribute

This attribute containsPaymentMethodData dictionaries containing thepayment method identifiers for thepayment methods that the web site accepts and any associatedpayment method specific data. It is populated from thePaymentRequest using theMethodData Population Algorithm defined below.

total attribute

This attribute indicates the total amount being requested for payment. It is of typePaymentCurrencyAmount dictionary as defined in [[payment-request]], and initialized with a copy of thetotal field of thePaymentDetailsInit provided when the correspondingPaymentRequest object was instantiated.

modifiers attribute

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

paymentOptions attribute

The value ofPaymentOptions in thePaymentRequest. Available only when shippingAddress and/or any subset of payer's contact information are requested.

shippingOptions attribute

The value ofShippingOptions in thePaymentDetailsInit dictionary of the correspondingPaymentRequest.(PaymentDetailsInit inherits ShippingOptions fromPaymentDetailsBase). Available only when shipping address is requested.

openWindow() method

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

changePaymentMethod() method

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

changeShippingAddress() method

This method is used by the payment handler to get updated payment details given the shippingAddress. When called, it runs thechange payment details algorithm.

changeShippingOption() method

This method is used by the payment handler to get updated payment details given the shippingOption identifier. When called, it runs thechange payment details algorithm.

respondWith() method

This method is used by the payment handler to provide aPaymentHandlerResponse when the payment successfully completes. When called, it runs theRespond to PaymentRequest Algorithm with |event| andhandlerResponsePromise as arguments.

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

PaymentRequestEventInit dictionary

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

ThetopOrigin,paymentRequestOrigin,paymentRequestId,methodData,total,modifiers,paymentOptions, andshippingOptions members share their definitions with those defined for {{PaymentRequestEvent}}

MethodData Population Algorithm

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

  1. LetregisteredMethods be the set of registeredpayment method identifiers of the invoked payment handler.
  2. Create a new emptySequence.
  3. SetdataList to the newly createdSequence.
  4. For each item inPaymentRequest@[[\methodData]] in the corresponding payment request, perform the following steps:
    1. SetinData to the item under consideration.
    2. SetcommonMethods to the set intersection ofinData.supportedMethods andregisteredMethods.
    3. IfcommonMethods is empty, skip the remaining substeps and move on to the next item (if any).
    4. Create a newPaymentMethodData object.
    5. SetoutData to the newly createdPaymentMethodData.
    6. SetoutData.supportedMethods to a list containing the members ofcommonMethods.
    7. SetoutData.data to a copy ofinData.data.
    8. AppendoutData todataList.
  5. SetmethodData todataList.

Modifiers Population Algorithm

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

  1. LetregisteredMethods be the set of registeredpayment method identifiers of the invoked payment handler.
  2. Create a new emptySequence.
  3. SetmodifierList to the newly createdSequence.
  4. For each item inPaymentRequest@[[\paymentDetails]].modifiers in the corresponding payment request, perform the following steps:
    1. SetinModifier to the item under consideration.
    2. SetcommonMethods to the set intersection ofinModifier.supportedMethods andregisteredMethods.
    3. IfcommonMethods is empty, skip the remaining substeps and move on to the next item (if any).
    4. Create a newPaymentDetailsModifier object.
    5. SetoutModifier to the newly createdPaymentDetailsModifier.
    6. SetoutModifier.supportedMethods to a list containing the members ofcommonMethods.
    7. SetoutModifier.total to a copy of inModifier.total.
    8. AppendoutModifier tomodifierList.
  5. Setmodifiers tomodifierList.

Internal Slots

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

Internal Slot Default Value Description (non-normative)
[[\windowClient]] null The currently activeWindowClient. This is set if a payment handler is currently showing a window to the user. Otherwise, it is null.
[[\respondWithCalled]] false YAHO

Handling a PaymentRequestEvent

Upon receiving aPaymentRequest by way ofPaymentRequest.show() and subsequent user selection of a payment handler, theuser agent MUST run the following steps:

  1. Letregistration be the {{ServiceWorkerRegistration}} corresponding to the payment handler selected by the user.
  2. Ifregistration is not found, reject the {{Promise}} that was created byPaymentRequest.show() with an {{"InvalidStateError"}} {{DOMException}} and terminate these steps.
  3. Fire Functional Event "paymentrequest" using {{PaymentRequestEvent}} onregistration with the following properties:

    {{PaymentRequestEvent/topOrigin}}
    the [=serialization of an origin=] of the top level payee web page.
    paymentRequestOrigin
    the [=serialization of an origin=] of the context where PaymentRequest was initialized.
    {{PaymentRequestEvent/methodData}}
    The result of executing theMethodData Population Algorithm.
    modifiers
    The result of executing theModifiers Population Algorithm.
    {{PaymentRequestEvent/total}}
    A copy of the total field on thePaymentDetailsInit from the correspondingPaymentRequest.
    paymentRequestId
    \[\[details\]\].id from thePaymentRequest.
    paymentOptions
    A copy of the paymentOptions dictionary passed to the constructor of the correspondingPaymentRequest.
    shippingOptions
    A copy of the shippingOptions field on thePaymentDetailsInit from the correspondingPaymentRequest.

    Then run the following steps in parallel, withdispatchedEvent:

    1. Wait for all of the promises in theextend lifetime promises ofdispatchedEvent to resolve.
    2. If thepayment handler has not provided aPaymentHandlerResponse, reject the {{Promise}} that was created byPaymentRequest.show() with an {{"OperationError"}} {{DOMException}}.

Windows

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

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

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

Open Window Algorithm

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

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

  1. Let |event| be this {{PaymentRequestEvent}}.
  2. If |event|'s {{Event/isTrusted}} attribute is false, return a {{Promise}} rejected with a {{"InvalidStateError"}} {{DOMException}}.
  3. Letrequest be thePaymentRequest that triggered this {{PaymentRequestEvent}}.
  4. Leturl be the result ofparsing theurl argument.
  5. If the url parsing throws an exception, return a {{Promise}} rejected with that exception.
  6. Ifurl isabout:blank, return a {{Promise}} rejected with a {{TypeError}}.
  7. Ifurl's origin is not the same as theservice worker's origin associated with the payment handler, return a {{Promise}} resolved with null.
  8. Letpromise be a new {{Promise}}.
  9. Returnpromise and perform the remaining steps in parallel:
  10. If |event|.{{ PaymentRequestEvent/[[windowClient]] }} is not null, then:
    1. If |event|.{{ PaymentRequestEvent/[[windowClient]] }}.visibilityState is not "unloaded", rejectpromise with an {{"InvalidStateError"}} {{DOMException}} and abort these steps.
  11. LetnewContext be a newtop-level browsing context.
  12. NavigatenewContext tourl, with exceptions enabled and replacement enabled.
  13. If the navigation throws an exception, rejectpromise with that exception and abort these steps.
  14. If the origin ofnewContext is not the same as the service worker client origin associated with the payment handler, then:
    1. Resolvepromise with null.
    2. Abort these steps.
  15. Letclient be the result of running thecreate window client algorithm withnewContext as the argument.
  16. Set |event|.{{ PaymentRequestEvent/[[windowClient]] }} toclient.
  17. Resolvepromise withclient.

Example of handling the {{PaymentRequestEvent}}

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

      async function getPaymentResponseFromWindow() {        return new Promise((resolve, reject) => {          self.addEventListener("message", listener = e => {            self.removeEventListener("message", listener);            if (!e.data || !e.data.methodName) {              reject();              return;            }            resolve(e.data);          });        });      }      self.addEventListener("paymentrequest", e => {        e.respondWith((async() => {          // Open a new window for providing payment UI to user.          const windowClient = await e.openWindow("payment_ui.html");          // Send data to the opened window.          windowClient.postMessage({            total: e.total,            modifiers: e.modifiers          });          // Wait for a payment response from the opened window.          return await getPaymentResponseFromWindow();        })());      });

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

<form><table>  <tr><th>Cardholder Name:</th><td><input name="cardholderName"></td></tr>  <tr><th>Card Number:</th><td><input name="cardNumber"></td></tr>  <tr><th>Expiration Month:</th><td><input name="expiryMonth"></td></tr>  <tr><th>Expiration Year:</th><td><input name="expiryYear"></td></tr>  <tr><th>Security Code:</th><td><input name="cardSecurityCode"></td></tr>  <tr><th></th><td><input type="submit" value="Pay"></td></tr></table></form><script>navigator.serviceWorker.addEventListener("message", e => {  /* Note: message sent from payment app is available in e.data */});document.getElementById("form").addEventListener("submit", e => {  const details = {};  ["cardholderName", "cardNumber", "expiryMonth", "expiryYear", "cardSecurityCode"]  .forEach(field => {    details[field] = form.elements[field].value;  });  const paymentAppResponse = {    methodName: "https://example.com/pay",    details  };  navigator.serviceWorker.controller.postMessage(paymentAppResponse);  window.close();});</script>

Response

PaymentHandlerResponse dictionary

The PaymentHandlerResponse is conveyed using the following dictionary:
          dictionary PaymentHandlerResponse {          DOMString methodName;          object details;          DOMString? payerName;          DOMString? payerEmail;          DOMString? payerPhone;          AddressInit shippingAddress;          DOMString? shippingOption;          };

methodName attribute

Thepayment method identifier for thepayment method that the user selected to fulfil the transaction.

details attribute

AJSON-serializable object that provides apayment method specific message used by the merchant to process the transaction and determine successful fund transfer.

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

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

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

payerName attribute

The user provided payer's name.

payerEmail attribute

The user provided payer's email.

payerPhone attribute

The user provided payer's phone number.

shippingAddress attribute

The user provided shipping address.

shippingOption attribute

The identifier of the user selected shipping option.

Change Payment Method Algorithm

When this algorithm is invoked withmethodName andmethodDetails parameters, the user agent MUST run the following steps:

  1. Run thepayment method changed algorithm withPaymentMethodChangeEvent |event| constructed using the givenmethodName andmethodDetails parameters.
  2. If |event|.updateWith(detailsPromise) is not run, returnnull.
  3. If |event|.updateWith(detailsPromise) throws, rethrow the error.
  4. If |event|.updateWith(detailsPromise) times out (optional), throw {{"InvalidStateError"}} {{DOMException}}.
  5. Construct and return aPaymentRequestDetailsUpdate from thedetailsPromise in |event|.updateWith(detailsPromise).

Change Payment Details Algorithm

When this algorithm is invoked withshippingAddress orshippingOption the user agent MUST run the following steps:

  1. Run thePaymentRequest updated algorithm withPaymentRequestUpdateEvent |event| constructed using the updated details (shippingAddress orshippingOption).
  2. If |event|.updateWith(detailsPromise) is not run, returnnull.
  3. If |event|.updateWith(detailsPromise) throws, rethrow the error.
  4. If |event|.updateWith(detailsPromise) times out (optional), throw {{"InvalidStateError"}} {{DOMException}}.
  5. Construct and return aPaymentRequestDetailsUpdate from thedetailsPromise in |event|.updateWith(detailsPromise).

Respond to PaymentRequest Algorithm

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

  1. If |event|'s {{Event/isTrusted}} is false, then throw an "InvalidStateError" {{DOMException}} and abort these steps.
  2. If |event|'s [=Event/dispatch flag=] is unset, then throw an {{"InvalidStateError"}} {{DOMException}} and abort these steps.
  3. If |event|.{{ PaymentRequestEvent/[[respondWithCalled]] }} is true, throw an {{"InvalidStateError"}} {{DOMException}} and abort these steps.
  4. Set |event|.{{ PaymentRequestEvent/[[respondWithCalled]] }} to true.
  5. Set the |event|'s [=Event/stop propagation flag=] andevent's [=Event/stop immediate propagation flag=].
  6. AddhandlerResponsePromise to the |event|'sextend lifetime promises
  7. Increment the |event|'spending promises count by one.
  8. Upon rejection ofhandlerResponsePromise:
    1. Run thepayment app failure algorithm and terminate these steps.
  9. Upon fulfillment ofhandlerResponsePromise:
    1. LethandlerResponse be |value|converted to an IDL value {{PaymentHandlerResponse}}. If this throws an exception, run thepayment app failure algorithm and terminate these steps.
    2. Validate that all required members exist inhandlerResponse and are well formed.
      1. IfhandlerResponse.methodName is not present or not set to one of the values from |event|.methodData, run the payment app failure algorithm and terminate these steps.
      2. IfhandlerResponse.details is not present or notJSON-serializable, run thepayment app failure algorithm and terminate these steps.
      3. LetshippingRequired be therequestShipping value of the associated PaymentRequest'spaymentOptions. IfshippingRequired andhandlerResponse.shippingAddress is not present, run thepayment app failure algorithm and terminate these steps.
      4. IfshippingRequired andhandlerResponse.shippingOption is not present or not set to one of shipping options identifiers from |event|.shippingOptions, run thepayment app failure algorithm and terminate these steps.
      5. LetpayerNameRequired be therequestPayerName value of the associated PaymentRequest'spaymentOptions. IfpayerNameRequired andhandlerResponse.payerName is not present, run thepayment app failure algorithm and terminate these steps.
      6. LetpayerEmailRequired be therequestPayerEmail value of the associated PaymentRequest'spaymentOptions. IfpayerEmailRequired andhandlerResponse.payerEmail is not present, run thepayment app failure algorithm and terminate these steps.
      7. LetpayerPhoneRequired be therequestPayerPhone value of the associated PaymentRequest'spaymentOptions. IfpayerPhoneRequired andhandlerResponse.payerPhone is not present, run thepayment app failure algorithm and terminate these steps.
    3. Serialize required members ofhandlerResponse (methodName anddetails are always required;shippingAddress andshippingOption are required whenshippingRequired is true;payerName,payerEmail, andpayerPhone are required whenpayerNameRequired,payerEmailRequired, andpayerPhoneRequired are true, respectively.):
      1. For eachmemberinhandlerResponseLetserializeMemberbe the result ofStructuredSerializewith handlerResponse.member. Rethrow any exceptions.
    4. The user agent MUST run theuser accepts the payment request algorithm as defined in [[!payment-request]], replacing steps 9-15 with these steps or their equivalent.
      1. Deserialize serialized members:
        1. For eachserializeMemberletmemberbe the result ofStructuredDeserializewithserializeMember. Rethrow any exceptions.
      2. If any exception occurs in the above step, then run thepayment app failure algorithm and terminate these steps.
      3. AssignmethodName to associated PaymentRequest'sresponse.methodName.
      4. Assigndetails to associated PaymentReqeust'sresponse.details.
      5. IfshippingRequired, then set the shippingAddress attribute of associated PaymentReqeust'sresponse toshippingAddress. Otherwise, set it to null.
      6. IfshippingRequired, then set the shippingOption attribute of associated PaymentReqeust'sresponse toshippingOption. Otherwise, set it to null.
      7. IfpayerNameRequired, then set the payerName attribute of associated PaymentReqeust'sresponse topayerName. Otherwise, set it to null.
      8. IfpayerEmailRequired, then set thepayerEmail attribute of associated PaymentReqeust'sresponse topayerEmail. Otherwise, set it to null.
      9. IfpayerPhoneRequired, then set thepayerPhone attribute of associated PaymentReqeust'sresponse topayerPhone. Otherwise, set it to null.
  10. Upon fulfillment orupon rejection ofhandlerResponsePromise,queue a microtask to perform the following steps:
    1. Decrement the |event|'spending promises count by one.
    2. Letregistration be thethis'srelevant global object's associatedservice worker'scontaining service worker registration.
    3. Ifregistration is not null, invokeTry Activate withregistration.

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

      paymentRequestEvent.respondWith(new Promise(function(accept,reject) {        /* ... processing may occur here ... */        accept({          methodName: "https://example.com/pay",          details: {            cardHolderName:   "John Smith",            cardNumber:       "1232343451234",            expiryMonth:      "12",            expiryYear :      "2020",            cardSecurityCode: "123"           },          shippingAddress: {            addressLine: [              "1875 Explorer St #1000",            ],            city: "Reston",            country: "US",            dependentLocality: "",            organization: "",            phone: "+15555555555",            postalCode: "20190",            recipient: "John Smith",            region: "VA",            sortingCode: ""          },          shippingOption: "express",          payerEmail: "john.smith@gmail.com",        });      }));

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

Security and Privacy Considerations

Addresses

The Web Payments Working Group removed support for shipping and billing addresses from the original version of Payment Request API due to privacy issues; seeissue 842. In order to provide documentation for implementations that continue to support this capability, the Working Group is now restoring the feature with an expectation of addressing privacy issues. In doing so the Working Group may also make changes to Payment Request API based on the evolution of other APIs (e.g., the Content Picker API).

Information about the User Environment

User Consent to Install a Payment Handler

User Consent before Payment

User Awareness about Sharing Data Cross-Origin

Secure Communications

Authorized Payment Apps

Supported Origin

Data Validation

Private Browsing Mode

Payment Handler Display Considerations

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

User experience details are left to implementers.

Dependencies

This specification relies on several other underlying specifications.

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

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

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

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


[8]ページ先頭

©2009-2025 Movatter.jp