The Payment Request API: Revolutionizing Online Payments (Part 1)
Tags: javascript, api, development
Published: 2023-06-04 13:15:00

---
title: The Payment Request API: Revolutionizing Online Payments (Part 1)
published: true
description: Streamlining Payment Processes for Seamless Transactions
date: 2023-06-04 12:15:00 UTC
tags: javascript, API, development
canonical_url: https://www.ma-no.org/en/programming/javascript/the-payment-request-api-revolutionizing-online-payments-part-1
cover_image: https://www.ma-no.org/cache/galleries/contents-2294/960-400/payment-api-development-impjpg.webp
# Use a ratio of 100:42 for best results.
# published_at:  2023-06-04 12:15 +0000
---

![Streamlining Payment Processes for Seamless Transactions](https://www.ma-no.org/cache/galleries/contents-2294/960-400/payment-api-development-impjpg.webp)


<p>The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into the intricacies of this powerful API and explore how it simplifies the payment experience for both users and merchants.
</p>
<p>The Payment Request API serves as a bridge between merchants and users, enabling seamless and secure payments. With its integration into modern browsers, the API allows websites to request payment information from users, such as credit card details or digital wallet credentials, in a standardized and user-friendly manner. By eliminating the need for manual form-filling and offering a consistent payment interface across different platforms, the API significantly enhances the checkout process.
</p>
<p>To illustrate the simplicity of integrating the Payment Request API, let&#39;s consider an example. The following code demonstrates how to create a <strong>basic payment </strong>request:
</p>
&nbsp;
<p>THE HTML</p>
&nbsp;
<pre>
&lt;!--The button with the id paymentButton triggers the payment process when clicked.--&gt;
&lt;button id=&quot;paymentButton&quot;&gt;Pay Now&lt;/button&gt; 
&lt;div id=&quot;response&quot;&gt;We do not charge you anything, it is just a test!&lt;/div&gt;
</pre>
&nbsp;
<p><strong>THE JAVASCRIPT</strong>
</p>
&nbsp;
<pre>// Define the supported payment methods<br>const supportedPaymentMethods = [<br>  {<br>    supportedMethods: ['basic-card'],<br>    data: {<br>      supportedNetworks: ['visa', 'mastercard'],<br>    },<br>  },<br>  {<br>    supportedMethods: ['https://google.com/pay'],<br>    data: {<br>      merchantIdentifier: '0123456789',<br>      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],<br>    },<br>  },<br>];<br>// Define the payment details<br>const paymentDetails = {<br>  total: {<br>    label: 'Total',<br>    amount: {<br>      currency: 'USD',<br>      value: '100.00',<br>    },<br>  },<br>  displayItems: [<br>    {<br>      label: 'Product A',<br>      amount: {<br>        currency: 'USD',<br>        value: '50.00',<br>      },<br>    },<br>    {<br>      label: 'Product B',<br>      amount: {<br>        currency: 'USD',<br>        value: '50.00',<br>      },<br>    },<br>  ],<br>};<br>// Create a payment request<br>const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);<br>// Display the payment sheet when the user clicks a button<br>const paymentButton = document.getElementById('paymentButton');<br>paymentButton.addEventListener('click', async () =&gt; {<br>  try {<br>// Show the payment request sheet to the user<br>    const paymentResponse = await paymentRequest.show();<br>// Process the payment response<br>    await processPaymentResponse(paymentResponse);<br>  } catch (error) {<br>    console.error('Error processing payment:', error);<br>  }<br>});<br>// Process the payment response      <br>async function processPaymentResponse(paymentResponse) {<br>// Implement your logic to handle the payment response here        <br>// This function will be called when the user completes the payment      <br>}<br>
</pre>
&nbsp;
<p>And now, let&#39;s have a look at the last part of the code, explaining the code step by step.
</p>
<p>First of all, we create a Payment Request Object using the 
  <code>PaymentRequest() 
  </code> constructor.
</p>
&nbsp;
<pre>
const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);
</pre>
&nbsp;
<p>The 
  <code>PaymentRequest 
  </code> object is created with two parameters: 
  <code>supportedPaymentMethods 
  </code> and 
  <code>paymentDetails 
  </code>. The 
  <code>supportedPaymentMethods 
  </code> is an array that defines, as suggested, the supported payment methods, such as credit cards or third-party payment providers.
</p>
<p>The 
  <code>paymentDetails 
  </code> object specifies the details of the payment, including the total amount and individual items.
