How to Integrate Google Pay Payment Gateway in React Application
As a designer, you should manage installments when dealing with online business applications. Luckily, there are as of now arrangements accessible for you through authentic administrations. One such confided in arrangement that you'll find out about right now the Google Pay API.
The Google Pay API permits designers to effectively coordinate an installment technique that gives a streamlined, secure, and private experience for your clients or clients.
Why Use Google Pay
While tolerating installments, you'll most likely have a checkout structure where the client enters delivery and card subtleties. Be that as it may, this is what you'll have to consider: your clients don't recollect the 16-digit number, the security code, or the termination date of their credit or plastic. They may not confide in the site, despite the fact that it has a SSL authentication and there's a green lock on the location bar. On this, your client needs to manage entering similar subtleties on each web based business application.
Also Read:-How to Create a React Application and Deploy It on GitHub Pages
These components may cause rubbing for clients in the checkout stream and in this way decline deals. To assist you with building a consistent and straightforward checkout process, Google Pay API permits you helpful access to the client's card subtleties spared in their Google account. Along these lines, your clients don't need to enter the card subtleties physically into the checkout structure—you can automatically get them utilizing the Google Pay API.
Load the Google Pay API JavaScript Library
To start with, add the content tag to your application's index.html document to stack the Google Pay JavaScript library.
<script
async
src="https://pay.google.com/gp/p/js/pay.js"
onload="onGooglePayLoaded()"
></script>
Instate Google Pay API
When the content is stacked, develop the PaymentsClient object. Start by launching the customer object universally in the window object, which you will use to make calls to the Google Pay API from your segment later on.
function onGooglePayLoaded() {
window.googlePayClient = new google.payments.api.PaymentsClient({
environment: "TEST"
});
}
The payment gateway is instated with a PaymentOptions object. For the TEST condition, you don't have to enlist with Google. In the TEST condition, Google will offer access to genuine card subtleties, however you won't have the option to charge them. To empower real payments, you have to enroll with Google for PRODUCTION get to.
Also Read:-How to Render a React Component Inside a Bootstrap Popover
Design the Payment Methods
In the App.js record, characterize the card systems and the validation strategies that will be permitted by your application.
const { googlePayClient } = window;
const baseCardPaymentMethod = {
type: "CARD",
parameters: {
allowedCardNetworks: ["VISA", "MASTERCARD"],
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"]
}
};
Define the API Version
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.
const googlePayBaseConfiguration = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [baseCardPaymentMethod]
};
Decide Readiness to Pay With Google Pay
Since the installment customer is designed and characterized, check whether Google Pay API is prepared to make installments. This additionally incorporates checking whether the API is upheld for the present gadget and program.
Also Read:-How to Use Radio Buttons in ReactJS
Check the preparation when the part is mounted. On the off chance that it is a class segment, utilize the componentDidMount() lifecycle technique, and on the off chance that it is a practical segment, utilize the useEffect snare.
function App() {
// ...
useEffect(() => {
googlePayClient
.isReadyToPay(googlePayBaseConfiguration)
.then(res => {
if (res.result) {
createAndRenderPayButton();
} else {
alert("Unable to pay using Google Pay");
}
})
.catch(function (err) {
console.error("Error determining readiness to use Google Pay: ", err);
});
}, []);
// ...
}
The isReadyToPay() strategy takes in the base design as its contention and decide status to pay. As it is nonconcurrent in nature, you have to join the .at that point() and .catch() calls to it. In the event that there's an effective reaction, render the Google Pay Button to the client. Something else, show elective installment techniques as a fallback.
Include the Pay With GPay Button
Presently, when you realize that the client is prepared to make an installment, call the subsequent API, createButton(). The createButton() strategy will restore the Pay with GPay button HTML component. You can pass alternatives like buttonColor and buttonType to style the catch so it mixes in well with your general site hues. You can discover more information on the alternatives here.
Set the catch HTML in your part's state so it tends to be rendered by JSX utilizing the dangerouslySetInnerHTML prop.
const [gPayBtn, setGPayBtn] = useState(null);
function createAndAddButton() {
if (googlePayClient) {
const googlePayButton = googlePayClient.createButton({
buttonColor: "default",
buttonType: "long",
onClick: processPayment
});
setGPayBtn(googlePayButton);
}
}
return (
<div className="App">
<h1>Click the Pay button</h1>
<div
onClick={processPayment}
dangerouslySetInnerHTML={{ __html: gPayBtn && gPayBtn.innerHTML }}
/>
</div>
);
At the point when the catch is clicked, call processPayment(), which will begin the Payment procedure.
Payment
When you add the catch to your page and the client taps on the Google Pay Button, call the loadPaymentData() strategy to open up the Google Pay Payment window. Build the paymentDataRequest object, which incorporates a lot of Payment arrangements which will be utilized for this specific exchange.
function processPayment() {
// ...
googlePayClient
.loadPaymentData(paymentDataRequest)
.then(function (paymentData) {
console.log(paymentData);
})
.catch(function (err) {
console.log(err);
});
}
Notwithstanding the Payment accreditations, you can likewise demand extra data, for example, email, telephone number, delivering address, charging address, and so forth.
const cardPaymentMethod = {
type: "CARD",
tokenizationSpecification: tokenizationSpecification,
parameters: {
allowedCardNetworks: ["VISA", "MASTERCARD"],
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
billingAddressRequired: true,
billingAddressParameters: {
format: "FULL",
phoneNumberRequired: true
}
}
};
The exchange and dealer data, alongside the base arrangement object, ought to be remembered for the paymentDataRequest object.
const transactionInfo = {
totalPriceStatus: "FINAL",
totalPrice: "123.45",
currencyCode: "USD"
};
const merchantInfo = {
// merchantId: '01234567890123456789', Only in PRODUCTION
merchantName: "Your Merchant Name"
};
const paymentDataRequest = {
...googlePayBaseConfiguration,
...{
allowedPaymentMethods: [cardPaymentMethod],
transactionInfo,
merchantInfo
}
};
tokenizationSpecification is an item which contains the Payment demand tokenization parameters. Here, you characterize which Payment entryway you'll be utilizing in your application.
const tokenizationSpecification = {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "example",
gatewayMerchantId: "gatewayMerchantId"
}
};
In this guide, you'll use the Stripe Processor, but there are a bunch of other options available.
const tokenizationSpecification = {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "stripe",
"stripe:version": "v3",
"stripe:publishableKey": YOUR_STRIPE_PUBLISHABLE_KEY
}
};
The tokenization detail characterizes how the installment technique picked by your clients is overseen and used to finish an exchange. At the point when you've built the solicitation object, pass it to loadPaymentData, an async call which will open a Google installment sheet. After the client makes a choice, Google will return you a paymentData object, which comprises of metadata about the client's choice. It incorporates the installment token, which you can use to finish the exchange. Now, you have done the entirety of the necessary advances, and your exchange is fit to be finished.
Also Read:-How to Implement Stripe Payment Gateway In React
Complete Source Code
Underneath you'll locate the total code for your reference.
import React, { useState, useEffect } from "react";
import "./styles.css";
const { googlePayClient } = window;
const baseCardPaymentMethod = {
type: "CARD",
parameters: {
allowedCardNetworks: ["VISA", "MASTERCARD"],
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"]
}
};
const googlePayBaseConfiguration = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [baseCardPaymentMethod]
};
export default function App() {
const [gPayBtn, setGPayBtn] = useState(null);
function createAndAddButton() {
if (googlePayClient) {
const googlePayButton = googlePayClient.createButton({
buttonColor: "default",
buttonType: "long",
onClick: processPayment
});
setGPayBtn(googlePayButton);
}
}
function processPayment() {
console.log("test");
const tokenizationSpecification = {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "stripe",
"stripe:version": "v3",
"stripe:publishableKey": "pk_test_35p114pH8oNuHX72SmrvsFqh00Azv3ZaIA"
}
};
const cardPaymentMethod = {
type: "CARD",
tokenizationSpecification: tokenizationSpecification,
parameters: {
allowedCardNetworks: ["VISA", "MASTERCARD"],
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
billingAddressRequired: true,
billingAddressParameters: {
format: "FULL",
phoneNumberRequired: true
}
}
};
const transactionInfo = {
totalPriceStatus: "FINAL",
totalPrice: "123.45",
currencyCode: "USD"
};
const merchantInfo = {
// merchantId: '01234567890123456789', Only in PRODUCTION
merchantName: "Example Merchant Name"
};
const paymentDataRequest = {
...googlePayBaseConfiguration,
...{
allowedPaymentMethods: [cardPaymentMethod],
transactionInfo,
merchantInfo
}
};
googlePayClient
.loadPaymentData(paymentDataRequest)
.then(function (paymentData) {
console.log(paymentData);
})
.catch(function (err) {
console.log(err);
});
}
useEffect(() => {
googlePayClient
.isReadyToPay(googlePayBaseConfiguration)
.then(function (response) {
if (response.result) {
createAndAddButton();
} else {
alert("Unable to pay using Google Pay");
}
})
.catch(function (err) {
console.error("Error determining readiness to use Google Pay: ", err);
});
}, []);
return (
<div className="App">
<h1>Click the Pay button</h1>
<div
onClick={processPayment}
dangerouslySetInnerHTML={{ __html: gPayBtn && gPayBtn.innerHTML }}
/>
</div>
);
}
Conclusion
Right now, have figured out how to actualize Google Pay API in your React application. Given the way that the checkout procedure can be one of the most exceedingly terrible encounters a client faces, you ought to consider incorporating Google Pay with all your web based business applications. Keep in mind, Google Pay API won't process the installment; it will be finished by an installment processor like Stripe or Paypal. Google Pay assumes an essential job in encouraging the trading of touchy data between the client and the installment processor.
Also Read:-How to Create Chat App Using WebSockets in React/Redux App
Ideally, these essential directions gave a general outline of the installment procedure stream with Google Pay and how to execute it with the Google Pay API.