Introduction to the Native Payments Request API

Introduction to the Native Payments Request API

Did you know many modern browsers have an in-built Payment Request API? In this article, you'll understanding to to the Native Payments Request API

Did you know many modern browsers have an in-built Payment Request API? In this article, you'll understanding to to the Native Payments Request API

Payment Request API — a W3C browser standard that facilitates the exchange of payment and contact information.

The Payment Request API provides a browser-based method of connecting users and their preferred payment systems and platforms to merchants that they want to pay for goods and services

Payment Request API Goals — https://www.w3.org/TR/payment-request/#goals

This is a brilliant idea since the idea behind the payment API is to standardize how we pay for things, reduce friction when it comes to implementing accepting payments, and less volatile bugs.

What the PaymentRequest API looks like;

new PaymentRequest(methodData: fn, details: fn, options?);

As you can see, we create a new instance of the payment API with a constructor method. The payment constructor takes two mandatory parameters and one optional parameter:

  • methodData — an object containing information concerning the payment provider, such as what payment methods are supported, etc.
  • details — an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc.
  • options (optional) — an object containing additional options related to the payment.

    Payment API Demo

Payment API demo

As we can see, the payment is directly integrated into the browser. No more insecure third-party redirects or API calls, everything happens in the browser directly!

Getting started the Payments Request API

The Payment API is experimental technology and is prone to change in the future. I still encourage getting familiar with this new API since I believe the proposal is strong and here to stay, maybe some incremental additional new features may be added.

If you wish to follow the examples along, grab a copy of the repository.

git clone https://github.com/indreklasn/payments-request-api-example.git && yarn && yarn start

This shell command will clone the repo, install the dependencies and start the server at localhost:3000

You should see a very simple counter with a buy button

Note; The payment API works on localhost for testing purposes.

Since our app is simple, we’re going to place all payment related logic into the app.js file.

let count = 0
const cartIncrementButton = document.getElementById('cartIncrement')
const cartDecrementButton = document.getElementById('cartDecrement')
const countElement = document.getElementById('count')
const buyButton = document.getElementById('purchase')

