> For the complete documentation index, see [llms.txt](https://docs.solapayments.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/sample-code.md). Agents can also search and read this documentation through its [MCP server](https://docs.solapayments.com/~gitbook/mcp).

# Google Pay Sample Code

1. **Let's define a helper object with all necessary components:**

   ```javascript
   window.gpRequest = {
       environment: GPEnvironment.test,
       merchantInfo: {
           merchantName: "Example Merchant"
       },
       buttonOptions: {
           buttonSizeMode: GPButtonSizeMode.fill
       },
       billingParams: {
           billingAddressRequired: true,
           billingAddressFormat: GPBillingAddressFormat.full                        
       },
       shippingParams: {
           emailRequired: true,
           onGetShippingCosts: function (shippingData) {
               logDebug({
                   label: "onGetShippingCosts",
                   data: shippingData
               });
               return {
                   "shipping-001": "0.00",
                   "shipping-002": "1.99",
                   "shipping-003": "10.00"
               }
           },
           onGetShippingOptions: function (shippingData) {
               logDebug({
                   label: "onGetShippingOptions",
                   data: shippingData
               });
               let selectedOptionid = "shipping-001";
               if (shippingData && shippingData.shippingOptionData && shippingData.shippingOptionData.id !== "shipping_option_unselected") {
                   selectedOptionid = shippingData.shippingOptionData.id;
               }
               return {
                   defaultSelectedOptionId: selectedOptionid,
                   shippingOptions: [
                       {
                           "id": "shipping-001",
                           "label": "Free: Standard shipping",
                           "description": "Free Shipping delivered in 5 business days."
                       },
                       {
                           "id": "shipping-002",
                           "label": "$1.99: Standard shipping",
                           "description": "Standard shipping delivered in 3 business days."
                       },
                       {
                           "id": "shipping-003",
                           "label": "$10: Express shipping",
                           "description": "Express shipping delivered in 1 business day."
                       },
                   ]
               };
           }
       },
       onGetTransactionInfo: function () {
           let amt = getAmount();
           return {
               displayItems: [
                   {
                       label: "Subtotal",
                       type: "SUBTOTAL",
                       price: amt.toString(),
                   },
                   {
                       label: "Tax",
                       type: "TAX",
                       price: (0.1 * amt).toString(),
                   }
               ],
               countryCode: 'US',
               currencyCode: "USD",
               totalPriceStatus: "FINAL",
               totalPrice: (1.1 * amt).toString(),
               totalPriceLabel: "Total"
           }
       },    
       onBeforeProcessPayment: function () {
           return new Promise(function (resolve, reject) {
               try {
                   //Do some validation here
                   resolve(iStatus.success);
               } catch (err) {
                   reject(err);
               }
           });
       },
       onProcessPayment: function (paymentResponse) {
           return new Promise(function (resolve, reject) {
                   try {
                       // show returned data in developer console for debugging
                       console.log("paymentResponse", JSON.stringify(paymentResponse));
                       paymentToken = paymentResponse.paymentData.paymentMethodData.tokenizationData.token;
                       console.log("paymentToken", paymentToken);
                       const amt = (paymentResponse && paymentResponse.transactionInfo && paymentResponse.transactionInfo.totalPrice) || 0;
                       try {
                       if (amt <= 0) {
                           throw "Payment is not authorized. Invalid amount. Amount must be greater than 0";
                       }
                       authorizeGPay(paymentResponse)
                           .then((resp) => {
                               gpRequest.handleResponse(resp);
                               setGPPayload(JSON.stringify(paymentResponse, null, 2));
                               resolve(resp);
                           })
                           .catch((rej) => {
                               console.error("Payment is not authorized", JSON.stringify(rej));
                               setGPPayload("");
                               setTimeout(function () { alert("Payment is not authorized. Please check the logs") }, 500);
                               reject(rej);
                           });
                       } catch (err) {
                           const emsg = JSON.stringify(err);
                           console.error(emsg);
                           setTimeout(function () { alert(emsg) }, 500);
                           reject({error: err});
                       }
               } catch (err) {
                   reject(err);
               }
           });
       },
       onPaymentCanceled: function(respCanceled) {
           setTimeout(function () { alert("Payment was canceled") }, 500);
       },
       handleResponse: function (resp) {
           const respObj = JSON.parse(resp);
           if (respObj) {
               if (respObj.xError) {
                   setTimeout(function () { alert(`There was a problem with your order (${respObj.xRefNum})!`) }, 500);
               } else
                   setTimeout(function () { alert(`Thank you for your order (${respObj.xRefNum})!`) }, 500);
           }
       },
   };
   ```
2. **Object with necessary properties to initialize Google Pay:**

   ```javascript
   function initGP() {
       return {
           merchantInfo: gpRequest.merchantInfo,
           buttonOptions: gpRequest.buttonOptions,
           onGetTransactionInfo: "gpRequest.onGetTransactionInfo",
           environment: gpRequest.environment,
           billingParameters: gpRequest.billingParams,
           shippingParameters: {
               emailRequired: gpRequest.shippingParams.emailRequired,
               onGetShippingCosts: "gpRequest.shippingParams.onGetShippingCosts",
               onGetShippingOptions: "gpRequest.shippingParams.onGetShippingOptions"
           },
           onBeforeProcessPayment: "gpRequest.onBeforeProcessPayment",
           onProcessPayment: "gpRequest.onProcessPayment",
           onPaymentCanceled: "gpRequest.onPaymentCanceled",
           onGPButtonLoaded: "gpButtonLoaded"
       };
   }
   ```

   For more information please refer to [Request](https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/request-objects.md) object<br>
3. **Google Pay iField:**

   ```html
   <style> 
       ......
       iframe {
           border: 0 solid black;
           width: 600px;
           height: 28px;
           padding: 0px;
           margin-bottom: 5px;
       }
       iframe.gp {
           display: block;
           border: 0;
           width: 250px;
           height: 45px;
           padding: 0px;
           margin: 0px;
       }
       .hidden {
           display: none;
       }
       .....
   </style>   
   <body>
     <form id="payment-form" method="POST">
       .....
       <input id="amountId" name="xAmount" placeholder="Amount"></input>
       .....
       <iframe id="igp" class="gp hidden" data-ifields-id="igp" data-ifields-oninit="initGP" src="igp.htm"
               allowpaymentrequest
               sandbox="allow-popups allow-modals allow-scripts allow-same-origin"
               title="GPay checkout page">
       </iframe>
       .....
   </form>
   </body>    
   ```
4. **Let’s enable Google Pay for the website:**

   ```javascript
   document.addEventListener("DOMContentLoaded", function(event) { 
       .....
       ckGooglePay.enableGooglePay({amountField: 'amount'}); 
       .....
   }
   ```

   For more information please refer to [Google Pay Control Object](https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/google-pay-control-object.md)<br>
5. To see the full solution please click [**here**](https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/ifields-integration.md)**.**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/sample-code.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
