Are you interested in attending a Google Pay launchathon in your city? Let us know!

Tutorial

The following steps show how to integrate a web application with the Google Pay API.

Step 1: Load the Google Pay API JavaScript library

Include Google's hosted JavaScript on your page.

<script
  src="https://payments.developers.google.com/js/apis/pay.js">
</script>

Initialize a PaymentsClient object.

var paymentsClient =
    new google.payments.api.PaymentsClient({environment: 'TEST'});

Step 2: Discover Google Pay API support

Define the methods of payment supported by your payment processor.

var allowedPaymentMethods = ['CARD', 'TOKENIZED_CARD'];

Call isReadyToPay() to determine if the Google Pay API is supported by the current browser and possible logged-in Google user.

paymentsClient.isReadyToPay({allowedPaymentMethods: allowedPaymentMethods})
    .then(function(response) {
      if (response.result) {
        // add button
      }
    })
    .catch(function(err) {
      // show error in developer console for debugging
      console.error(err);
    });

Step 3: Add a purchase button

Add a Google-branded purchase button to your page to encourage a shopper to check out using a payment method supported by the Google Pay API and your site. See brand guidelines for more information.

var button = document.createElement('button');
button.id = 'google-pay';
button.appendChild(document.createTextNode('Google Pay'));
document.getElementById('container').appendChild(button);

Step 4: Create a PaymentDataRequest object

Build a JavaScript object describing the payment methods and the payment gateway or decryption key supported by your site. Check with your payment gateway for specific fields relevant to your setup.

var paymentDataRequest = {
  // a merchant ID is available after approval by Google
  merchantId: '01234567890123456789',
  paymentTokenizationParameters: {
    tokenizationType: 'PAYMENT_GATEWAY',
    // tokenization parameters are provided by your gateway
    parameters: {}
  },
  allowedPaymentMethods: allowedPaymentMethods,
  cardRequirements: {
    allowedCardNetworks: ['AMEX', 'DISCOVER', 'MASTERCARD', 'VISA']
  }
};

Define a total price and currency you would like a shopper to authorize.

paymentDataRequest.transactionInfo = {
  totalPriceStatus: 'FINAL',
  totalPrice: '123.45',
  currencyCode: 'USD'
};

Step 5: Register event handler

Register a click event handler for the purchase button calling loadPaymentData().

Handle the response from the Google Pay API after a Google user has granted permission for your site to receive their payment data and optional contact data.

paymentsClient.loadPaymentData(paymentDataRequest).then(function(paymentData){
  // process paymentData
}).catch(function(err){
  // show error in developer console for debugging
  console.error(err);
});

Step 6 (optional): Prefetch payment data before user interaction

Prefetch your website's payment configuration from the Google Pay API before calling loadPaymentData() to improve execution time.

Note: add pretech functionality in your code only after successfully implementing the Google Pay API without the optimization.

paymentsClient.prefetchPaymentData(paymentDataRequest);

Putting it all together

The following example shows a complete end-to-end example using the Google Pay API JavaScript library.

<div id="container">
  <button>Checkout</button>
</div>
<script>
var allowedPaymentMethods = ['CARD', 'TOKENIZED_CARD'];
var allowedCardNetworks = ['AMEX', 'DISCOVER', 'MASTERCARD', 'VISA'];

/**
 * Initialize a Google Pay API client
 *
 * @returns {google.payments.api.PaymentsClient} Google Pay API client
 */
function getPaymentsClient() {
  return (new google.payments.api.PaymentsClient({environment: 'TEST'}));
}

/**
 * Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
 */
function initializeGooglePaymentsClient() {
  var paymentsClient = getPaymentsClient();
  paymentsClient.isReadyToPay({allowedPaymentMethods: allowedPaymentMethods})
      .then(function(response) {
        if (response.result) {
          addGooglePaymentButton();
          prefetchGooglePaymentData();
        }
      })
      .catch(function(err) {
        // show error in developer console for debugging
        console.error(err);
      });
}

/**
 * Add a Google Pay purchase button alongside an existing checkout button
 */
function addGooglePaymentButton() {
  var button = document.createElement('button');
  button.id = 'google-pay';
  button.appendChild(document.createTextNode('Google Pay'));
  button.addEventListener('click', onGooglePaymentButtonClicked);
  document.getElementById('container').appendChild(button);
}

/**
 * Configure support for the Google Pay API
 *
 * @see {@link https://developers.google.com/payments/web/object-reference#PaymentDataRequest|PaymentDataRequest}
 * @returns {object} PaymentDataRequest fields
 */
function getGooglePaymentDataConfiguration() {
  return {
    // a merchant ID is available after approval by Google
    merchantId: '01234567890123456789',
    paymentMethodTokenizationParameters: {
      tokenizationType: 'PAYMENT_GATEWAY',
      // Check with your payment gateway on the parameters to pass.
      // @see {@link https://developers.google.com/payments/web/object-reference#gateway}
      parameters: {}
    },
    allowedPaymentMethods: allowedPaymentMethods,
    cardRequirements: {allowedCardNetworks: allowedCardNetworks}
  };
}

/**
 * Provide Google Pay API with a payment amount, currency, and amount status
 *
 * @see {@link https://developers.google.com/payments/web/object-reference#TransactionInfo|TransactionInfo}
 * @returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest
 */
function getGoogleTransactionInfo() {
  return {
    currencyCode: 'USD',
    totalPriceStatus: 'FINAL',
    // set to cart total
    totalPrice: '1.00'
  };
}

/**
 * Prefetch payment data to improve performance
 */
function prefetchGooglePaymentData() {
  var paymentDataRequest = getGooglePaymentDataConfiguration();
  // transactionInfo must be set but does not affect cache
  paymentDataRequest.transactionInfo = {
    totalPriceStatus: 'NOT_CURRENTLY_KNOWN',
    currencyCode: 'USD'
  };
  var paymentsClient = getPaymentsClient();
  paymentsClient.prefetchPaymentData(paymentDataRequest);
}

/**
 * Show Google Pay chooser when Google Pay purchase button is clicked
 */
function onGooglePaymentButtonClicked() {
  var paymentDataRequest = getGooglePaymentDataConfiguration();
  paymentDataRequest.transactionInfo = getGoogleTransactionInfo();

  var paymentsClient = getPaymentsClient();
  paymentsClient.loadPaymentData(paymentDataRequest)
      .then(function(paymentData) {
        // handle response
        processPayment(paymentData);
      })
      .catch(function(err) {
        // show error in developer console for debugging
        console.error(err);
      });
}

/**
 * Process payment data returned by the Google Pay API
 *
 * @param {object} paymentData response from Google Pay API after shopper approves payment
 * @see {@link https://developers.google.com/payments/web/object-reference##paymentdata|PaymentData object reference}
 */
function processPayment(paymentData) {
  console.log(paymentData);
}
</script>
<script async
  src="https://payments.developers.google.com/js/apis/pay.js"
  onload="initializeGooglePaymentsClient()"></script>

Send feedback about...

Google Pay API