function init() {

  countElement.innerHTML = count
  cartIncrementButton.addEventListener('click', () => {
    count++
    countElement.innerHTML = `${count}
[Payment Request API ](https://www.w3.org/TR/payment-request/ "Payment Request API ")— a W3C browser standard that facilitates the exchange of payment and contact information.

The [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API "Payment Request API") provides a browser-based method of connecting users and their preferred payment systems and platforms to merchants that they want to pay for goods and services

![](https://miro.medium.com/max/700/1*-EHkIwadfV4b4lNN42Fcyg.png)

Payment Request API Goals — [https://www.w3.org/TR/payment-request/#goals](https://www.w3.org/TR/payment-request/#goals "https://www.w3.org/TR/payment-request/#goals")

This is a brilliant idea since the idea behind the *payment API* is to standardize how we pay for things, reduce friction when it comes to implementing accepting payments, and less volatile bugs.

What the *PaymentRequest API* looks like;

new PaymentRequest(methodData: fn, details: fn, options?);


As you can see, we create a new instance of the *payment API* with a constructor method. The payment constructor takes two mandatory parameters and one optional parameter:
* ```methodData``` — an object containing information concerning the payment provider, such as what payment methods are supported, etc.
* ```details``` — an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc.
* ```options``` (optional) — an object containing additional options related to the payment.
## Payment API Demo

![](https://miro.medium.com/freeze/max/60/1*OQ07k84nrm47BlO-cmCKaw.gif?q=20)

![](https://miro.medium.com/max/700/1*OQ07k84nrm47BlO-cmCKaw.gif)

Payment API demo

As we can see, the payment is directly integrated into the browser. No more insecure third-party redirects or API calls, everything happens in the browser directly!
## Getting started the Payments Request API

The *Payment API* is experimental technology and is prone to change in the future. I still encourage getting familiar with this new [API](https://morioh.com/topic/api "API") since I believe the proposal is strong and here to stay, maybe some incremental additional new features may be added.

If you wish to follow the examples along, grab a copy of the repository.

git clone https://github.com/indreklasn/payments-request-api-example.git && yarn && yarn start


This shell command will clone the repo, install the dependencies and start the server at ```localhost:3000```

![](https://miro.medium.com/max/60/1*y_w0PWTir-Oj8HL2IIt9vQ.png?q=20)

![](https://miro.medium.com/max/700/1*y_w0PWTir-Oj8HL2IIt9vQ.png)

You should see a very simple counter with a buy button

*Note; The payment API works on localhost for testing purposes.*

Since our app is simple, we’re going to place all payment related logic into the ```app.js``` file.

  })

  cartDecrementButton.addEventListener('click', () => {
    if (count === 0) return 
    count--
    countElement.innerHTML = `${count}
[Payment Request API ](https://www.w3.org/TR/payment-request/ "Payment Request API ")— a W3C browser standard that facilitates the exchange of payment and contact information.

The [Payment Request API](https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API "Payment Request API") provides a browser-based method of connecting users and their preferred payment systems and platforms to merchants that they want to pay for goods and services

![](https://miro.medium.com/max/700/1*-EHkIwadfV4b4lNN42Fcyg.png)

Payment Request API Goals — [https://www.w3.org/TR/payment-request/#goals](https://www.w3.org/TR/payment-request/#goals "https://www.w3.org/TR/payment-request/#goals")

This is a brilliant idea since the idea behind the *payment API* is to standardize how we pay for things, reduce friction when it comes to implementing accepting payments, and less volatile bugs.

What the *PaymentRequest API* looks like;

new PaymentRequest(methodData: fn, details: fn, options?);


As you can see, we create a new instance of the *payment API* with a constructor method. The payment constructor takes two mandatory parameters and one optional parameter:
* ```methodData``` — an object containing information concerning the payment provider, such as what payment methods are supported, etc.
* ```details``` — an object containing information concerning the specific payment, such as the total payment amount, tax, shipping cost, etc.
* ```options``` (optional) — an object containing additional options related to the payment.
## Payment API Demo

![](https://miro.medium.com/freeze/max/60/1*OQ07k84nrm47BlO-cmCKaw.gif?q=20)

![](https://miro.medium.com/max/700/1*OQ07k84nrm47BlO-cmCKaw.gif)

Payment API demo

As we can see, the payment is directly integrated into the browser. No more insecure third-party redirects or API calls, everything happens in the browser directly!
## Getting started the Payments Request API

The *Payment API* is experimental technology and is prone to change in the future. I still encourage getting familiar with this new [API](https://morioh.com/topic/api "API") since I believe the proposal is strong and here to stay, maybe some incremental additional new features may be added.

If you wish to follow the examples along, grab a copy of the repository.

git clone https://github.com/indreklasn/payments-request-api-example.git && yarn && yarn start


This shell command will clone the repo, install the dependencies and start the server at ```localhost:3000```

![](https://miro.medium.com/max/60/1*y_w0PWTir-Oj8HL2IIt9vQ.png?q=20)

![](https://miro.medium.com/max/700/1*y_w0PWTir-Oj8HL2IIt9vQ.png)

You should see a very simple counter with a buy button

*Note; The payment API works on localhost for testing purposes.*

Since our app is simple, we’re going to place all payment related logic into the ```app.js``` file.

  })
}

init()

Here’s some boilerplate code, we grab the DOM elements and hook them up with the increment and decrement buttons. We also show the final count to the user.

Imagine the increment as adding an item to the basket, decrement as removing the item from the basket, and count showing the total price to pay for the cart checkout.

Implementing the Payment Request API

buyButton.addEventListener('click', () => {

  const request = new PaymentRequest(buildSupportedPaymentMethodData(), buildShoppingCartDetails());

})

Once the user clicks on the “BUY” button, we create a new instance of the payment request. Now we need to define buildSupportedPaymentMethodData and buildShoppingCartDetails methods.

The first argument **<strong>buildSupportedPaymentMethodData</strong> is a method that returns an array of objects of all the supported payment methods.**

function buildSupportedPaymentMethodData() {
  // Example supported payment methods:
  return [{
    supportedMethods: 'basic-card',
    data: {
      supportedNetworks: ['visa', 'mastercard'],
      supportedTypes: ['debit', 'credit']
    }
  }];

The second argument **<strong>buildShoppingCartDetails</strong> is the information used to build up the purchase.**

For example, What the user is buying, how much it costs, what is the total sum, etc.

function buildShoppingCartDetails() {
  return {
    id: 'count-order',
    displayItems: [
      {
        label: 'Example item',
        amount: {currency: 'USD', value: '1.00'}
      }
    ],
    total: {
      label: 'Total',
      amount: {currency: 'USD', value: count }
    }
  };
}

Notice this time we return an object, instead of an array of objects.

Ok, we’re ready to show the payment request window to the user. Let’s call the show method on the request instance. This returns us a paymentResponse promise.

buyButton.addEventListener('click', () => {
  const request = new PaymentRequest(
    buildSupportedPaymentMethodData(),
    buildShoppingCartDetails()
  );
  request.show().then(paymentResponse => {
    console.log(paymentResponse)
  })
})

If we press the *“Buy” *button we should see this prompt;

Review your payment

You probably need to add a payment card. I recommend using the Visa test card. Insert the number, your name, address, etc. Those don’t have to valid for test purposes.

Visa test card

Adding a Visa test card

Handling the payment

Once we insert a card and approve the payment, we’re getting a paymentResponse returned from the promise request.

PaymentResponse — https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse

Since the payment is fulfilled now, all the methods and properties are read-only on the paymentResponse object.

Let’s call paymentResponse.complete() to indicate to the user everything went as expected.

<a href="https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse/complete" target="_blank"><strong>PaymentResponse.complete()</strong></a><strong> — </strong>https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse#Methods

buyButton.addEventListener('click', () => {

  const request = new PaymentRequest(buildSupportedPaymentMethodData(), buildShoppingCartDetails());
  request.canMakePayment().then(result => {

    if (result) {
      request.show().then(paymentResponse => {
        console.log(paymentResponse.details)
        // Here we would process the payment. For this demo, simulate immediate success:
        paymentResponse.complete('success')
          .then(() => thankYouMessage.style.opacity = 1)
      })
    }

  })
})

Voila! That’s all the code we need for our super simple shopping cart.

Full Payment Request API demo

Making a payment only with the Payment API

Here’s the source code in case you want to take a deeper dive.

Browser Support Payments API

https://caniuse.com/#search=payments%20api

Since this is a relatively new API, it’s not too well supported yet. Brave, Chrome, Safari, Firefox, Edge all support the new payments API and you can already try it on your browser.

On a side note, clearly, the new Payments API needs more work to be done, especially on mobile browsers. I wouldn’t rely on this API too much yet when it comes to mobile browsers.

web-development javascript

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Best Web and App Development Company in Ahmedabad

Contact DataPierce for any questions or queries you have about website development, designing, marketing projects or any small or enterprise software development.

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

For World Class Web Development Services in India visit RB Genie

Do you want excellent and world class web development services for your valuable projects? Contact **RB Genie **now, we have more than 8 years experienced team of web developers, which specializes in overall web design and website development...

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?