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
- Add the
GooglePayButton
component to your React app. - Ensure your backend endpoint (
/process-google-pay
) is running and accessible. - Test the button in a browser that supports Google Pay with a test payment profile.