Learn how to enable Google Pay in Stripe with this step-by-step guide covering account setup, integration, testing, going live, branding, and monitoring.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
How to Enable Google Pay in Stripe: A Comprehensive Tutorial
Step 1: Create a Stripe Account
Before setting up Google Pay with Stripe, ensure you have a Stripe account. If you don't have one yet:
Step 2: Install Stripe's JavaScript Library
Include Stripe's JavaScript library in your website. Add the following script tag to your HTML file, preferably just before the closing
tag:
Step 3: Configure Your Stripe Account for Google Pay
In your Stripe Dashboard:
Step 4: Set Up Your Payment Environment
Initialize the Stripe object with your publishable key in your JavaScript file:
// Initialize Stripe with your publishable key
const stripe = Stripe('pk_test_your_publishable_key');
// Create a payment request object
const paymentRequest = stripe.paymentRequest({
country: 'US', // Replace with your country
currency: 'usd', // Replace with your currency
total: {
label: 'Total',
amount: 1000, // Amount in cents
},
requestPayerName: true,
requestPayerEmail: true,
});
Step 5: Check if Google Pay is Available
Before showing the Google Pay button, check if the payment method is available for the user:
// Check the availability of the Payment Request API
paymentRequest.canMakePayment().then(function(result) {
if (result && result.googlePay) {
// Google Pay is available, show Google Pay button
const googlePayButton = document.getElementById('google-pay-button');
googlePayButton.style.display = 'block';
} else {
// Google Pay is not available, hide or disable the button
console.log('Google Pay is not available in this browser');
}
});
Step 6: Create a Payment Request Button Element
Add a container element in your HTML for the Google Pay button:
Then create the button using Stripe's Elements:
// Create a PaymentRequestButton element
const prButton = elements.create('paymentRequestButton', {
paymentRequest: paymentRequest,
style: {
paymentRequestButton: {
type: 'pay', // 'default', 'book', 'donate', or 'pay'
theme: 'dark', // 'dark', 'light', or 'light-outline'
height: '40px' // default is '40px', can be any custom value
}
}
});
// Check if the Payment Request is available before mounting
paymentRequest.canMakePayment().then(function(result) {
if (result && result.googlePay) {
prButton.mount('#google-pay-button');
} else {
document.getElementById('google-pay-button').style.display = 'none';
}
});
Step 7: Handle the Payment
Listen for the 'paymentmethod' event to handle the payment when a user completes the Google Pay process:
paymentRequest.on('paymentmethod', function(event) {
// Send the payment method ID to your server to complete the payment
fetch('/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
paymentMethodId: event.paymentMethod.id,
amount: 1000, // Amount in cents
}),
})
.then(function(response) {
return response.json();
})
.then(function(responseJson) {
if (responseJson.error) {
// Show error to your customer
event.complete('fail');
console.error(responseJson.error);
} else {
// The payment succeeded!
event.complete('success');
console.log('Payment successful!');
// Handle post-payment actions like redirecting to a success page
}
})
.catch(function(error) {
// Show error to your customer
event.complete('fail');
console.error('Error:', error);
});
});
Step 8: Create a Server-Side Endpoint to Handle Payments
Set up a server endpoint to process the payment. Here's an example using Node.js with Express:
const express = require('express');
const app = express();
const stripe = require('stripe')('sk_test_your_secret_key');
app.use(express.json());
app.post('/create-payment-intent', async (req, res) => {
try {
const { paymentMethodId, amount } = req.body;
// Create a PaymentIntent with the payment method ID
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: 'usd',
payment\_method: paymentMethodId,
confirmation\_method: 'manual',
confirm: true,
return\_url: 'https://yourwebsite.com/success',
});
// Handle different PaymentIntent statuses
if (
paymentIntent.status === 'requires\_action' &&
paymentIntent.next_action.type === 'use_stripe\_sdk'
) {
// The payment requires additional actions
res.json({
requires\_action: true,
payment_intent_client_secret: paymentIntent.client_secret,
});
} else if (paymentIntent.status === 'succeeded') {
// The payment succeeded
res.json({ success: true });
} else {
// The payment failed for some other reason
res.json({
error: 'Payment failed',
});
}
} catch (error) {
res.json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Step 9: Test Your Google Pay Implementation
To test your Google Pay integration:
Use this test card number for Google Pay testing: 4242 4242 4242 4242
Step 10: Go Live with Your Google Pay Integration
When you're ready to move to production:
Step 11: Implement Error Handling and Fallbacks
Add robust error handling to account for different scenarios:
// Add comprehensive error handling
paymentRequest.on('cancel', function() {
console.log('User canceled the payment');
// Handle cancellation (e.g., show a message or redirect)
});
// Fallback for browsers without Google Pay support
if (!window.PaymentRequest) {
document.getElementById('google-pay-button').style.display = 'none';
// Show alternative payment methods
document.getElementById('alternative-payment-methods').style.display = 'block';
}
Step 12: Add Google Pay Branding
Ensure your implementation follows Google Pay's branding guidelines:
You can add custom Google Pay branding with CSS:
#google-pay-button {
margin: 10px 0;
max-width: 300px;
}
/_ Add Google Pay badge to your checkout page _/
.payment-method-options {
display: flex;
align-items: center;
}
.payment-method-badge {
height: 24px;
margin-right: 10px;
}
Step 13: Monitor Your Google Pay Integration
After going live:
Add webhook handling for better monitoring:
// Server-side webhook handling example
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
sig,
'whsec_your_webhook_signing_secret'
);
} catch (err) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle specific events
switch (event.type) {
case 'payment\_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
// Then define and call a function to handle the successful payment
break;
case 'payment\_method.attached':
const paymentMethod = event.data.object;
console.log('PaymentMethod was attached to a Customer!');
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
res.json({received: true});
});
By following these detailed steps, you'll have a fully functional Google Pay integration with Stripe, offering your customers a seamless and secure payment experience.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.