Adding a Google Pay Button to React with Backend Support

Mo Sharif
3 min readJan 19, 2025

--

grok generated image

Google Pay is a powerful payment method for your app. This guide will walk you through implementing a Google Pay button in your React application, covering both the frontend and backend steps.

Step 1: Frontend Google Pay Button

Google Pay Payment Request Configuration

Start by creating a Google Pay payment request. This request defines details like the allowed payment methods, transaction details, and merchant information.

const googlePayClient = new google.payments.api.PaymentsClient({
environment: "TEST", // Change to 'PRODUCTION' when ready
});

const paymentRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [
{
type: "CARD",
parameters: {
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
allowedCardNetworks: ["VISA", "MASTERCARD"],
},
tokenizationSpecification: {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "example", // Replace with your payment gateway
gatewayMerchantId: "exampleMerchantId", // Replace with your merchant ID
},
},
},
],
transactionInfo: {
totalPriceStatus: "FINAL",
totalPrice: "10.00",
currencyCode: "USD",
},
merchantInfo: {
merchantId: "YOUR_MERCHANT_ID", // Replace with your Google Pay merchant ID
merchantName: "Your Store",
},
};

Checking Google Pay Availability

Before rendering the button, check if Google Pay is available on the user’s device.

const checkGooglePayAvailability = async () => {
const isReadyToPay = await googlePayClient.isReadyToPay({
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: paymentRequest.allowedPaymentMethods,
});
return isReadyToPay.result;
};

Handling Button Click

Handle the button click to create a payment data request and process the response.

const handleGooglePayClick = async () => {
try {
const paymentData = await googlePayClient.loadPaymentData(paymentRequest);

// Send the payment token to your backend for processing
const response = await fetch("/process-google-pay", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: paymentData.paymentMethodData.tokenizationData.token }),
});

const result = await response.json();

if (result.success) {
alert("Payment successful!");
} else {
alert("Payment failed. Please try again.");
}
} catch (error) {
console.error("Google Pay error:", error);
alert("Payment process failed.");
}
};

Full Google Pay Button Component

Combine the above pieces into a complete component.

const GooglePayButton = () => {
const [isAvailable, setIsAvailable] = React.useState(false);

React.useEffect(() => {
checkGooglePayAvailability().then(setIsAvailable);
}, []);

if (!isAvailable) return null;

return (
<button onClick={handleGooglePayClick} className="google-pay-button">
Pay with Google
</button>
);
};

export default GooglePayButton;

Step 2: Styling the Google Pay Button

Here’s a simple CSS style for the Google Pay button:

.google-pay-button {
background-color: #4285f4;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
}
.google-pay-button:hover {
background-color: #357ae8;
}
.google-pay-button:active {
background-color: #2a65c8;
}

Step 3: Backend Setup for Payment Processing

Google Pay requires a backend to process the payment token. Here’s how to set it up.

Payment Processing Endpoint

Here’s an example of processing the token with Stripe.

import Stripe from "stripe";
const stripe = new Stripe("your-stripe-secret-key");

export const processGooglePay = async (req, res) => {
const { token } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: 1000, // Amount in cents
currency: "USD",
payment_method_data: {
type: "card",
card: { token },
},
confirm: true,
});
res.json({ success: true, paymentIntent });
} catch (error) {
console.error("Payment processing error:", error);
res.status(500).json({ success: false, error: error.message });
}
};

Step 4: Testing the Integration

  1. Add the GooglePayButton component to your React app.
  2. Ensure your backend endpoint (/process-google-pay) is running and accessible.
  3. Test the button in a browser that supports Google Pay with a test payment profile.

--

--

Mo Sharif
Mo Sharif

Written by Mo Sharif

Hello, I'm Mo Sharif, a founder and passionate FE software engineer.

No responses yet