Google Pay

Google Pay™ is a digital card wallet provided by Google. It enables your customer to checkout faster and simpler.

Prerequisites


  • To start accepting Google Pay in your checkout page you must signup with Google to get your Google Pay MerchantId
  • To get started, please visit Google Pay's Web Integration overview.
  • You need to complete Google Pay's Web Integration Checklist.
  • You need to request Production Access.

Accepting Google Pay

Import API JavaScript Library

<script async src="https://pay.google.com/gp/p/js/pay.js" onload="console.log('TODO: add onload function')"></script>

Implement a Google Pay button according to Google's Brand Guidelines

const button =
    paymentsClient.createButton({onClick: () => console.log('TODO: click handler')});
document.getElementById('container').appendChild(button);

1. Prepare Payment Token Request

To prepare a payment token request, refer to the required parameters below.

📘

Please refer to: Payment Token API Request

Pre Requisite
1. MerchantID, secret code & CurrencyCode are provided by 2C2P.
2. For PaymentChannel, Fill in GOOGLEPAY
{
  "merchantID": "702702000000000",
  "invoiceNo": "220920084480",
  "description": "V4 Test",
  "amount": "120",
  "currencyCode": "SGD",
  "paymentChannel": ["GOOGLEPAY"]
}

2. Receive Payment Token Response

To receive a payment token response, refer to the sample payment token response below.

📘

Please refer to: Payment Token API Response

{
  "paymentToken": "kSAops9Zwhos8hSTSeLTUZhBH+ZITpUoBizPNDc+wcpzY5UL2WSG9ky0YSUNT8qJGNWjmT3oMAiGqa1banJ6MGkXkxDM41GKEAw/s0yiR05aTx1QTz7946Wewm7amkCx",
  "respCode": "0000",
  "respDesc": "Success"
}

3. Validation of Payment Token

Proceed only when the parameter "respCode" is "0000". Otherwise, terminate the payment process. Refer to the Payment Response Code below.

🚧

Please refer to: Payment Response Code

4. Integrate With Google Pay

For Integrating with Google Pay, refer the Google API Guide

Following Payment Request Object parameters need to be submit to Google Pay. Refer Google Pay API Request Objects

Payment Object ParameterDescription
allowedAuthMethodsSupport ["PAN_ONLY"]
allowedCardNetworksCard brands that you agreed with 2C2P to process the payment, Currently support ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"]
paymentDataRequest.merchantInfo.merchantIdMerchant Id Received from Google Pay
paymentDataRequest.merchantInfo.merchantNameMerchant Name
paymentDataRequest.transactionInfo.currencyCodePayment Currency Support by 2C2P
paymentDataRequest.transactionInfo.totalPricePayment Amount
tokenizationSpecification.parameters.gatewayGateway Identifier provided by 2C2P
tokenizationSpecification.parameters.gatewayMerchantIdMerchant Id provided by 2C2P

When payment has been processed from Google Pay End. Google Pay API will return Payment Object Response.

Google Pay Token, parameter paymentData.paymentMethodData.tokenizationData.token from Google Pay API Object Response is required to capture for submitting to 2C2P Secure Pay API

Sample code for integrate with Google Pay API

