DEV Community

Cover image for The Payment Request API: Revolutionizing Online Payments (Part 2)
Salvietta150x40
Salvietta150x40

Posted on • Updated on • Originally published at ma-no.org

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

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.

Top comments (0)