The Payment Request API: Revolutionizing Online Payments (Part 2)
Tags: javascript, api, development
Published: 2023-06-05 15:31:00

---
title: The Payment Request API: Revolutionizing Online Payments (Part 2)
published: true
description: Payment Request API: Advanced Features and Best Practices for Seamless Transactions
date: 2023-06-05 15:31 UTC
tags: javascript, API, development
canonical_url: https://www.ma-no.org/en/programming/javascript/the-payment-request-api-revolutionizing-online-payments-part-2
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-05 15:31 +0000
---


 our case, for testing purposes to simulate transactions without making real payments.
</p>
<p>
  <code>apiVersion: 2
  </code> and 
  <code>apiVersionMinor: 0
  </code> specify the version of the Google Pay API being used. In this case, we use version 2.0.
</p>
<p>We proceed by adding the 
  <code>merchantInfo
  </code> object specifying information about the merchant accepting the payment.
</p>
<p>
  <code>merchantIdentifier
  </code>, which we specified earlier, is a unique identifier assigned to the merchant by Google Pay.
</p>
<p>
  <code>merchantName
  </code> specifies the name of the merchant.
</p>
<p>Here&#39;s the code:
</p>
&nbsp;
<pre>{<br>supportedMethods: ['https://google.com/pay'],<br>        data: {<br>        environment: &quot;TEST&quot;,<br>                apiVersion: 2,<br>                apiVersionMinor: 0,<br>                merchantInfo: {<br>                merchantIdentifier: '12345678901234567890',<br>                        merchantName: &quot;Example Merchant&quot;<br>                        },<br>                allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],<br>                },<br>        },<br>
</pre>
&nbsp;
<p>In summary, this code block sets up the configuration for integrating Google Pay as a supported payment method. It includes specifying the environment, API version, merchant information, and allowed payment methods for Google Pay. This configuration enables users to choose Google Pay as a payment option when making a transaction on your web application.
</p>
<p>The next step is the configuration of the 
  <code>paymentOptions
  </code> object, with which you can customize the behavior and appearance of the payment request to suit your specific needs. These options allow you to collect the necessary information from the payer and facilitate the payment process.
</p>
<p>The 
  <code>paymentOptions
  </code> object is an object that contains various options or settings related to the payment request. It provides configuration for how the payment request should be displayed and what information it should collect from the payer. Let&#39;s go through each property of the paymentOptions object:
</p>
<p>
  <code>requestPayerName
  </code>:
</p>
<ul>
  <li>This property determines whether the payment request should prompt the user to provide their name.</li>
  <li>If set to true, the payment sheet will include a field where the payer can enter their name.</li>
</ul>
&nbsp;
<p>
  <code>requestPayerEmail:
  </code>
</p>
<ul>
  <li>This property specifies whether the payment request should prompt the user to enter their email address.</li>
  <li>When set to true, the payment sheet will include a field where the payer can enter their email address.</li>
</ul>
&nbsp;
<p>
  <code>requestPayerPhone:
  </code>
</p>
<ul>
  <li>This property indicates whether the payment request should ask the user to provide their phone number.</li>
  <li>If set to true, the payment sheet will include a field for the payer to enter their phone number.</li>
</ul>
&nbsp;
<p>
  <code>requestShipping:
  </code>
</p>
<ul>
  <li>This property determines whether the payment request should include a section for the payer to enter their shipping address.</li>
  <li>If set to true, the payment sheet will prompt the user to enter their shipping address.</li>
</ul>
&nbsp;
<p>
  <code>shippingType:
  </code>
</p>
<ul>
  <li>This property specifies the type of shipping requested from the user.</li>
  <li>In this case, the value is set to &quot;shipping&quot;, indicating that the requested shipping is for physical goods to be delivered to the payer&#39;s address.</li>
</ul>
&nbsp;
<p>The next major change to the previous code, is the addition of used to retrieve an HTML element from the DOM with the id attribute set to &quot;response&quot;.
</p>
&nbsp;
<pre>
const response = document.getElementById(&quot;response&quot;);
</pre>
&nbsp;
<p>The purpose of this line is to obtain a reference to an element in the HTML document where you want to display the response or status of the payment request. By using 
  <code>document.getElementById
  </code>(&quot;response&quot;), you can access and manipulate the content of that specific element.