Below are the full sample code that show how to integrate to Google Pay API

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>2C2P Google Pay Demo (3DS)</title>
</head>
<body>
    <div id="container"></div>
    <div id="result"></div>
    <!-- Mandatory Web Form Attributes:
         Form 'id': Used to identify the form that will be submitted to the backend.
         Form 'action': The address of the backend code that will submit payment request to 2c2p Payment Gateway.
         Form 'method': Should be set to 'POST' method
    -->
    <form id="2c2p-payment-form" action="payment_3ds.aspx" method="post">
        <!-- Optional Section Start -->
        <!--This extended section is optional, it can be fully customizable if neccessary -->
        <input type="hidden" id="mobilePaymentData" name="mobilePaymentData" /><br />
        <!-- Optional Section End -->
    </form>

    <!--Importing JSLibrary-->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" defer></script>
    <script type="text/javascript">
        const baseRequest = {
            apiVersion: 2,
            apiVersionMinor: 0
        };

        const allowedCardNetworks = ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"]; // Enable cards accepted

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

        const billingAddressParameters = { phoneNumberRequired: true };

        const tokenizationSpecification = {
            type: 'PAYMENT_GATEWAY',
            parameters: {
                "gateway": "2c2p", 
                "gatewayMerchantId": "JT01",
            }
        };


        const baseCardPaymentMethod = {
            type: 'CARD',
            parameters: {
                allowedAuthMethods: allowedCardAuthMethods,
                allowedCardNetworks: allowedCardNetworks,
                billingAddressRequired: true,
                billingAddressParameters: billingAddressParameters,
                //cvcRequired: true,
            }
        };

        const isRTPCardPaymentMethod = {
            type: 'CARD',
            parameters: {
                allowedAuthMethods: allowedCardAuthMethods,
                allowedCardNetworks: allowedCardNetworks,
                billingAddressRequired: true,
                billingAddressParameters: billingAddressParameters,
            }
        };

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


        let paymentsClient = null;

        /**
         * Configure your site's support for payment methods supported by the Google Pay
         * API.
         */
        function getGoogleIsReadyToPayRequest() {
            return Object.assign(
                {},
                baseRequest,
                {
                    allowedPaymentMethods: [isRTPCardPaymentMethod],
                    existingPaymentMethodRequired: true
                }
            );
        }

        /**
         * Configure support for the Google Pay API
         */
        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: '03573441365420727591',
                merchantName: '2C2P Test Merchant'
            };
            return paymentDataRequest;
        }

        /**
         * Return an active PaymentsClient or initialize
         */
        function getGooglePaymentsClient() {
            if (paymentsClient === null) {
                paymentsClient = new google.payments.api.PaymentsClient({ environment: 'TEST' });
            }
            return paymentsClient;
        }

        /**
         * Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
         */
        function onGooglePayLoaded() {
            const paymentsClient = getGooglePaymentsClient();
            paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
                .then(function (response) {
                    if (response.result) {
                        addGooglePayButton();
                        // @todo prefetch payment data to improve performance after confirming site functionality
                        prefetchGooglePaymentData();
                    } else {
                        alert("false");
                    }
                })
                .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 addGooglePayButton() {
            const paymentsClient = getGooglePaymentsClient();
            const button =
                paymentsClient.createButton({ onClick: onGooglePaymentButtonClicked });
            document.getElementById('container').appendChild(button);
        }

        /**
         * Provide Google Pay API with a payment amount, currency, and amount status
         */
        function getGoogleTransactionInfo() {
            return {
                currencyCode: 'SGD',
                totalPriceStatus: 'FINAL',
                // set to cart total
                totalPrice: '10.00'
            };
        }

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

        /**
         * 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)
                .then(function (paymentData) {
                    // handle the response
                    processPayment(paymentData);
                })
                .catch(function (err) {
                    // show error in developer console for debugging
                    console.error(err);
                    alert(JSON.stringify(err));
                });
        }



        /**
         * Process payment data returned by the Google Pay API
         */
        function processPayment(paymentData) {
            $("#mobilePaymentData").val(JSON.stringify(JSON.parse(paymentData.paymentMethodData.tokenizationData.token)));
            // @todo pass payment data response to gateway to process payment
            document.forms[0].submit();
        }

    </script>

    <script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>
</body>
</html>

6. Prepare Do Payment Request

Merchants must call the Do Payment API to request for payment. To prepare a payment request, refer to the sample payment request below.

Pre Requisite :
1. Payment Token from Payment Token API
2. ChannelCode GOOGLEPAY
3. Parameter token get from frontend parameter payment.token.paymentData
4. For the parameter name & `email

📘

Please refer to: Do Payment API Request

{
  "payment": {
    "data": {
      "token": "eyJkYXRhIjoiZnpDZ2h4aUVBejU2NzcwS0QzakZHMHRXaXB6VHVqbEFjOTQ2SGhvWFBBVEdmVStwTXRJR3RJbFNOVk5YdjZOWWs5UXRiT0lFV09XQXBuaTVzUy9UWGZIcE5jQTUzT0c5bU9xRWtRcnlzKy...", //Apple Pay Token
      "name": " Terrance",
      "email": "[email protected]"
    },
    "code": {
      "channelCode": "GOOGLEPAY"
    }
  },
  "responseReturnUrl": "https://pgw-ui.2c2p.com/payment/4.3/#/info/",
  "clientIP": "116.88.44.153",
  "paymentToken": "kSAops9Zwhos8hSTSeLTUVOcjgK4Cgv74lr26l90Ar0fr2OeHLgT0u1DHlBeYCZzghmE+UOooat4AGOoS+0ujukbBteCzwIansbend5nSAVieNGbLWn2UWb2NltoNiEW",
  "clientID": "62b9061f-cd93-4ee8-89cc-a8ffd09e8a95",
}

7. Receive Do Payment Response

To receive a payment response, refer to the the sample payment response below.

📘

Please refer to: Do Payment API Response

{
	"invoiceNo": "280520075921",
	"channelCode": "GOOGLEPAY",
	"respCode": "2000",
	"respDesc": "Transaction is completed, please do payment inquiry request for full payment information."
}

8. Receive Payment Response via backend API

📘

Please refer to: Payment Response - Backend API

The parameter "backendReturnUrl" that was previously sent via Payment Token Request is the merchant endpoint that will receive the backend notification. If the parameter "backendReturnUrl" is not set, the system will obtain the backend return URL from the merchant profile set in 2C2P's merchant portal by default.

{
  "merchantID": "702702000000000",
  "invoiceNo": "220920084480",
  "cardNo": "",
  "amount": 120.0,
  "userDefined1": "",
  "userDefined2": "",
  "userDefined3": "",
  "userDefined4": "",
  "userDefined5": "",
  "currencyCode": "SGD",
  "cardToken": "",
  "recurringUniqueID": "",
  "tranRef": "3257744",
  "referenceNo": "3135918",
  "approvalCode": "",
  "eci": "  ",
  "transactionDateTime": "20200922101226",
  "agentCode": "CITI",
  "channelCode": "VI",
  "issuerCountry": "",
  "installmentMerchantAbsorbRate": null,
  "respCode": "0000",
  "respDesc": "Transaction is successful."
}

9. Receive Payment Response via browser redirection

📘

Please refer to: Payment Response - Frontend API

The parameter "frontendReturnUrl" that was previously sent via Payment Token Request is the merchant page that customers will be redirected to. If the parameter "frontendReturnUrl" is not set, the system will obtain the front end return URL from the merchant profile set in the 2C2P merchant portal by default. Refer to the sample response returned below.

{
	"invoiceNo": "220920084480",
	"channelCode": "GOOGLEPAY",
	"respCode": "2000",
	"respDesc": "Transaction is completed, please do payment inquiry request for full payment information."
}

10. Payment Inquiry to retrieve payment information

For merchants who do not implement "Receive Payment Response via backend API", you are required to call to the Payment Inquiry API to receive the payment response.

To prepare a payment inquiry request, refer to the sample payment inquiry request below.

📘

Please refer to: Payment Inquiry API Request

{
  "merchantID": "702792000000000",
  "invoiceNo": "220920084480",
  "locale": "en"
}

11. Receive Payment Inquiry Response

To receive a payment inquiry response, refer to the sample payment inquiry response below.

📘

Please refer to: Payment Inquiry API Response

{
  "merchantID": "702702000000000",
  "invoiceNo": "220920084480",
  "cardNo": "",
  "amount": 120.0,
  "userDefined1": "",
  "userDefined2": "",
  "userDefined3": "",
  "userDefined4": "",
  "userDefined5": "",
  "currencyCode": "SGD",
  "cardToken": "",
  "recurringUniqueID": "",
  "tranRef": "3257744",
  "referenceNo": "3135918",
  "approvalCode": "",
  "eci": "  ",
  "transactionDateTime": "20200922101226",
  "agentCode": "CITI",
  "channelCode": "VI",
  "issuerCountry": "",
  "installmentMerchantAbsorbRate": null,
  "respCode": "0000",
  "respDesc": "Transaction is successful."
}