</p>
<p>Let&#39;s continue:
</p>
&nbsp;
<pre>const paymentButton = document.getElementById('paymentButton');<br>// Display the payment sheet when the user clicks a button<br>paymentButton.addEventListener('click', async () =&gt; {<br>  try {<br>// Show the payment request sheet to the user<br>    const paymentResponse = await paymentRequest.show();<br>// Process the payment response<br>    await processPaymentResponse(paymentResponse);<br>  } catch (error) {<br>    console.error('Error processing payment:', error);<br>  }<br>});<br>
</pre>
&nbsp;
<p>In the first line, we define the 
  <code>paymentButton 
  </code> variable by retrieving the element using 
  <code>document.getElementById 
  </code>.
</p>
<p>Then, an event listener is added to a button with the id 
  <code>paymentButton 
  </code>. When the button is clicked, the 
  <code>click 
  </code> event is triggered. Inside the event handler, the 
  <code>show() 
  </code> method of the paymentRequest object is called to display the payment sheet to the user. This method returns a promise that resolves with a 
  <code>PaymentResponse 
  </code> object when the user completes or cancels the payment.
</p>
<p>If the payment is completed, the 
  <code>processPaymentResponse() 
  </code> function is called with the 
  <code>paymentResponse 
  </code> as an argument to handle the payment response. If an error occurs during the payment process, it is caught in the catch block, and an error message is logged to the console.
</p>
<p>In the following code, we define the supported methods:
</p>
&nbsp;
<pre>// Define the supported payment methods<br>const supportedPaymentMethods = [<br>  {<br>    supportedMethods: ['basic-card'],<br>    data: {<br>      supportedNetworks: ['visa', 'mastercard'],<br>    },<br>  },<br>  {<br>    supportedMethods: ['https://google.com/pay'],<br>    data: {<br>      merchantIdentifier: '0123456789',<br>      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],<br>    },<br>  },<br>];<br>
</pre>
&nbsp;
<p>The 
  <code>supportedPaymentMethods 
  </code> variable is an array that defines the supported payment methods. In this example, two methods are defined: 
  <code>basic-card 
  </code> and 
  <code>https://google.com/pay 
  </code>. The 
  <code>basic-card 
  </code> method supports credit cards with the <strong>visa</strong> and <strong>mastercard</strong> networks. The 
  <code>https://google.com/pay 
  </code> method is a custom payment method provided by Google Pay, and it requires the merchant identifier and the allowed payment methods to be specified.
</p>
<p>Clearly the choice of supported payment methods depends on your specific requirements and the target audience of your application or website. Here are some commonly used payment methods that you may consider adding to the 
  <code>supportedPaymentMethods 
  </code> array:
</p>
<p><strong>1. Credit Cards:</strong>
  <br />
  &#39; 
  <code>basic-card 
  </code>&#39;: This method supports basic credit card payments. It is widely supported and allows users to enter their card details manually.
