As a developer, you will have to deal with payments when working on e-commerce applications. Fortunately, there are already solutions available for you through legitimate services. One such trusted solution that you'll learn about in this guide is the Google Pay API.
The Google Pay API allows developers to easily integrate a payment method that provides a streamlined, secure, and confidential experience for your users or customers.
When accepting payments, you'll probably have a checkout form where the user enters shipping and card details. But here's what you'll need to consider: your customers do not remember the 16-digit number, the security code, or the expiration date of their credit or debit card. They may not trust the website, even though it has an SSL certificate and there's a green lock on the address bar. On top of this, your user has to deal with entering the same details on every e-commerce application.
These factors may cause friction for users in the checkout flow and thereby decrease sales. To help you build a seamless and simple checkout process, Google Pay API allows you convenient access to the user's card details saved in their Google account. This way, your users do not have to enter the card details manually into the checkout form—you can programmatically fetch them using the Google Pay API.
First, add the script tag to your application's index.html file to load the Google Pay JavaScript library.
1<script
2 async
3 src="https://pay.google.com/gp/p/js/pay.js"
4 onload="onGooglePayLoaded()"
5></script>
As soon as the script is loaded, construct the PaymentsClient
object. Begin by instantiating the client object globally in the window object, which you will use to make calls to the Google Pay API from your component later on.
1function onGooglePayLoaded() {
2 window.googlePayClient = new google.payments.api.PaymentsClient({
3 environment: "TEST"
4 });
5}
The payment client is initialized with a PaymentOptions
object. For the TEST environment, you don't need to register with Google. In the TEST environment, Google will give access to real card details, but you won't be able to charge them. To enable actual payments, you need to register with Google for PRODUCTION access.
In the App.js file, define the card networks and the authentication methods that will be allowed by your application.
1const { googlePayClient } = window;
2
3const baseCardPaymentMethod = {
4 type: "CARD",
5 parameters: {
6 allowedCardNetworks: ["VISA", "MASTERCARD"],
7 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"]
8 }
9};
After you have configured the payment methods, define the Google Pay API version that will be used to process the payment, along with the allowedPaymentMethods
property to which you need to pass the baseCardPaymentMethod
object.
1const googlePayBaseConfiguration = {
2 apiVersion: 2,
3 apiVersionMinor: 0,
4 allowedPaymentMethods: [baseCardPaymentMethod]
5};
Now that the payment client is configured and defined, check whether Google Pay API is ready to make payments. This also includes checking whether the API is supported for the current device and browser.
Check the readiness as soon as the component is mounted. If it is a class component, use the componentDidMount()
lifecycle method, and if it is a functional component, use the useEffect
hook.
1function App() {
2 // ...
3 useEffect(() => {
4 googlePayClient
5 .isReadyToPay(googlePayBaseConfiguration)
6 .then(res => {
7 if (res.result) {
8 createAndRenderPayButton();
9 } else {
10 alert("Unable to pay using Google Pay");
11 }
12 })
13 .catch(function (err) {
14 console.error("Error determining readiness to use Google Pay: ", err);
15 });
16 }, []);
17 // ...
18}
The isReadyToPay()
method takes in the base configuration as its argument and determine readiness to pay. As it is asynchronous in nature, you need to attach the .then()
and .catch()
calls to it. If there's a successful response, render the Google Pay Button to the user. Otherwise, show alternative payment methods as a fallback.
Once you add the button to your page and the user clicks on the Google Pay Button, call the loadPaymentData()
method to open up the Google Pay payment window. Construct the paymentDataRequest
object, which includes a set of payment configurations which will be used for this particular transaction.
1function processPayment() {
2 // ...
3 googlePayClient
4 .loadPaymentData(paymentDataRequest)
5 .then(function (paymentData) {
6 console.log(paymentData);
7 })
8 .catch(function (err) {
9 console.log(err);
10 });
11}
In addition to the payment credentials, you can also request additional information such as email, phone number, shipping address, billing address, etc.
1const cardPaymentMethod = {
2 type: "CARD",
3 tokenizationSpecification: tokenizationSpecification,
4 parameters: {
5 allowedCardNetworks: ["VISA", "MASTERCARD"],
6 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
7 billingAddressRequired: true,
8 billingAddressParameters: {
9 format: "FULL",
10 phoneNumberRequired: true
11 }
12 }
13};
The transaction and merchant information, along with the base configuration object, should be included in the paymentDataRequest
object.
1const transactionInfo = {
2 totalPriceStatus: "FINAL",
3 totalPrice: "123.45",
4 currencyCode: "USD"
5};
6
7const merchantInfo = {
8 // merchantId: '01234567890123456789', Only in PRODUCTION
9 merchantName: "Your Merchant Name"
10};
11
12const paymentDataRequest = {
13 ...googlePayBaseConfiguration,
14 ...{
15 allowedPaymentMethods: [cardPaymentMethod],
16 transactionInfo,
17 merchantInfo
18 }
19};
tokenizationSpecification
is an object which contains the payment request tokenization parameters. Here, you define which payment gateway you'll be using in your application.
1const tokenizationSpecification = {
2 type: "PAYMENT_GATEWAY",
3 parameters: {
4 gateway: "example",
5 gatewayMerchantId: "gatewayMerchantId"
6 }
7};
In this guide, you'll use the Stripe Processor, but there are a bunch of other options available.
1const tokenizationSpecification = {
2 type: "PAYMENT_GATEWAY",
3 parameters: {
4 gateway: "stripe",
5 "stripe:version": "v3",
6 "stripe:publishableKey": YOUR_STRIPE_PUBLISHABLE_KEY
7 }
8};
The tokenization specification defines how the payment method chosen by your customers is managed and used to complete a transaction. When you've constructed the request object, pass it to loadPaymentData, an async call which will open a Google payment sheet. After the user makes a selection, Google will return you a paymentData
object, which consists of metadata about the user's selection. It includes the payment token, which you can use to complete the transaction. At this point, you have carried out all of the required steps, and your transaction is ready to be completed.
To learn more about handling the card token, check out this Stripe Integration guide.
Below you'll find the complete code for your reference.
1import React, { useState, useEffect } from "react";
2import "./styles.css";
3
4const { googlePayClient } = window;
5
6const baseCardPaymentMethod = {
7 type: "CARD",
8 parameters: {
9 allowedCardNetworks: ["VISA", "MASTERCARD"],
10 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"]
11 }
12};
13
14const googlePayBaseConfiguration = {
15 apiVersion: 2,
16 apiVersionMinor: 0,
17 allowedPaymentMethods: [baseCardPaymentMethod]
18};
19
20export default function App() {
21 const [gPayBtn, setGPayBtn] = useState(null);
22
23 function createAndAddButton() {
24 if (googlePayClient) {
25 const googlePayButton = googlePayClient.createButton({
26 buttonColor: "default",
27
28 buttonType: "long",
29
30 onClick: processPayment
31 });
32
33 setGPayBtn(googlePayButton);
34 }
35 }
36
37 function processPayment() {
38 console.log("test");
39 const tokenizationSpecification = {
40 type: "PAYMENT_GATEWAY",
41 parameters: {
42 gateway: "stripe",
43 "stripe:version": "v3",
44 "stripe:publishableKey": "pk_test_35p114pH8oNuHX72SmrvsFqh00Azv3ZaIA"
45 }
46 };
47
48 const cardPaymentMethod = {
49 type: "CARD",
50 tokenizationSpecification: tokenizationSpecification,
51 parameters: {
52 allowedCardNetworks: ["VISA", "MASTERCARD"],
53 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
54 billingAddressRequired: true,
55 billingAddressParameters: {
56 format: "FULL",
57 phoneNumberRequired: true
58 }
59 }
60 };
61
62 const transactionInfo = {
63 totalPriceStatus: "FINAL",
64 totalPrice: "123.45",
65 currencyCode: "USD"
66 };
67
68 const merchantInfo = {
69 // merchantId: '01234567890123456789', Only in PRODUCTION
70 merchantName: "Example Merchant Name"
71 };
72
73 const paymentDataRequest = {
74 ...googlePayBaseConfiguration,
75 ...{
76 allowedPaymentMethods: [cardPaymentMethod],
77 transactionInfo,
78 merchantInfo
79 }
80 };
81
82 googlePayClient
83 .loadPaymentData(paymentDataRequest)
84 .then(function (paymentData) {
85 console.log(paymentData);
86 })
87 .catch(function (err) {
88 console.log(err);
89 });
90 }
91
92 useEffect(() => {
93 googlePayClient
94 .isReadyToPay(googlePayBaseConfiguration)
95 .then(function (response) {
96 if (response.result) {
97 createAndAddButton();
98 } else {
99 alert("Unable to pay using Google Pay");
100 }
101 })
102 .catch(function (err) {
103 console.error("Error determining readiness to use Google Pay: ", err);
104 });
105 }, []);
106
107 return (
108 <div className="App">
109 <h1>Click the Pay button</h1>
110 <div
111 onClick={processPayment}
112 dangerouslySetInnerHTML={{ __html: gPayBtn && gPayBtn.innerHTML }}
113 />
114 </div>
115 );
116}
In this guide, you have learned how to implement Google Pay API in your React application. Given the fact that the checkout process can be one of the worst experiences a user faces, you should consider integrating Google Pay with all your e-commerce applications. Remember, Google Pay API won't process the payment; it will be done by a payment processor like Stripe or Paypal. Google Pay plays a vital role in facilitating the exchange of sensitive information between the user and the payment processor.
Hopefully, these basic instructions gave a general overview of the payment process flow with Google Pay and how to implement it with the Google Pay API.