</p>
<p>After retrieving the element using 
  <code>document.getElementById
  </code>(&quot;response&quot;), the reference is stored in the 
  <code>response
  </code> constant. Later in the code, the content of this element is updated based on the outcome of the payment request. For example, if the payment is successful, a text is displayed within the 
  <code>response
  </code> element.
</p>
<p>We are now going to modify the code that sets up an event listener for a button click and shows a payment request sheet to the user, handles the payment response, and provides appropriate feedback messages to the user based on the outcome of the payment process.
</p>
&nbsp;
<pre>
// Add an event listener to the paymentButton
paymentButton.addEventListener(&#39;click&#39;, async () =&gt; {
try {
// Show the payment request sheet to the user
const paymentResponse = await paymentRequest.show();
</pre>
&nbsp;
<p>In this part, an event listener is added to the paymentButton element. It listens for a &#39;<strong>click</strong>&#39; event and executes the callback function when the button is clicked. The callback function is defined as an asynchronous function, denoted by the 
  <code>async
  </code> keyword. Inside the callback function, the code attempts to show the payment request sheet to the user by calling 
  <code>paymentRequest.show()
  </code>. This function displays a sheet or dialog where the user can enter their payment information.
</p>
&nbsp;
<pre>// Process the payment response<br>if (paymentResponse) {<br>// If a payment response is received<br>await paymentResponse.complete('success'); // Complete the payment<br>        await processPaymentResponse(paymentResponse); // Process the payment response<br>        response.innerText = 'thanks for your purchase'; // Display a success message<br>        } else {<br>// If the payment request is canceled<br>response.innerText = 'Payment request canceled.'; // Display a cancellation message<br>        }<br>} catch (error) {<br>// If an error occurs during the payment request<br>console.error('Payment request failed:', error); // Log the error to the console<br>        response.innerText = 'Sorry, something went wrong.'; // Display an error message<br>        }<br>});</pre>
&nbsp;
<p>After showing the payment request sheet, the code checks if a 
  <code>paymentResponse
  </code> object is received. If a response is present, it means the user has completed the payment process.
</p>
<p>In the case of a successful payment response, the code proceeds to complete the payment by calling 
  <code>paymentResponse.complete(&#39;success&#39;)
  </code>. This informs the payment system that the payment was successful. Then, it calls the 
  <code>processPaymentResponse
  </code> function, passing the paymentResponse object as an argument. This function is responsible for handling the payment response and performing any necessary actions based on the response.
</p>
<p>Finally, it updates the response element with a success message.
</p>
<p>If the payment request is canceled (no paymentResponse object), the code updates the response element with a cancellation message.
</p>
<p>If an error occurs during the payment request, the code catches the error in the catch block. It logs the error message to the console using console.error and updates the response element with an error message.
</p>
&nbsp;
<pre>// Define a function to process the payment response<br>async function processPaymentResponse(paymentResponse) {<br>// Handle the payment response here<br>// Implement the necessary logic based on the response<br>  console.log('Processing payment response:', paymentResponse);<br>// ...<br>} </pre>
&nbsp;
<p>The 
  <code>processPaymentResponse
  </code> function is defined separately, outside the event listener. It is an asynchronous function that takes the 
  <code>paymentResponse
  </code> object as an argument. This function can be implemented to handle the payment response as needed. In the code provided, it logs the 
  <code>paymentResponse
  </code> object to the console.
</p>
<p>Clearly, you can modify this function to perform any specific logic required for processing the payment response.
</p>
<p>I am sure this is the part that many of you have been waiting for, a demo to try it out for yourself: <strong>feel free to try out this <a href="https://codepen.io/salvietta150x40/pen/ZEmYWBe" target="_blank" title="The Payment Request API: Revolutionizing Online Payments">CodePen</a>.</strong>
</p>