</p>
<p><strong>2. Digital Wallets:</strong>
  <br />
  <code>https://google.com/pay 
  </code>: This method enables users to pay using Google Pay. It requires the merchant identifier and supports various payment methods provided by Google Pay.
  <br />
  <code>https://apple.com/apple-pay 
  </code>: This method enables users to pay using Apple Pay. It requires additional configuration and supports Apple Pay as a payment method.
  <br />
  &#39; 
  <code>https://www.paypal.com/webapps/mpp/paypal-checkout 
  </code>`: This method integrates PayPal Checkout, allowing users to pay with their PayPal accounts.
</p>
<p><strong>3. Bank Transfers:</strong>
  <br />
  <code>https://secure.checkout.example/bank 
  </code>: This method allows users to initiate bank transfers directly from their bank accounts.
</p>
<p><strong>4. Cryptocurrencies:</strong>
  <br />
  <code>https://example.com/bitcoin 
  </code>: This method supports payments using cryptocurrencies like Bitcoin or Ethereum. It requires integration with a cryptocurrency payment processor.
</p>
<p><strong>5. Local Payment Methods:</strong>
  <br />
  <code>https://example.com/local-payment 
  </code>: This method represents a custom local payment method specific to your region or target audience. It would require integration with a local payment provider.
</p>
<p>It&#39;s important to note that the availability and support for these payment methods may vary depending on the payment processor or platform you are using. You should consult the documentation of your payment provider or platform to identify the specific supported payment methods they offer.
</p>
<p>
</p>
<p>Consistent with the choice to use 
  <code>https://google.com/pay 
  </code>, the 
  <code>allowedPaymentMethods 
  </code> property is set to 
  <code>[&#39;TOKENIZED_CARD&#39;, &#39;CARD&#39;] 
  </code>. These values represent the specific payment methods allowed within the <strong>Google Pay integration.</strong>
</p>
<p>The 
  <code>allowedPaymentMethods 
  </code> property helps define the available options within a payment method. For example, it could be used to differentiate between credit card payments and tokenized card payments (where the card details are stored securely by the payment provider).
</p>
<p>By specifying the allowed payment methods, you can control the options presented to the user during the payment process. It allows you to tailor the payment experience based on your specific integration requirements and the capabilities of the payment provider or platform you are working with.
</p>
<p>In the code that follows, we will define the payment details:
</p>
&nbsp;
<pre>// Define the payment details<br>const paymentDetails = {<br>  total: {<br>    label: 'Total',<br>    amount: {<br>      currency: 'USD',<br>      value: '100.00',<br>    },<br>  },<br>  displayItems: [<br>    {<br>      label: 'Product A',<br>      amount: {<br>        currency: 'USD',<br>        value: '50.00',<br>      },<br>    },<br>    {<br>      label: 'Product B',<br>      amount: {<br>        currency: 'USD',<br>        value: '50.00',<br>      },<br>    },<br>  ],<br>};</pre>
&nbsp;
<p>As the 
  <code>paymentDetails 
  </code> variable name suggested, it specifies the details of the payment. It includes a 
  <code>total 
  </code> object that defines the total amount to be paid. In this case, the total is $100.00 USD. The 
  <code>displayItems 
  </code> array contains individual items included in the payment, such as &#39;Product A&#39; and &#39;Product B&#39;, each with a value of $50.00 USD.
</p>
<p>Overall, this code sets up a payment request with supported payment methods and payment details, shows a payment sheet when a button is clicked, and handles the payment response.
</p>
<p>When the 
  <code>paymentButton 
  </code> is clicked, the click event handler is triggered. It calls the 
  <code>show() 
  </code> method on the 
  <code>paymentRequest 
  </code> object, which displays the payment sheet to the user. The user will be presented with a UI to choose a payment method and enter payment details.
</p>
<p>If the user completes the payment, the 
  <code>show() 
  </code> method will resolve with a 
  <code>PaymentResponse 
  </code> object, which represents the user&#39;s payment authorization. This response is then passed to the 
  <code>processPaymentResponse() 
  </code> function for further processing. The 
  <code>processPaymentResponse() 
  </code> function is not shown in the code snippet you provided, but it would typically handle the payment response by sending it to a server for verification and processing the payment on the server-side.
</p>
<p>On the other hand, if the user cancels the payment or an error occurs during the payment process, the 
  <code>catch 
  </code> block will be executed, and an error message will be logged to the console.
</p>
<p>Overall, this code demonstrates a <strong>basic implementation</strong> of the Payment Request API, where the user is presented with a payment sheet, and the payment response is processed asynchronously. The specific implementation of the 
  <code>processPaymentResponse() 
  </code> function and the subsequent steps for handling the payment will depend on the requirements of the application or website where this code is being used.
</p>
<p>By utilizing the Payment Request API, websites can streamline the payment experience for users. It provides a standardized and user-friendly interface, supports multiple payment methods, and enhances security through tokenization.
</p>
<p>In addiction, here are some useful links to the Mozilla Developer Network (MDN) documentation that provide more detailed information about the Payment Request API, including browser support:
</p>
<ol>
  <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API" rel="nofollow" target="_new">Payment Request API - MDN Web Docs</a>: This page provides an overview of the Payment Request API, including its purpose, browser compatibility, and key concepts. It covers the basic usage of the API and provides examples to help you get started.</li>
  <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest" rel="nofollow" target="_new">PaymentRequest - MDN Web Docs</a>: This is the specific documentation for the PaymentRequest interface. It explains the properties, methods, and events associated with the PaymentRequest object. It also provides examples and usage guidelines for creating payment requests.</li>
  <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse" rel="nofollow" target="_new">PaymentResponse - MDN Web Docs</a>: This page focuses on the PaymentResponse interface, which represents the user&#39;s response to a payment request. It explains the properties and methods available on the PaymentResponse object and provides examples of how to handle and process the payment response.</li>
</ol>
<p>Additionally, you can refer to the <a href="https://caniuse.com/payment-request" rel="nofollow" target="_new">Can I use</a> website, which provides up-to-date information on browser support for the Payment Request API. It shows a detailed breakdown of support across different browsers and versions, helping you understand the compatibility of the API.
</p>
<p>By referring to these resources, you&#39;ll be able to get a more comprehensive understanding of the Payment Request API, its usage, and the browser support you can expect.
</p>
<p>In conclusion, the Payment Request API simplifies the payment process for users and merchants alike. By incorporating this API into their websites, businesses can create a seamless and secure payment experience, resulting in improved customer satisfaction and increased conversion rates.
</p>
<p>In the next part of this series, we will explore <a href="https://www.ma-no.org/en/programming/javascript/the-payment-request-api-revolutionizing-online-payments-part-2" title="advanced features and implementation best practices for harnessing the full potential of the Payment Request API">advanced features and how to process the payment response</a>.
</p>
<p>
</p>
<br />
<br />
&nbsp;