PaymentRequest: show() method
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.
ThePaymentRequest interface'sshow() method instructs the user agent to begin theprocess of showing and handling the user interface for the payment request to theuser.
Only one payment request can be in the process of being handled at once, across alldocuments. Once onePaymentRequest'sshow() method has beencalled, any other call toshow() will by rejected with anAbortError until the returned promise has been concluded, either by beingfulfilled with aPaymentResponse indicating the results of the paymentrequest, or by being rejected with an error.
Note:In reality, despite the fact that the specification says thiscan't be done, some browsers, including Firefox, support multiple active paymentrequests at a time.
If your architecture doesn't necessarily have all of the data ready to go at the momentit instantiates the payment interface by callingshow(), specify thedetailsPromise parameter, providing aPromise that isfulfilled once the data is ready. If this is provided,show() will notallow the user to interact with the payment interface until the promise is fulfilled, sothat data can be updated prior to the user engaging with the payment process.
Processing the result and, if necessary, callingPaymentResponse.retry()to retry a failed payment can all be done either asynchronously or synchronously,depending on your needs. For the best user experience, asynchronous solutions aretypically the best way to go. Most examples on MDN and elsewhere useasync/awaitto wait asynchronously while results are validated and so forth.
In this article
Syntax
show()show(details)Parameters
detailsOptionalEither an object or a
Promisethat resolves to an object. Provide this if your architecture requiresthat the payment request's details need to be updated between instantiating thepayment interface and the user beginning to interact with it. The object should contain the updated information:displayItemsOptionalAn array of objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice, each with the following properties:
amountAn object describing the monetary value of the item. This object includes the following fields:
currencyA string containing a valid 3-letterISO 4217 currency identifier (ISO 4217) indicating the currency used for the payment
value.valueA string containing a valid decimal value representing the mount of currency constituting the payment amount. This string must only contain an optional leading "-" to indicate a negative value, then one or more digits from 0 to 9, and an optional decimal point (".", regardless of locale) followed by at least one more digit. No whitespace is permitted.
labelA string specifying a human-readable name or description of the item or service being charged for. This may be displayed to the user by theuser agent, depending on the design of the interface.
pendingA Boolean value which is
trueif the specifiedamounthas not yet been finalized. This can be used to show items such as shipping or tax amounts that depend upon the selection of shipping address, shipping option, or so forth. The user agent may show this information but is not required to do so.
errorOptionalDeprecatedNon-standardA string specifying an error message to present to the user. When calling
updateWith(), includingerrorin the updated data causes theuser agent to display the text as a general error message. For address-field specific errors, use theshippingAddressErrorsfield.modifiersOptionalAn array of objects, each describing a modifier for particular payment method identifiers, each with the following properties:
supportedMethodsA string that represents the payment method identifier. The payment method identifier only applies if the user selects this payment method.
totalOptionalAn object that overrides the
totalproperty of thedetailsPromiseparameter if this payment method is selected by the user. The property takes the same input with thetotalproperty of thedetailsPromiseparameter.additionalDisplayItemsOptionalAn
Arrayof objects provide additional display items that are appended to thedisplayItemsproperty of thedetailsPromiseparameter if this payment method is selected by the user. This property 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. The property takes the same input with thedisplayItemsproperty of thedetailsPromiseparameter.dataOptionalA serializable object that provides optional information that might be needed by the supported payment methods.
For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").
shippingAddressErrorsOptionalDeprecatedNon-standardAn object which includes an error message for each property of the shipping address that could not be validated.
shippingOptionsOptionalDeprecatedNon-standardAn array of objects, each describing one available shipping option from which the user may choose.
totalOptionalAn object with the same properties as the objects in
displayItemsproviding an updated total for the payment. Make sure this equals the sum of all of the items indisplayItems.This is not calculated automatically. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged.
Return value
APromise that eventually resolves with aPaymentResponse.The promise is resolved when the user accepts the payment request (such as by clicking a"Pay" button in the browser's payment sheet).
Exceptions
Exceptions are not thrown but returned when thePromise rejects.
AbortErrorDOMExceptionReturned if theuser agent is already showing a payment panel. Only one paymentpanel may be visible at a timeacross all documents loaded by the useragent.
The promise is also rejected with
AbortErrorif the user cancels thepayment request.InvalidStateErrorDOMExceptionReturned if the same payment hasalready been shown for this request (its state is
interactivebecause itis being shown already).NotSupportedErrorDOMExceptionReturned if the user agent does notsupport the payment methods specified when the
PaymentRequestconstructor was called.SecurityErrorDOMExceptionReturned if the call to
show()was not in response to a user action, such as aclickorkeyupevent. Other reasons aSecurityErrormay be thrownare at the discretion of the user agent, and may include situations such as too manycalls toshow()being made in a short time orshow()beingcalled while payment requests are blocked by parental controls.
Security
Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.
Usage notes
The most common patterns for usingshow() involve either theasync/awaitsyntax or the use ofshow().then().catch() to handle the response and anypossible rejection. Those look like this:
async/await syntax
Usingawait to wait for a promise to be resolved makes it possible towrite the code to handle payments particularly cleanly:
async function processPayment() { try { const payRequest = new PaymentRequest(methodData, details, options); payRequest.onshippingaddresschange = (ev) => ev.updateWith(checkAddress(payRequest)); payRequest.onshippingoptionchange = (ev) => ev.updateWith(checkShipping(payRequest)); const response = await payRequest.show(); await validateResponse(response); } catch (err) { /* handle the error; AbortError usually means a user cancellation */ }}In this code, the methodscheckAddress() andcheckShipping(),respectively, check the shipping address and the shipping option changes and supply inresponse either an object or a promise to return one;this object contains the fields in thePaymentResponse which have been orneed to be changed.
ThevalidateResponse() method, below, is called onceshow()returns, in order to look at the returnedresponse and either submit thepayment or reject the payment as failed:
async function validateResponse(response) { try { if (await checkAllValues(response)) { await response.complete("success"); } else { await response.complete("fail"); } } catch (err) { await response.complete("fail"); }}Here, a custom function calledcheckAllValues() looks at each value in theresponse and ensures that they're valid, returningtrue ifevery field is valid orfalse if any are not. If and only if every field isvalid, thecomplete() method is called on theresponse with the string"success", which indicates that everything isvalid and that the payment can complete accordingly.
If any fields have unacceptable values, or if an exception is thrown by the previouscode,complete() is called with the string"fail", whichindicates that the payment process is complete and failed.
Instead of immediately failing, you could choose to callretry() on the response object to ask the useragent to try to process the payment again; this should usually only be done after theuser has made any needed corrections to the order.
Starting the payment process, in the end, is as simple as calling theprocessPayment() method.
then/catch syntax
You can also use the older promise-based approach to work with payments, using thethen() andcatch()functions on the promise returned byshow():
function processPayment() { const payRequest = new PaymentRequest(methodData, details, options); payRequest.onshippingaddresschange = (ev) => ev.updateWith(checkAddress(payRequest)); payRequest.onshippingoptionchange = (ev) => ev.updateWith(checkShipping(payRequest)); payRequest .show() .then((response) => validateResponse(response)) .catch((err) => handleError(err));}This is functionally equivalent to theprocessPayment() method using theawait syntax.
function validateResponse(response) { checkAllValues(response) .then((response) => response.complete("success")) .catch((response) => response.complete("fail"));}You could even havecheckAllValues() be a synchronous function, althoughthat may have performance implications you don't want to deal with:
function validateResponse(response) { if (checkAllValues(response)) { response.complete("success"); } else { response.complete("fail"); }}See the articleUsing promises for more information if you need more information about working withpromises.
Examples
In the following example, aPaymentRequest object is instantiated beforetheshow() method is called. This method triggers the user agent's built-inprocess for retrieving payment information from the user. Theshow() methodreturns aPromise that resolves to aPaymentResponse objectwhen the user interaction is complete. The developer then uses the information inthePaymentResponse object to format and send payment data to the server.You should send the payment information to the server asynchronously so that the finalcall topaymentResponse.complete() can indicate the success or failure ofthe payment.
button.onclick = async () => { // Initialization of PaymentRequest arguments are excerpted for the sake of // brevity. const payment = new PaymentRequest(methods, details, options); try { const response = await payment.show(); // Process response here, including sending payment instrument // (e.g., credit card) information to the server. // paymentResponse.methodName contains the selected payment method // paymentResponse.details contains a payment method specific response await response.complete("success"); } catch (err) { console.error("Uh oh, something bad happened", err.message); }};The following example shows how to update the payment sheet as it's being presented tothe end-user.
async function requestPayment() { // We start with AU$0 as the total. const initialDetails = { total: { label: "Total", amount: { value: "0", currency: "AUD" }, }, }; const request = new PaymentRequest(methods, initialDetails, options); // Check if the user supports the `methods` if (!(await request.canMakePayment())) { return; // no, so use a web form instead. } // Let's update the total as the sheet is shown const updatedDetails = { total: { label: "Total", amount: { value: "20", currency: "AUD" }, }, }; const response = await request.show(updatedDetails); // Check response, etc.}document.getElementById("buyButton").onclick = requestPayment;Specifications
| Specification |
|---|
| Payment Request API> # dom-paymentrequest-show> |