/stripe-guides

How to enable Google Pay in Stripe?

Learn how to enable Google Pay in Stripe with this step-by-step guide covering account setup, integration, testing, going live, branding, and monitoring.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to enable Google Pay in Stripe?

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:

  • Visit Stripe's website
  • Click on "Start now" or "Create account"
  • Complete the registration process with your business details
  • Verify your email address

 

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:

  • Go to "Settings" > "Payment methods"
  • Find "Google Pay" in the list of payment methods
  • Click "Enable" or toggle the switch to activate Google Pay
  • Confirm any additional requirements if prompted

 

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 Stripe's test mode with your test API keys
  • Make sure you're using a Chrome browser that supports Google Pay
  • Use a device with Google Pay set up or a test card in a compatible browser
  • Test the full payment flow using Stripe's test cards

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:

  • Switch from Stripe test keys to live keys
  • Update your code to use the live Stripe publishable key
  • Verify all URLs point to your production endpoints
  • Perform final testing in a staging environment
  • Launch your Google Pay-enabled checkout

 

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:

  • Use official Google Pay buttons and logos
  • Follow Google Pay brand guidelines
  • Display the Google Pay logo near other payment method options

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:

  • Monitor Stripe Dashboard for transaction data
  • Set up webhooks to track payment events
  • Analyze conversion rates for Google Pay vs. other payment methods
  • Address any issues that arise promptly

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.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022