Fast Checkout button (Apple/Google Pay)

Information about the Native Apple Pay and Google Pay support in Native Checkout

Overview

The Native Apple Pay and Google Pay APIs enables you to accept payments from within your applications through Apple Pay and Google Pay.

Apple Pay Native Checkout

You can find the complete guide to integrating Apple Pay native checkout here.

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:

When preparing to go live, please refer to the Publish Your Integration page to configure your website for production following Google’s guidelines.

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. 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 4. 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 5. Integration with Viva Backend

Step 5.1. Generate a one-time charge token

Merchants/Partners need to retrieve the paymentToken value from the previous step.

post    /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": "paymentToken" }'  # Replace "paymentToken" with the Google Pay Payment Token

Step 5.2. Make the actual charge using the one-time charge token

post    /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,
    "customer": {
      "email": "native@vivawallet.com",
      "phone": "442036666770",
      "fullname": "John Smith",
      "requestLang": "en",
      "countryCode": "GB"
    }
  }'

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!