Skip to main content
Skip table of contents

Enable Google Pay for Web

Google Pay for Web is a dedicated button for custom websites, suitable for those not utilizing PayFrame or PayFields integrations. It allows the creation of hosted payment sites using Payrix as a secure gateway for processing card information through Google Pay tokens. The tutorial guides integrating the Google Pay API with Payrix, covering aspects like registration, API configuration, and payment method management, along with valuable insights and code examples. Key steps include defining the payrixTokenizationSpecification and modifying JavaScript for transactions, ensuring compliance with Payrix's requirements for capturing cardholder information, and managing transaction amounts

Tip: To enable Google Pay for PayFields or PayFrame integrations, please refer to the following resources:

Getting Started

To get started enabling Google Pay for Web, follow the steps below:

  1. Register for access to the Google Pay Business Console.

  2. Get your Merchant ID for Google Pay environments.

  3. For production access to the Google Pay API and to register your Merchant account with Google, check out Google Pay developer documentation. You'll need to register at the Google Pay Business Console to get access to your Google Pay API Merchant ID.

Note: Referrers can integrate Google Pay with Payrix, but please note that we do not provide support for Google’s “Integration Checklist” or the Google Pay API regarding setup or troubleshooting.

Configuring Google Pay on the Payrix Gateway

The following example shows how to integrate Google Pay with the Payrix gateway. Google provides framework-specific examples in their Google Pay GitHub Repository. The setup steps below utilize the HTML example provided by Google.

Configure Payrix as the Google Pay Payment Gateway

  1. In your code, define the payrixTokenizationSpecification, replacing {{your_payrix_gateway_merchantid}} with the appropriate values for sandbox testing or production.

Please refer to Google's Google Pay Setup Tutorial for specific guidance on setting up Google Pay integration for the web.

JS
  // Update the `gatewayMerchantId` property with your own value.
  // This id will be different for TEST and PRODUCTION environments
  const payrixTokenizationSpecification = {
    type: 'PAYMENT_GATEWAY',
    parameters: {
      gateway: 'payrix',
      gatewayMerchantId: '{{your_payrix_gateway_merchantid}}',
    },
  };

  Object.freeze(payrixTokenizationSpecification); 

Configure Google Pay Transaction Parameters

  1. Payrix gateway mandates that the cardholder's first and last name be provided when processing payments. To comply, you must modify the definition of baseGooglePayRequest to set billingAddressRequired: true. Additionally, include the FULL format for billingAddressParameters or supply the cardholder's first and last name through other means.

JS
  const baseGooglePayRequest = {
    apiVersion: 2,
    apiVersionMinor: 0,
    allowedPaymentMethods: [
      {
        type: 'CARD',
        parameters: {
          allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
          allowedCardNetworks: ['AMEX', 'DISCOVER', 'INTERAC', 'JCB', 'MASTERCARD', 'VISA'],
          billingAddressRequired: true,
          billingAddressParameters: {
            format: 'FULL',
          },
        },
        tokenizationSpecification: payrixTokenizationSpecification,
      },
    ],
    merchantInfo,
  };
  1. The total transaction amount for the Payrix gateway is represented as an integer in cents. It is essential to convert this value accurately from the transactionInfo.totalPrice provided by Google Pay. To enhance your JavaScript for creating requests to the Payrix Gateway, please incorporate the following helper functions.

