Raj Technologies
Published in

Raj Technologies

Google Pay API JavaScript Example

Source Code

Define the version of the Google Pay API referenced when creating your

configuration

in PaymentDataRequest

const baseRequest = {apiVersion: 2,apiVersionMinor: 0};

confirm card networks supported by your site and gateway

allowedCardNetworks

const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];

Card authentication methods supported by your site and your gateway

confirm your processor supports Android device tokens for your

const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];

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 payer authorization

check with your gateway on the parameters to pass

const tokenizationSpecification = {type: 'PAYMENT_GATEWAY',parameters: {'gateway': 'example','gatewayMerchantId': 'exampleGatewayMerchantId'}};

Describe your site’s support for the CARD payment method and its required fields

const baseCardPaymentMethod = {type: 'CARD',parameters: {allowedAuthMethods: allowedCardAuthMethods,allowedCardNetworks: allowedCardNetworks}};

Describe your site’s support for the CARD payment method including optional fields

const cardPaymentMethod = Object.assign({},baseCardPaymentMethod,{tokenizationSpecification: tokenizationSpecification});

An initialized google.payments.api.PaymentsClient object or null if not yet set

getGooglePaymentsClient

let paymentsClient = null;

Configure your site’s support for payment methods supported by the Google Pay API.

Each member of allowedPaymentMethods should contain only the required fields, allowing reuse of this base request when determining a viewer’s ability to pay and later requesting a supported payment method

returns {object} Google Pay API version, payment methods supported by the site

function getGoogleIsReadyToPayRequest() {return Object.assign({},baseRequest,{allowedPaymentMethods: [baseCardPaymentMethod]});}

Configure support for the Google Pay API

returns {object} PaymentDataRequest fields

function getGooglePaymentDataRequest() {const paymentDataRequest = Object.assign({}, baseRequest);paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];paymentDataRequest.transactionInfo = getGoogleTransactionInfo();paymentDataRequest.merchantInfo = {// @todo a merchant ID is available for a production environment after approval by Google// See {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}// merchantId: '01234567890123456789',merchantName: 'Example Merchant'};paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];return paymentDataRequest;}

Return an active PaymentsClient or initialize

returns {google.payments.api.PaymentsClient} Google Pay API client

function getGooglePaymentsClient() {if ( paymentsClient === null ) {paymentsClient = new google.payments.api.PaymentsClient({environment: 'TEST',paymentDataCallbacks: {onPaymentAuthorized: onPaymentAuthorized}});}return paymentsClient;}

Handles authorize payments callback intents.

param {object} paymentData response from Google Pay API after a payer approves payment through user gesture.

object reference

returns Promise<{object}> Promise of PaymentAuthorizationResult object to acknowledge the payment authorization status.

function onPaymentAuthorized(paymentData) {return new Promise(function(resolve, reject){// handle the responseprocessPayment(paymentData).then(function() {resolve({transactionState: 'SUCCESS'});}).catch(function() {resolve({transactionState: 'ERROR',error: {intent: 'PAYMENT_AUTHORIZATION',message: 'Insufficient funds, try again. Next attempt should work.',reason: 'PAYMENT_DATA_INVALID'}});});});}

Initialize Google PaymentsClient after Google-hosted JavaScript has loaded

Display a Google Pay payment button after confirmation of the viewer’s ability to pay.

function onGooglePayLoaded() {const paymentsClient = getGooglePaymentsClient();paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest()).then(function(response) {if (response.result) {addGooglePayButton();}}).catch(function(err) {// show error in developer console for debuggingconsole.error(err);});}

Add a Google Pay purchase button alongside an existing checkout button

https://developers.google.com/pay/api/web/reference/request-objects#ButtonOptions|Button options

https://developers.google.com/pay/api/web/guides/brand-guidelines|Google Pay brand guidelines

function addGooglePayButton() {const paymentsClient = getGooglePaymentsClient();const button =paymentsClient.createButton({onClick: onGooglePaymentButtonClicked});document.getElementById('googlepay').appendChild(button);}

Provide Google Pay API with a payment amount, currency, and amount status

returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest

function getGoogleTransactionInfo() {return {displayItems: [{label: "Subtotal",type: "SUBTOTAL",price: "1.00",},//       {//           label: "Tax",//           type: "TAX",//           price: "1.00",//         }],//     countryCode: 'US',//     currencyCode: "USD",countryCode: 'IN',currencyCode: "INR",totalPriceStatus: "FINAL",totalPrice: "1.00",totalPriceLabel: "Total"};}

Show Google Pay payment sheet when Google Pay payment button is clicked

function onGooglePaymentButtonClicked() {const paymentDataRequest = getGooglePaymentDataRequest();paymentDataRequest.transactionInfo = getGoogleTransactionInfo();const paymentsClient = getGooglePaymentsClient();paymentsClient.loadPaymentData(paymentDataRequest);}let attempts = 0;

Process payment data returned by the Google Pay API

param {object} paymentData response from Google Pay API after user approves payment

https://developers.google.com/pay/api/web/reference/response-objects#PaymentData

PaymentData object reference

function processPayment(paymentData) {return new Promise(function(resolve, reject) {setTimeout(function() {// @todo pass payment token to your gateway to process paymentpaymentToken = paymentData.paymentMethodData.tokenizationData.token;if (attempts++ % 2 == 0) {reject(new Error('Every other attempt fails, next one should succeed'));} else {resolve({});}}, 500);});}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bhargav Raviya

Bhargav Raviya

I am Laravel, Flutter, and Digital Marketing Expert and follow the blog on raviyatechnical.blogspot.com Github:-https://github.com/bhargavraviya