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

Streamlining Payment Processes for Seamless Transactions

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

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.

Part 1: Simplifying the Payment Experience

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.

To illustrate the simplicity of integrating the Payment Request API, let's consider an example. The following code demonstrates how to create a basic payment request:

 
<!--The button with the id paymentButton triggers the payment process when clicked.-->
<button id="paymentButton">Pay Now</button> 
<div id="response">We do not charge you anything, it is just a test!</div>
 

THE JAVASCRIPT

 
// Define the supported payment methods
const supportedPaymentMethods = [
  {
    supportedMethods: ['basic-card'],
    data: {
      supportedNetworks: ['visa', 'mastercard'],
    },
  },
  {
    supportedMethods: ['https://google.com/pay'],
    data: {
      merchantIdentifier: '0123456789',
      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],
    },
  },
];
// Define the payment details
const paymentDetails = {
  total: {
    label: 'Total',
    amount: {
      currency: 'USD',
      value: '100.00',
    },
  },
  displayItems: [
    {
      label: 'Product A',
      amount: {
        currency: 'USD',
        value: '50.00',
      },
    },
    {
      label: 'Product B',
      amount: {
        currency: 'USD',
        value: '50.00',
      },
    },
  ],
};
// Create a payment request
const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);
// Display the payment sheet when the user clicks a button
const paymentButton = document.getElementById('paymentButton');
paymentButton.addEventListener('click', async () => {
  try {
// Show the payment request sheet to the user
    const paymentResponse = await paymentRequest.show();
// Process the payment response
    await processPaymentResponse(paymentResponse);
  } catch (error) {
    console.error('Error processing payment:', error);
  }
});
// Process the payment response      
async function processPaymentResponse(paymentResponse) {
// Implement your logic to handle the payment response here        
// This function will be called when the user completes the payment      
}

 

And now, let's have a look at the last part of the code, explaining the code step by step.

First of all, we create a Payment Request Object using the PaymentRequest() constructor.

 
const paymentRequest = new PaymentRequest(supportedPaymentMethods, paymentDetails);
 

The PaymentRequest object is created with two parameters: supportedPaymentMethods and paymentDetails . The supportedPaymentMethods is an array that defines, as suggested, the supported payment methods, such as credit cards or third-party payment providers.

The paymentDetails object specifies the details of the payment, including the total amount and individual items.

Let's continue:

 
const paymentButton = document.getElementById('paymentButton');
// Display the payment sheet when the user clicks a button
paymentButton.addEventListener('click', async () => {
  try {
// Show the payment request sheet to the user
    const paymentResponse = await paymentRequest.show();
// Process the payment response
    await processPaymentResponse(paymentResponse);
  } catch (error) {
    console.error('Error processing payment:', error);
  }
});

 

In the first line, we define the paymentButton variable by retrieving the element using document.getElementById .

Then, an event listener is added to a button with the id paymentButton . When the button is clicked, the click event is triggered. Inside the event handler, the show() method of the paymentRequest object is called to display the payment sheet to the user. This method returns a promise that resolves with a PaymentResponse object when the user completes or cancels the payment.

If the payment is completed, the processPaymentResponse() function is called with the paymentResponse 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.

In the following code, we define the supported methods:

 
// Define the supported payment methods
const supportedPaymentMethods = [
  {
    supportedMethods: ['basic-card'],
    data: {
      supportedNetworks: ['visa', 'mastercard'],
    },
  },
  {
    supportedMethods: ['https://google.com/pay'],
    data: {
      merchantIdentifier: '0123456789',
      allowedPaymentMethods: ['TOKENIZED_CARD', 'CARD'],
    },
  },
];

 

The supportedPaymentMethods variable is an array that defines the supported payment methods. In this example, two methods are defined: basic-card and https://google.com/pay . The basic-card method supports credit cards with the visa and mastercard networks. The https://google.com/pay method is a custom payment method provided by Google Pay, and it requires the merchant identifier and the allowed payment methods to be specified.

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 supportedPaymentMethods array:

1. Credit Cards:
' basic-card ': This method supports basic credit card payments. It is widely supported and allows users to enter their card details manually.

2. Digital Wallets:
https://google.com/pay : This method enables users to pay using Google Pay. It requires the merchant identifier and supports various payment methods provided by Google Pay.
https://apple.com/apple-pay : This method enables users to pay using Apple Pay. It requires additional configuration and supports Apple Pay as a payment method.
' https://www.paypal.com/webapps/mpp/paypal-checkout `: This method integrates PayPal Checkout, allowing users to pay with their PayPal accounts.

3. Bank Transfers:
https://secure.checkout.example/bank : This method allows users to initiate bank transfers directly from their bank accounts.

4. Cryptocurrencies:
https://example.com/bitcoin : This method supports payments using cryptocurrencies like Bitcoin or Ethereum. It requires integration with a cryptocurrency payment processor.

5. Local Payment Methods:
https://example.com/local-payment : This method represents a custom local payment method specific to your region or target audience. It would require integration with a local payment provider.

It'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.

Consistent with the choice to use https://google.com/pay , the allowedPaymentMethods property is set to ['TOKENIZED_CARD', 'CARD'] . These values represent the specific payment methods allowed within the Google Pay integration.

The allowedPaymentMethods 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).

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.

In the code that follows, we will define the payment details:

 
// Define the payment details
const paymentDetails = {
  total: {
    label: 'Total',
    amount: {
      currency: 'USD',
      value: '100.00',
    },
  },
  displayItems: [
    {
      label: 'Product A',
      amount: {
        currency: 'USD',
        value: '50.00',
      },
    },
    {
      label: 'Product B',
      amount: {
        currency: 'USD',
        value: '50.00',
      },
    },
  ],
};
 

As the paymentDetails variable name suggested, it specifies the details of the payment. It includes a total object that defines the total amount to be paid. In this case, the total is $100.00 USD. The displayItems array contains individual items included in the payment, such as 'Product A' and 'Product B', each with a value of $50.00 USD.

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.

When the paymentButton is clicked, the click event handler is triggered. It calls the show() method on the paymentRequest 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.

If the user completes the payment, the show() method will resolve with a PaymentResponse object, which represents the user's payment authorization. This response is then passed to the processPaymentResponse() function for further processing. The processPaymentResponse() 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.

On the other hand, if the user cancels the payment or an error occurs during the payment process, the catch block will be executed, and an error message will be logged to the console.

Overall, this code demonstrates a basic implementation 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 processPaymentResponse() 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.

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.

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:

  1. Payment Request API - MDN Web Docs: 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.
  2. PaymentRequest - MDN Web Docs: 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.
  3. PaymentResponse - MDN Web Docs: This page focuses on the PaymentResponse interface, which represents the user'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.

Additionally, you can refer to the Can I use 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.

By referring to these resources, you'll be able to get a more comprehensive understanding of the Payment Request API, its usage, and the browser support you can expect.

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.

In the next part of this series, we will explore advanced features and how to process the payment response.



 

Imagen de storyset en Freepik

 
by Silvia Mazzetta Date: 12-06-2023 javascript API hits : 11180  
 
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 2)

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…

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