JS
  function extractIntegerCents(totalPrice) {
    // Use regex to match a formatted number
    const match = totalPrice.match(/-?\d+(?:,\d{3})*(?:\.\d+)?/);
    if (match) {
      // Remove commas and convert to float
      const cleanedNumber = match[0].replace(/,/g, '');
      return parseFloat(cleanedNumber) * 100;
    }
    return NaN; // Return NaN if no number is found
  }

  function getPayrixGatewayRequestData({ gatewayMerchantId, totalPrice, paymentDataResponse}) {
    const paymentToken = JSON.parse(paymentDataResponse.paymentMethodData.tokenizationData.token);
    const [ first, ...last ] = paymentDataResponse.paymentMethodData.info.billingAddress.name.split(' ');
    return {
      merchant: gatewayMerchantId, // Payrix Merchant ID
      total: extractIntegerCents(totalPrice), // integer transaction total as cents
      type: 'sale',
      origin: 2, // E-Commerce
      entryMode: 10, // Google Pay
      payment: {
        encrypted: 'googlePaymentToken',
        paymentData: paymentToken
      },
      address1: paymentDataResponse.paymentMethodData.info.billingAddress.address1,
      address2: paymentDataResponse.paymentMethodData.info.billingAddress.address2,
      city: paymentDataResponse.paymentMethodData.info.billingAddress.locality,
      state: paymentDataResponse.paymentMethodData.info.billingAddress.administrativeArea,
      zip: paymentDataResponse.paymentMethodData.info.billingAddress.postalCode,
      first,
      last: last.join(' '),
    };
  }

Set Up Google Pay Payment Success Handlers to Integrate with Payrix

  1. To modify the Google Pay payment success handler, update it to call the Payrix gateway using the provided helpers. Ensure to replace {{your_payrix_gateway_url}} and {{your_payrix_gateway_apikey}} with the correct values for testing in the sandbox environment or for going live in production when you are ready.

JS
        const gatewayReq = getPayrixGatewayRequestData({
          gatewayMerchantId: payrixTokenizationSpecification.parameters.gatewayMerchantId,
          totalPrice: req.transactionInfo.totalPrice,
          paymentDataResponse: res
        });

        return fetch('{{your_payrix_gateway_url}}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'APIKEY': '{{your_payrix_gateway_apikey}}',
          },
          body: JSON.stringify(gatewayReq),
        });
      })

Configure Payrix Gateway Response Handlers

  1. To effectively manage the Payrix gateway response, your code could be structured as follows, particularly if you are utilizing promises:

Tip: For framework-specific examples, visit Google’s Google Pay GitHub Repository.

JS
    // Get an instance of the Google Payments Client.
    getGooglePaymentsClient()
      // Load the payment data in console for the transaction.
      .loadPaymentData(req)
      // If the payment is successful, process the payment
      .then(function (res) {
        // show returned data for debugging
        console.log(res);
        // @note DO NOT save the payment credentials for future transactions,
        // unless they're used for merchant-initiated transactions with user
        // consent in place.
        const gatewayReq = getPayrixGatewayRequestData({
          gatewayMerchantId: payrixTokenizationSpecification.parameters.gatewayMerchantId,
          totalPrice: req.transactionInfo.totalPrice,
          paymentDataResponse: res
        });

        return fetch('{{your_payrix_gateway_url}}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'APIKEY': '{{your_payrix_gateway_apikey}}',
          },
          body: JSON.stringify(gatewayReq),
        });
      })
      .then(function (gatewayRes) {
        if (!gatewayRes.ok) {
          throw new Error(`Payrix gateway response status: ${gatewayRes.status}`);
        }
        return gatewayRes.json();
      })
      .then(function (gatewayResJson) {
        if (gatewayResJson.errors && gatewayResJson.errors.length > 0) {
          throw new Error(`Payrix gateway response errors: ${gatewayResJson.errors}`);
        }
        // payment gateway authorizes payment
        console.log(gatewayResJson);
      })
      // If there is an error, log it to the console.
      .catch(console.error);

Sandbox Testing

To ensure a smooth integration and functionality of Google Pay on your web platform, follow the steps below to test in both Payrix and Google Pay's sandbox environments.

If you have created a direct integration with Google Pay using your own Google Pay Console account, you can proceed by following the steps in the Integration Checklist provided by Google for Developers. This checklist will guide you through the steps necessary to test your integration in the sandbox environment.


Conclusion

In summary, integrating Google Pay for Web with the Payrix gateway effectively processes payments on custom websites. This tutorial outlines essential steps for setting up Google Pay using a standalone button for efficient transaction management.

Key findings emphasize accurately defining billing address parameters and converting transaction amounts to meet Payrix requirements. The tutorial also includes links to resources for integrating Google Pay with PayFields and PayFrame.

References

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.