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 directly in the browser!

Getting started

The Payment API is experimental technology and is apt 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 will 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.

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

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

The first argument buildSupportedPaymentMethodData is a method that returns an array of objects of all the supported payment methods.

The second argument buildShoppingCartDetails shows the information used to build up the purchase.

This constitutes, for example, what the user is buying; how much it costs; and what is the total sum.

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 a paymentResponse promise. If you’re not too familiar with promises, check out this article.

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, and address. Those don’t have to be 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.

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 that everything went as expected.

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