Native Google Pay API
Information on the Native Google Pay API.
Overview
The Native Google Pay APIs enables you to accept payments from within your applications through Google Pay.
Google Pay Native API
Sources:
https://developers.google.com/pay/api/web/guides/setup
https://developers.google.com/pay/api/web/guides/tutorial
https://codelabs.developers.google.com/codelabs/gpay-web-101#1
Before you start
Before starting the API implementation, please ensure that the following prerequisites are met:
Serve an HTTPS webpage with a TLS domain-validated certificate.
Use one of the following supported web browsers: Google Chrome, Mozilla Firefox, Apple Safari, Microsoft Edge, Opera, or UCWeb UC Browser.
Add a payment method to your Google Account.
Adhere to Google Pay API Acceptable Use Policy.
Integration steps
Step 1. Include Google’s hosted JavaScript on your page
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Google Pay API for Web 101</title>
</head>
<body>
<div id="gpay-container"></div>
<p>Transaction info and errors will be logged to the console.</p>
<script type="text/javascript" src="main.js"></script>
<script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>
</body>
</html>Step 2. Configure Google Pay and set up a paymentsClient object
A Google Pay payment request requires a request object. The object defined here as baseGooglePayRequest contains the minimum common settings for all requests.
In a main.js file add this code below :
//=============================================================================
// Configuration
//=============================================================================
// The DOM element that the Google Pay button will be rendered into
const GPAY_BUTTON_CONTAINER_ID = 'gpay-container';
// Update the `merchantId` and `merchantName` properties with your own values.
// Your real info is required when the environment is `PRODUCTION`.
const merchantInfo = {
merchantId: '12345678901234567890',
merchantName: 'Example Merchant'
};
// This is the base configuration for all Google Pay payment data requests.
const baseGooglePayRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [{
type: 'CARD',
parameters: {
allowedAuthMethods: [
"PAN_ONLY", "CRYPTOGRAM_3DS"
],
allowedCardNetworks: [
"AMEX", "JCB", "MASTERCARD", "VISA"
]
},
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: 'vivawallet',
gatewayMerchantId: 'db081a3b-b1ee-4bdc-9ec6-6582d3a3e1d6'
}
}
}],
merchantInfo
};
// Prevent accidental edits to the base configuration. Mutations will be
// handled by cloning the config using deepCopy() and modifying the copy.
Object.freeze(baseGooglePayRequest);
During the initial development phase, use the TEST environment, which returns dummy payment methods. These methods allow you to reference the structure of a payment response but cannot complete real transactions. A PaymentsClient is used to make payment requests and register callbacks.
Append the following client code to the bottom of the main.js file:
//=============================================================================
// Google Payments client singleton
//=============================================================================
let paymentsClient = null;
function getGooglePaymentsClient() {
if (paymentsClient === null) {
paymentsClient = new google.payments.api.PaymentsClient({
environment: 'TEST',
merchantInfo,
// todo: paymentDataCallbacks (codelab pay-web-201)
});
}
return paymentsClient;
}
Step 3. Validate Google Pay sandbox 3DS testing
Before you move on to transaction testing, confirm that your Google Pay test environment can generate CRYPTOGRAM_3DS tokens.
Viva’s Native Checkout API requires 3D Secure authentication. If Google Pay returns a PAN_ONLY token (cardHolderAuthenticated="0"), the /nativecheckout/v2/transactions endpoint rejects it with the error PaymentsCardHolderAuthenticationInvalidStatus (Event ID: 2061).
To validate your sandbox setup:
Temporarily set
allowedAuthMethodsin yourbaseGooglePayRequest(Step 2) toCRYPTOGRAM_3DSonly:allowedAuthMethods: [ "CRYPTOGRAM_3DS" ],Make sure your test Google account has access to 3DS-enabled cards, using one of these options:
- Join the Google Pay API Test Cards Allowlist group with the Google account you use for testing.
- Use a real card stored in Google Wallet while keeping the
PaymentsClientenvironment set toTEST.
Open the Google Pay payment sheet and check that at least one card appears.
Note: If the payment sheet is empty when allowedAuthMethods is set to ["CRYPTOGRAM_3DS"], the Google account you’re testing with doesn’t have access to 3DS-enabled test cards yet. Google controls which test cards are available, and Viva can’t provision them for you.
Once a card appears in the payment sheet, your sandbox is ready for transaction testing and you can continue to the next step.
Step 4. Add a Google Pay payment button (Add helpers)
For more information on available button types, colors, and display requirements, refer to the Brand Guidelines.
//=============================================================================
// Helpers
//=============================================================================
const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
function renderGooglePayButton() {
const button = getGooglePaymentsClient().createButton({
onClick: onGooglePaymentButtonClicked
});
document.getElementById(GPAY_BUTTON_CONTAINER_ID).appendChild(button);
}
Step 5. Add event handlers
Append this code to the bottom of main.js file:
//=============================================================================
// Event Handlers
//=============================================================================
function onGooglePayLoaded() {
const req = deepCopy(baseGooglePayRequest);
getGooglePaymentsClient()
.isReadyToPay(req)
.then(function(res) {
if (res.result) {
renderGooglePayButton();
} else {
console.log("Google Pay is not ready for this user.");
}
})
.catch(console.error);
}
function onGooglePaymentButtonClicked() {
// Create a new request data object for this request
const req = {
...deepCopy(baseGooglePayRequest),
transactionInfo: {
countryCode: 'FR',
currencyCode: 'EUR',
totalPriceStatus: 'FINAL',
totalPrice: (Math.random() * 999 + 1).toFixed(2),
},
// todo: callbackIntents (codelab gpay-web-201)
};
// Write request object to console for debugging
console.log(req);
getGooglePaymentsClient()
.loadPaymentData(req)
.then(function(res) {
// Write response object to console for debugging
console.log(res);
// @todo pass payment token to Viva gateway to process payment
// @note DO NOT save the payment credentials for future transactions
paymentToken = res.paymentMethodData.tokenizationData.token;
})
.catch(console.error);
}
Step 6. Integration with Viva Backend
Step 6.1. Generate a one-time charge token
Merchants/Partners need to retrieve the paymentToken value from the previous step.
/nativecheckout/v2/chargetokens
curl -X POST \
https://demo-api.vivapayments.com/nativecheckout/v2/chargetokens \
-H 'Authorization: Bearer [access_token]' \
-H 'Content-Type: application/json' \
-d '{
"amount": 100,
"token": "{\"signature\":\"MEYCIQClBKJC......." }' # in the token, pass the data you recieved from Google PayStep 6.2. Make the actual charge using the one-time charge token
/nativecheckout/v2/transactions
curl -X POST \
https://demo-api.vivapayments.com/nativecheckout/v2/transactions \
-H 'Authorization: Bearer [access_token]' \
-H 'Content-Type: application/json' \
-d '{
"amount": 100,
"preauth": false,
"sourceCode": "[4-digit code of your payment source]",
"chargeToken": "[charge_token]",
"installments": 1,
"allowsRecurring": false,
"merchantTrns": "Merchant transaction reference",
"customerTrns": "Short description of items/services purchased to display to your customer",
"currencyCode": 826,
"saleToAcquirerData": "ImFkZGl0aW9uYWxEYXRhIjogewogICAgICAibG9kZ2luZy5jYW5jZWxsYXRpb25EdWVEYXRlIjogIjIwMjYtMTEtMDNUMTg6MDA6MDArMDM6MDAiLAogICAgICAibG9kZ2luZy5jaGVja0luRGF0ZSI6ICIyMDI2LTEyLTAzIiwKICAgICAgImxvZGdpbmcuY2hlY2tPdXREYXRlIjogIjIwMjYtMTItMDUiLAogICAgICAibG9kZ2luZy5mb2xpb051bWJlciI6ICIzMDA4NDYwIiwKICAgICAgImxvZGdpbmcuY3VzdG9tZXJDb2RlIjogImhsZzBpNmZmZXJndDZja051M0ZXVjFDUHJ4RWVhcm5rPSIKICAgIH0=",
"customer": {
"email": "native@vivawallet.com",
"phone": "442036666770",
"fullname": "John Smith",
"requestLang": "en",
"countryCode": "GB"
}
}'To view a sample JSON structure and generate the corresponding encoded value, please visit this link.
Get Support
If you would like to integrate with Viva, or if you have any queries about our products and solutions, please see our Contact & Support page to see how we can help!