The Payment Request API: Revolutionizing Online Payments (Part 2)

Advanced Features and Best Practices for Seamless Transactions

by Silvia Mazzetta Date: 08-06-2023 javascript API

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features and best practices to further optimize the integration of this powerful API.

We start by making a modification of supportedMethods by adding the data property contains additional data related to the Google Pay payment method.

Then we set the environment for the Google Pay integration to "TEST": The "TEST" environment is used in our case, for testing purposes to simulate transactions without making real payments.

apiVersion: 2 and apiVersionMinor: 0 specify the version of the Google Pay API being used. In this case, we use version 2.0.

We proceed by adding the merchantInfo object specifying information about the merchant accepting the payment.

merchantIdentifier, which we specified earlier, is a unique identifier assigned to the merchant by Google Pay.

merchantName specifies the name of the merchant.

Here's the code:

 
 {
 supportedMethods: ['https://google.com/pay'],
   data: {
     environment: "TEST",
     apiVersion: 2,
     apiVersionMinor: 0,
     merchantInfo: {
       merchantIdentifier: '12345678901234567890',
       merchantName: "Example Merchant"
     },
   allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],
 },
 },
 
 

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.

The next step is the configuration of the paymentOptions 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.

The paymentOptions 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's go through each property of the paymentOptions object:

requestPayerName:

  • This property determines whether the payment request should prompt the user to provide their name.
  • If set to true, the payment sheet will include a field where the payer can enter their name.
 

requestPayerEmail:

  • This property specifies whether the payment request should prompt the user to enter their email address.
  • When set to true, the payment sheet will include a field where the payer can enter their email address.
 

requestPayerPhone:

  • This property indicates whether the payment request should ask the user to provide their phone number.
  • If set to true, the payment sheet will include a field for the payer to enter their phone number.
 

requestShipping:

  • This property determines whether the payment request should include a section for the payer to enter their shipping address.
  • If set to true, the payment sheet will prompt the user to enter their shipping address.
 

shippingType:

  • This property specifies the type of shipping requested from the user.
  • In this case, the value is set to "shipping", indicating that the requested shipping is for physical goods to be delivered to the payer's address.
 

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

 
const response = document.getElementById("response");
 

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 document.getElementById("response"), you can access and manipulate the content of that specific element.

After retrieving the element using document.getElementById("response"), the reference is stored in the response 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 response element.

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.

 
 
// Add an event listener to the paymentButton
paymentButton.addEventListener('click', async () => {
   try {
   // Show the payment request sheet to the user
   const paymentResponse = await paymentRequest.show();
 

In this part, an event listener is added to the paymentButton element. It listens for a 'click' event and executes the callback function when the button is clicked. The callback function is defined as an asynchronous function, denoted by the async keyword. Inside the callback function, the code attempts to show the payment request sheet to the user by calling paymentRequest.show(). This function displays a sheet or dialog where the user can enter their payment information.

 

 // Process the payment response
   if (paymentResponse) {
      // If a payment response is received
      await paymentResponse.complete('success'); // Complete the payment
      await processPaymentResponse(paymentResponse); // Process the payment response
      response.innerText = 'thanks for your purchase'; // Display a success message
      } else {
        // If the payment request is canceled
        response.innerText = 'Payment request canceled.'; // Display a cancellation message
      }
   
   } catch (error) {
     // If an error occurs during the payment request
     console.error('Payment request failed:', error); // Log the error to the console
     response.innerText = 'Sorry, something went wrong.'; // Display an error message
   }
});
 

After showing the payment request sheet, the code checks if a paymentResponse object is received. If a response is present, it means the user has completed the payment process.

In the case of a successful payment response, the code proceeds to complete the payment by calling paymentResponse.complete('success'). This informs the payment system that the payment was successful. Then, it calls the processPaymentResponse 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.

Finally, it updates the response element with a success message.

If the payment request is canceled (no paymentResponse object), the code updates the response element with a cancellation message.

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.

 
 // Define a function to process the payment response
   
 async function processPaymentResponse(paymentResponse) {
 // Handle the payment response here
 // Implement the necessary logic based on the response
   console.log('Processing payment response:', paymentResponse);
   // ...
 } 
 

The processPaymentResponse function is defined separately, outside the event listener. It is an asynchronous function that takes the paymentResponse object as an argument. This function can be implemented to handle the payment response as needed. In the code provided, it logs the paymentResponse object to the console.

Clearly, you can modify this function to perform any specific logic required for processing the payment response.

I am sure this is the part that many of you have been waiting for, a demo to try it out for yourself: feel free to try out this CodePen.

   

Imagen de storyset en Freepik

 
by Silvia Mazzetta Date: 08-06-2023 javascript API hits : 1746  
 
Silvia Mazzetta

Silvia Mazzetta

Web Developer, Blogger, Creative Thinker, Social media enthusiast, Italian expat in Spain, mom of little 9 years old geek, founder of  @manoweb. A strong conceptual and creative thinker who has a keen interest in all things relate to the Internet. A technically savvy web developer, who has multiple  years of website design expertise behind her.  She turns conceptual ideas into highly creative visual digital products. 

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 1)

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…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Clicky