# Google Pay Integration Guide

Welcome to our Google Pay integration guide! This document will walk you through adding Google Pay as a payment option in your application, making checkout faster and more convenient for your customers.

## What You'll Need

Before we begin, please ensure you have:

-   Your API credentials from our payment platform
-   An SSL certificate enabled on your domain (this is required for Google Pay to work in production)

## Getting Started with Google Pay

### Step 1: Register with Google Pay

To accept Google Pay payments, you'll need to set up your merchant account with Google:

1.  **Create your merchant account**: Visit the [Google Pay & Wallet Console](https://pay.google.com/business/console/) and complete your registration
2.  **Review the Google Pay documentation**: We recommend familiarising yourself with these key resources:
    -   **Overview**: [Google Pay API for Web overview](https://developers.google.com/pay/api/web/overview)
    -   **Setup guide**: [Set up your Google Pay API](https://developers.google.com/pay/api/web/setup)
    -   **API reference**: [PaymentDataRequest](https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest)
    -   **Client reference**: [PaymentsClient](https://developers.google.com/pay/api/web/reference/client)
    -   **Card networks**: [Card parameters](https://developers.google.com/pay/api/web/reference/request-objects#CardParameters)
    -   **Tokenization**: [TokenizationSpecification](https://developers.google.com/pay/api/web/reference/request-objects#gateway)
    -   **Testing**: [Test card suite](https://developers.google.com/pay/api/web/test-card-suite)
    -   **Branding**: [Brand guidelines](https://developers.google.com/pay/api/web/guides/brand-guidelines)

## Frontend Integration

### Step 1: Add the Google Pay Script

First, include the Google Pay JavaScript library in your Next.js application:

```text
// app/layout.tsx (Next.js App Router)
import Script from "next/script";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <Script 
          src="https://pay.google.com/gp/p/js/pay.js" 
          strategy="afterInteractive" 
        />
      </head>
      <body>{children}</body>
    </html>
  );
}
```

### Step 2: Build Your Checkout Component

Create a checkout page that displays the Google Pay button and handles the payment flow:

```text
"use client";
import React from "react";

// Environment configuration - we'll explain these values below
const GOOGLE_PAY_ENV = process.env.NEXT_PUBLIC_GOOGLE_PAY_ENV || "TEST";
const GATEWAY_MERCHANT_ID = process.env.NEXT_PUBLIC_CYBERSOURCE_GATEWAY_MERCHANT_ID || "";
const GOOGLE_PAY_MERCHANT_ID = process.env.NEXT_PUBLIC_GOOGLE_PAY_MERCHANT_ID || "";
const GOOGLE_PAY_MERCHANT_NAME = process.env.NEXT_PUBLIC_GOOGLE_PAY_MERCHANT_NAME || "";

export default function CheckoutPage() {
  const [amount, setAmount] = React.useState("10.00");
  const [status, setStatus] = React.useState("");
  const buttonRef = React.useRef<HTMLDivElement | null>(null);
  const amountRef = React.useRef<string>(amount);

  React.useEffect(() => { 
    amountRef.current = amount; 
  }, [amount]);

  // This function handles what happens when a customer completes their Google Pay authorization
  const onPaymentAuthorized = React.useCallback(async (paymentData: any) => {
    try {
      setStatus("Processing...");
      
      // TODO: This is where you'll send the paymentData to your backend API
      // The paymentData object contains the encrypted payment information
      console.log("Payment data received:", paymentData);
      
      // For now, we'll just show that the payment data was received
      setStatus("Payment data received - ready to process");
      
      return { transactionState: "SUCCESS" };
      
    } catch (err: any) {
      setStatus(err?.message || "Payment error");
      return {
        transactionState: "ERROR",
        error: { 
          intent: "PAYMENT_AUTHORIZATION", 
          message: err?.message || "Payment error" 
        },
      };
    }
  }, []);

  // Configure the Google Pay payment request
  const getPaymentDataRequest = React.useCallback((): any => ({
    apiVersion: 2,
    apiVersionMinor: 0,
    allowedPaymentMethods: [
      {
        type: "CARD",
        parameters: {
          // Types of authentication Google Pay can provide
          allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
          // Credit card networks you accept
          allowedCardNetworks: ["VISA", "MASTERCARD", "AMEX", "DISCOVER"],
          // Request billing address for fraud prevention and receipts
          billingAddressRequired: true,
          billingAddressParameters: {
            format: "FULL",
            phoneNumberRequired: true,
          },
        },
        // Configure tokenization - this encrypts the payment data for your gateway
        tokenizationSpecification: {
          type: "PAYMENT_GATEWAY",
          parameters: {
            gateway: "cybersource",
            gatewayMerchantId: GATEWAY_MERCHANT_ID,
          },
        },
      },
    ],
    // Transaction details shown to the customer
    transactionInfo: {
      totalPriceStatus: "ESTIMATED",
      totalPrice: normalizeAmount(amountRef.current),
      currencyCode: "AUD",
      countryCode: "AU",
    },
    // Your business information
    merchantInfo: { 
      merchantId: GOOGLE_PAY_MERCHANT_ID, 
      merchantName: GOOGLE_PAY_MERCHANT_NAME 
    },
    // Request customer email for receipts
    emailRequired: true,
    // Enable payment authorization callback
    callbackIntents: ["PAYMENT_AUTHORIZATION"],
  }), []);

  // Initialize Google Pay when the component loads
  React.useEffect(() => {
    let cancelled = false;

    const init = async () => {
      try {
        // Wait for the Google Pay script to load
        if (!window.google?.payments?.api) {
          await new Promise<void>((resolve, reject) => {
            const script = document.createElement("script");
            script.src = "https://pay.google.com/gp/p/js/pay.js";
            script.onload = () => resolve();
            script.onerror = () => reject(new Error("Failed to load Google Pay"));
            document.head.appendChild(script);
          });
        }

        if (cancelled) return;

        // Create the Google Pay client
        const paymentsClient = new window.google.payments.api.PaymentsClient({
          environment: GOOGLE_PAY_ENV,
          paymentDataCallbacks: { onPaymentAuthorized }
        });

        // Check if the user's device and account can make payments
        const ready = await paymentsClient.isReadyToPay({
          apiVersion: 2,
          apiVersionMinor: 0,
          allowedPaymentMethods: [{
            type: "CARD",
            parameters: {
              allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
              allowedCardNetworks: ["VISA", "MASTERCARD", "AMEX", "DISCOVER"],
            },
            tokenizationSpecification: {
              type: "PAYMENT_GATEWAY",
              parameters: { 
                gateway: "cybersource", 
                gatewayMerchantId: GATEWAY_MERCHANT_ID 
              },
            },
          }],
        });

        // If Google Pay is available, create and show the button
        if (ready?.result && buttonRef.current) {
          const button = paymentsClient.createButton({
            onClick: () => paymentsClient.loadPaymentData(getPaymentDataRequest()),
            buttonType: "long",   // Makes the button say "Buy with Google Pay"
            buttonColor: "black", // You can also use "white" or "default"
          });
          
          buttonRef.current.innerHTML = "";
          buttonRef.current.appendChild(button);
        }

      } catch (error: any) {
        setStatus(error?.message || "Google Pay initialization error");
      }
    };

    init();
    return () => { cancelled = true; };
  }, [getPaymentDataRequest, onPaymentAuthorized]);

  return (
    <div className="checkout-container">
      <h2>Checkout</h2>
      
      <div className="amount-input">
        <label>
          Amount (AUD):
          <input
            type="text"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            onBlur={() => setAmount(prev => 
              prev === "" || prev === "." ? "0.00" : normalizeAmount(prev)
            )}
          />
        </label>
      </div>

      {/* The Google Pay button will appear here when ready */}
      <div ref={buttonRef} className="google-pay-button" />

      {status && (
        <div className="status">
          Status: {status}
        </div>
      )}
    </div>
  );
}

// Helper function to ensure amounts are properly formatted
function normalizeAmount(input: string): string {
  const cleaned = (input || "0").replace(/[^0-9.]/g, "");
  const num = Number(cleaned);
  if (!Number.isFinite(num) || num < 0) return "0.00";
  return num.toFixed(2);
}
```

### Step 3: Configure Your Environment Variables

Create a `.env.local` file in your project root and add these configuration values:

```text
# Google Pay environment - use "TEST" for development, "PRODUCTION" for live payments
NEXT_PUBLIC_GOOGLE_PAY_ENV=TEST

# Your gateway merchant ID with CyberSource (we'll provide this to you)
NEXT_PUBLIC_CYBERSOURCE_GATEWAY_MERCHANT_ID=your_gateway_merchant_id

# Google Pay merchant ID from Google Pay & Wallet Console (required for production)
NEXT_PUBLIC_GOOGLE_PAY_MERCHANT_ID=your_google_pay_merchant_id

# Your business name as it appears to customers in the Google Pay sheet
NEXT_PUBLIC_GOOGLE_PAY_MERCHANT_NAME=Your Store Name
```

**Understanding Your Configuration:**

-   `**GOOGLE_PAY_ENV**`: Controls whether you're in test mode (`"TEST"`) or processing real payments (`"PRODUCTION"`)
-   `**CYBERSOURCE_GATEWAY_MERCHANT_ID**`: This unique identifier connects Google Pay to our payment processing system - we'll provide this when you sign up
-   `**GOOGLE_PAY_MERCHANT_ID**`: Your merchant ID from Google (optional during testing, required for production)
-   `**GOOGLE_PAY_MERCHANT_NAME**`: The name your customers will see when they're making a payment

## What Happens Next?

When you run this code, here's what your customers will experience:

1.  **They see your checkout page** with the amount and a Google Pay button
2.  **They click the Google Pay button** and their payment sheet opens
3.  **They select a payment method** from their saved cards or add a new one
4.  **They authorise the payment** using their device authentication (fingerprint, PIN, etc.)
5.  **Your** `**onPaymentAuthorized**` **function receives the encrypted payment data** ready to be processed by your backend

The payment data includes everything you need to complete the transaction:

-   Encrypted payment credentials
-   Billing address (if requested)
-   Customer email (if requested)
-   Transaction details

## Testing Your Integration

While in `TEST` mode, you can use Google's test cards to simulate different payment scenarios. Visit the [Google Pay test card suite](https://developers.google.com/pay/api/web/test-card-suite) for a complete list of test cards and expected behaviours.

## Processing Payments with Our API

Once you receive the payment token from Google Pay, you'll need to process it through our OneStep Payment endpoint. Here's how to handle the payment data:

### Step 1: Encode the Payment Token

When Google Pay returns the payment data in your `onPaymentAuthorized` callback, you'll need to encode the entire payment data object as base64:

```text
// Helper function to convert payment data to base64
const toBase64Json = (paymentData: any): string => {
  const json = JSON.stringify(paymentData);
  const bytes = new TextEncoder().encode(json);
  let binary = "";
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
};
```

### Step 2: Submit to OneStep Payment Endpoint

Update your `onPaymentAuthorized` function to process the payment:

```text
const onPaymentAuthorized = React.useCallback(async (paymentData: any) => {
  try {
    setStatus("Processing...");
    
    // Convert amount to 3 decimal precision (e.g., "10.00" -> "10000")
    const amount = Math.round(Number(normalizeAmount(amountRef.current)) * 1000).toString();
    
    // Generate unique transaction ID
    const merchantTxnId = crypto?.randomUUID?.() || `txn-${Date.now()}`;
    
    // Build OneStep Payment request
    const requestBody = {
      Header: {
        TransactionType: "OneStepPayment",
      },
      Transaction: {
        MerchantTxnID: merchantTxnId,
        Currency: "AUD",
        Amount: amount, // 3D Precision string, e.g., "10000"
        ChannelType: "07", // your channel classification
        Method: "GOOGLEPAY",
      },
      SecureTokenHolder: {
        // Pass through the entire Google Pay paymentData as base64 JSON
        GooglePayDataToken: toBase64Json(paymentData),
      },
    };

    // Add billing address if provided by Google Pay
    const billing = paymentData?.paymentMethodData?.info?.billingAddress;
    if (billing) {
      requestBody.BillingAddress = {
        CustomerName: billing.name,
        Street1: billing.address1,
        City: billing.locality,
        State: billing.administrativeArea,
        Zip: billing.postalCode,
        CountryCode: billing.countryCode,
      };
    }

    // Add customer email if provided
    if (paymentData?.email) {
      requestBody.Customer = {
        EmailAddress: paymentData.email,
      };
    }

    // Send to your OneStep Payment endpoint
    const response = await fetch("/api/onestep-payment", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(requestBody),
    });

    const result = await response.json();
    
    // Check payment result
    const approved = result?.Result?.ResponseCode === "1000";
    const authCode = result?.MethodResult?.AuthCode;
    
    setStatus(approved ? `Approved ${authCode ? `(Auth ${authCode})` : ""}` : "Declined");
    
    return { 
      transactionState: approved ? "SUCCESS" : "ERROR" 
    };
    
  } catch (err: any) {
    setStatus(err?.message || "Payment error");
    return {
      transactionState: "ERROR",
      error: { 
        intent: "PAYMENT_AUTHORIZATION", 
        message: err?.message || "Payment error" 
      },
    };
  }
}, []);
```

### Important Notes

-   **Amount Format**: Our API expects amounts in 3 decimal precision (multiply by 1000). For example, $10.00 becomes "10000"
-   **Base64 Encoding**: The entire Google Pay `paymentData` object must be base64 encoded and sent in `GooglePayDataToken`
-   **Transaction ID**: Generate a unique `MerchantTxnID` for each transaction for tracking purposes
-   **Optional Fields**: Billing address and customer email are included automatically if provided by Google Pay

### Expected Response

Our OneStep Payment API will return a response like this:

```text
{
  "Result": {
    "ResponseCode": "1000",
    "ResponseMessage": "Request successful",
    "MerchantTxnID": "1747895291",
    "PaymentID": "a32a5d16-e7ed-11ec-8fea-0242ac120002",
    "Currency": "AUD",
    "Amount": "10000",
    "Method": "GOOGLEPAY"
  },
  "ProviderResps": {
    "ProviderResp": [
      {
        "ProviderName": "surcharge-api",
        "ProviderResponse": "200",
        "ResponseCode": "1000",
        "ProviderReference": "016153570198200",
        "ProviderTransactionNumber": "016153570198200"
      }
    ]
  },
  "MethodResult": { 
    "AuthCode": "831000" 
  },
  "PaymentInfo": {
    "PaymentBrand": "VISA",
    "PaymentBrandType": "CREDIT",
    "BIN": "400000",
    "CardHolder": "Card Holder Name",
    "CardExpiryMonth": "01",
    "CardExpiryYear": "2027"
  },
  "Surcharge": {
    "SurchargeCategory": "CLASSIC",
    "SurchargeFee": "200",
    "SurchargePercentage": "5.5",
    "OriginalAmount": "100000",
    "SurchargedAmount": "5700"
  }
}
```

A `ResponseCode` of "1000" indicates a successful payment.

## Ready for Production?

Once you've tested your integration and are ready to accept real payments:

1.  **Switch to production mode** by setting `NEXT_PUBLIC_GOOGLE_PAY_ENV=PRODUCTION`
2.  **Update your merchant ID** with your production Google Pay merchant ID
3.  **Complete your Google Pay merchant verification** in the Google Pay & Wallet Console
4.  **Implement the backend payment processing** using the payment data from the `onPaymentAuthorized` callback

## Going to Production

When you're ready to accept real Google Pay payments, you'll need to complete Google's production approval process. This ensures your integration meets Google's standards and provides a great customer experience.

### Production Approval Process

**Important**: This process is required for all `PRODUCTION` environments and typically takes 1-5 business days for Google to review.

#### Step 1: Access Your Business Console

Visit [Google Pay & Wallet Console](https://pay.google.com/business/console/) and log in with your business account.

![](https://novatti.portal.swaggerhub.com/services/api/attachments/2ba96c29-3573-4820-9568-e8064d9b2ddc)

#### Step 2: Complete Your Business Profile

Navigate to **Business Profile** and ensure all required information is filled out completely, including:

-   Business name and address
-   Contact information
-   Business registration details
-   Banking information for settlements

![](https://novatti.portal.swaggerhub.com/services/api/attachments/7a254f4b-5e38-4281-95cb-31ae4ce9a10a)

#### Step 3: Add Your Website for Production

1.  Go to **Google Pay API** section
2.  Scroll to **Integrate with your website** section
3.  Click **Add website**  
     
    
    ![](https://novatti.portal.swaggerhub.com/services/api/attachments/a2f9fd10-f3dc-43f8-be23-2c48f4cb58e7)
    
4.  Enter your website URL where Google Pay will be integrated   
     
    
    ![](https://novatti.portal.swaggerhub.com/services/api/attachments/aa0c41ca-eee9-4c72-acb3-081101e8f087)
    
5.  For **Google Pay API Integration type**, choose **Gateway**   
     
    
    ![](https://novatti.portal.swaggerhub.com/services/api/attachments/44b48e0d-5df7-420f-9633-7161b57b7a50)
    

#### Step 4: Provide Integration Screenshots

Upload screenshots of your complete buy flow showing:

-   Your checkout page with the Google Pay button
-   The Google Pay payment sheet in action
-   Order confirmation/success page
-   Any other relevant steps in your payment process

![](https://novatti.portal.swaggerhub.com/services/api/attachments/750870ab-df7f-4a3f-bdd5-130a621787e1)

#### Step 5: Submit for Review

Click **Submit for approval** and wait for Google Pay team's response. You'll receive updates via email about your application status.

**Expected Timeline**: 1-5 business days for Google's review and approval.

![](https://novatti.portal.swaggerhub.com/services/api/attachments/6b062c09-1eb2-46c6-b043-2134e9fcffa3)

### Production Checklist

Before submitting for production approval, ensure:

-    Your website uses HTTPS (SSL certificate required)
-   Google Pay button follows [brand guidelines](https://developers.google.com/pay/api/web/guides/brand-guidelines)
-   Integration has been thoroughly tested in TEST mode
-   Business profile is complete and accurate
-   Payment flow works smoothly from start to finish
-   Error handling is implemented for declined transactions
-   Customer support processes are in place

### After Approval

Once Google approves your production integration:

1.  **Update your environment variables**:

```text
   NEXT_PUBLIC_GOOGLE_PAY_ENV=PRODUCTION
```

1.  **Use your production merchant ID** provided by Google
2.  **Monitor your integration** for the first few transactions to ensure everything works correctly

## Need Help?

If you run into any issues during integration:

-   Check the browser console for error messages
-   Ensure your SSL certificate is properly configured
-   Verify all environment variables are set correctly
-   Review Google's [troubleshooting guide](https://developers.google.com/pay/api/web/support)

For questions specific to our payment platform, please contact our support team.

* * *
