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: Choose a tokenization method

Google encrypts information about a shopper's selected card for secure processing by a merchant's gateway or directly on a merchant's secured servers.

Gateway

var tokenizationParameters = {
  tokenizationType: 'PAYMENT_GATEWAY',
  parameters: {
    gateway: 'example',
    gatewayMerchantId: 'exampleGatewayMerchantId'
  }
}

Replace example with a gateway identifier of a Google-supported gateway and exampleGatewayMerchantId with a unique merchant identifier provided by your gateway.

See gateway tokenization documentation for more information about supported gateways and unique identifiers. The PAYMENT_GATEWAY tokenization type is the most common merchant implementation of the Google Pay API.

Direct

var tokenizationParameters = {
  tokenizationType: 'DIRECT',
  parameters: {
    publicKey: 'yourPublicKey'
  }
}

Replace yourPublicKey with a public key you registered with Google to receive payment information encrypted with that key. See our payment data cryptography documentation for information about configuring encryption keys suitable for the Google Pay API.

Step 2: Define supported payment card networks

Define the card networks accepted by your site. The Google Pay API may return cards on file on Google.com and/or a device token on an Android device.

var allowedCardNetworks = ['AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA'];
var allowedPaymentMethods = ['CARD', 'TOKENIZED_CARD'];

Step 3: 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 pay/apiClient object. Initial development will use a TEST environment returning dummy payment methods suitable for testing. See Test and deploy for more information about requirements for a PRODUCTION environment returning chargeable payment methods.

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

Step 4: Determine readiness to pay with the Google Pay API

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 a Google Pay button
      }
    })
    .catch(function(err) {
      // show error in developer console for debugging
      console.error(err);
    });

Step 5: Add a Google Pay button

Add a Google Pay 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.appendChild(document.createTextNode('Google Pay'));
document.getElementById('container').appendChild(button);

Step 6: Create a PaymentDataRequest object

Build a JavaScript object describing your site's support for the Google Pay API. See PaymentDataRequest for a full list of supported properties.

var paymentDataRequest = {
  // a merchant ID is not required when a PaymentsClient environment is set to TEST
  // a merchant ID is available for a production environment after approval by Google
  // merchantId: '01234567890123456789',
  paymentMethodTokenizationParameters: tokenizationParameters,
  },
  allowedPaymentMethods: allowedPaymentMethods,
  cardRequirements: {
    allowedCardNetworks: allowedCardNetworks
  }
};

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

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

Step 7: Register event handler for user gesture

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 8 (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">
  <!-- An existing checkout button -->
  <button>Checkout</button>
</div>

<script>
/**
 * Payment methods accepted by your gateway
 *
 * @todo confirm support for both payment methods with your gateway
 */
var allowedPaymentMethods = ['CARD', 'TOKENIZED_CARD'];

/**
 * Card networks supported by your site and your gateway
 *
 * @see {@link https://developers.google.com/pay/api/web/object-reference#CardRequirements|CardRequirements}
 * @todo confirm card networks supported by your site and gateway
 */
var allowedCardNetworks = ['AMEX', 'DISCOVER', 'JCB', 'MASTERCARD', 'VISA'];

/**
 * Identify your gateway and your site's gateway merchant identifier
 *
 * The Google Pay API response will return an encrypted payment method capable of
 * being charged by a supported gateway after shopper authorization
 *
 * @todo check with your gateway on the parameters to pass
 * @see {@link https://developers.google.com/pay/api/web/object-reference#Gateway|PaymentMethodTokenizationParameters}
 */
var tokenizationParameters = {
  tokenizationType: 'PAYMENT_GATEWAY',
  parameters: {
    'gateway': 'example',
    'gatewayMerchantId': 'abc123'
  }
}

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

/**
 * Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
 */
function onGooglePayLoaded() {
  var paymentsClient = getGooglePaymentsClient();
  paymentsClient.isReadyToPay({allowedPaymentMethods: allowedPaymentMethods})
      .then(function(response) {
        if (response.result) {
          addGooglePayButton();
          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
 *
 * @see {@link https://developers.google.com/pay/api/brand-guidelines|Google Pay brand guidelines}
 */
function addGooglePayButton() {
  var button = document.createElement('button');
  // identify the element to apply Google Pay branding in related CSS
  button.className = '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/pay/api/web/object-reference#PaymentDataRequest|PaymentDataRequest}
 * @returns {object} PaymentDataRequest fields
 */
function getGooglePaymentDataConfiguration() {
  return {
    // @todo a merchant ID is available for a production environment after approval by Google
    // @see {@link https://developers.google.com/pay/api/web/test-and-deploy|Test and deploy}
    merchantId: '01234567890123456789',
    paymentMethodTokenizationParameters: tokenizationParameters,
    allowedPaymentMethods: allowedPaymentMethods,
    cardRequirements: {
      allowedCardNetworks: allowedCardNetworks
    }
  };
}

/**
 * Provide Google Pay API with a payment amount, currency, and amount status
 *
 * @see {@link https://developers.google.com/pay/api/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 = getGooglePaymentsClient();
  paymentsClient.prefetchPaymentData(paymentDataRequest);
}

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

  var paymentsClient = getGooglePaymentsClient();
  paymentsClient.loadPaymentData(paymentDataRequest)
      .then(function(paymentData) {
        // handle the 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/pay/api/web/object-reference#PaymentData|PaymentData object reference}
 */
function processPayment(paymentData) {
  // show returned data in developer console for debugging
  console.log(paymentData);
  // @todo pass payment data response to gateway to process payment
}

</script>
<script async
  src="https://payments.developers.google.com/js/apis/pay.js"
  onload="onGooglePayLoaded()"></script>

Send feedback about...

Google Pay API