# Google Pay Request Objects

#### *For complete sample code please refer* [*here*](https://docs.solapayments.com/mobile-wallets/google-pay-hosted-checkout/sample-code) <a href="#for-complete-sample-code-please-refer-here" id="for-complete-sample-code-please-refer-here"></a>

## **Available dictionary objects** <a href="#available-dictionary-objects" id="available-dictionary-objects"></a>

### iStatus <a href="#istatus" id="istatus"></a>

```
const iStatus = {
    success: 100,
    unsupported: -100,
    error: -200
}
```

**Use:** `iStatus.success`

### GPEnvironment <a href="#gpenvironment" id="gpenvironment"></a>

```
const GPEnvironment = {
    test: "TEST",
    production: "PRODUCTION"
}
```

**Use:** `GPEnvironment.test`

### GPButtonColor <a href="#gpbuttoncolor" id="gpbuttoncolor"></a>

```
const GPButtonColor = {
    default: "default",
    black: "black",
    white: "white"
}
```

**Use:** `GPButtonColor.white`

### GPButtonType <a href="#gpbuttontype" id="gpbuttontype"></a>

```
const GPButtonType = {
    buy: "buy",
    donate: "donate",
    plain: "plain"
}
```

**Use:** `GPButtonType.buy`

### GPButtonSizeMode <a href="#gpbuttonsizemode" id="gpbuttonsizemode"></a>

```
const GPButtonSizeMode = {
    static: "static",
    fill: "fill"
}
```

**Use:** `GPButtonSizeMode.fill`

### GPBillingAddressFormat <a href="#gpbillingaddressformat" id="gpbillingaddressformat"></a>

```
const GPBillingAddressFormat = {
    min: "MIN",
    full: "FULL"
}
```

**Use:** `GPBillingAddressFormat.min`

## **Request objects** <a href="#request-objects" id="request-objects"></a>

### GooglePayRequest <a href="#googlepayrequest" id="googlepayrequest"></a>

The Main object that contains all the information necessary to communicate with Google Pay API.

| **Name**                 | **Type**                                         | **Required** | **Description**                                                                                                                                                                                                                                                                                                                                                                |
| ------------------------ | ------------------------------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `merchantInfo`           | [*MerchantInfo*](#merchantinfo-object)           | No           | Describes the Merchant name and website. For more information please click the link                                                                                                                                                                                                                                                                                            |
| `onGPButtonLoaded`       | String                                           | No           | <p>Name of a callback function to be called when Google Pay button is loaded.<br>Accepts an object of type <a href="#GPButtonLoadedResult-Object">GPButtonLoadedResult</a>.</p>                                                                                                                                                                                                |
| `onGetTransactionInfo`   | String                                           | Yes          | <p>Name of a callback function to be called that returns the final price and tax calculations.<br>Please click <a href="sample-code">here</a> for the sample code</p>                                                                                                                                                                                                          |
| `onBeforeProcessPayment` | String                                           | No           | <p>Name of a callback function to be called when consumer clicked the button but before Google Pay sheet is loaded . Usually used to make validations before the payment.<br>Please click <a href="sample-code">here</a> for the sample code</p>                                                                                                                               |
| `onProcessPayment`       | String                                           | Yes          | <p>Name of a callback function to be called when Google Payment is authorized for the completion of the transaction.<br>This function accepts a parameter of <a href="https://docs.cardknox.com/mobile-wallets/google-pay-hosted-checkout/response-objects#paymentresponse-object">PaymentResponse</a>.<br>Please click <a href="sample-code">here</a> for the sample code</p> |
| `onPaymentCanceled`      | String                                           | No           | <p>Name of a callback function to be called when Google Pay sheet is closed/canceled without completing the transaction.<br>Please click <a href="sample-code">here</a> for the sample code</p>                                                                                                                                                                                |
| `environment`            | String                                           | No           | <p>Google Pay Environment. Could be either “TEST“ or “PRODUCTION“.<br>If omitted, defaults to “TEST“</p>                                                                                                                                                                                                                                                                       |
| `billingParameters`      | [BillingParameters](#billingparameters-object)   | No           | <p>Sets Billing parameters, including transactionId.<br>For more information please click the link</p>                                                                                                                                                                                                                                                                         |
| `shippingParameters`     | [ShippingParameters](#shippingparameters-object) | No           | Sets various Shipping Options. For more information please click the link                                                                                                                                                                                                                                                                                                      |
| `buttonOptions`          | [ButtonOptions](#buttonoptions-object)           | No           | <p>Provides Google Pay button customization options.<br>For more information please click the link</p>                                                                                                                                                                                                                                                                         |

&#x20;**Payment Request example**

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

**onGPButtonLoaded example**

```
gpButtonLoaded: function(resp) {
    if (!resp) return;
    if (resp.status === iStatus.success) {
        showHide("divGpay", true);
        showHide("lbGPPayload", true);
    } else if (resp.reason) {
        alert(resp.reason);
    }
}
```

**onGetTransactionInfo example**

```
onGetTransactionInfo: function () {
    let amt = this.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 callback example**

```
onBeforeProcessPayment: function () {
    return new Promise(function (resolve, reject) {
        try {
            //Do some validation here
            resolve(iStatus.success);
        } catch (err) {
            reject(err);
        }
    });
}
```

**onProcessPayment callback example**

```
onProcessPayment: function (paymentRequest) {
    let self = this;
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            try {
                console.log("paymentRequest", JSON.stringify(paymentRequest));
                paymentToken = paymentRequest.paymentData.paymentMethodData.tokenizationData.token;
                console.log("paymentToken", paymentToken);
                const amt = (chained([paymentRequest, "transactionInfo", "totalPrice"]) && paymentRequest.transactionInfo.totalPrice) || 0;
                try {
                    if (amt <= 0) 
                        throw "Payment is not authorized. Invalid amount. Amount must be greater than 0";
                    authorizeGPay({ token: paymentToken, amount: amt})
                    .then((resp) => {
                        gpRequest.handleResponse(resp);
                        resolve(resp);
                    })
                    .catch((rej) => {
                        console.error("Payment is not authorized", JSON.stringify(rej));
                        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 (e) {
                reject(e);
            }
        }, 100); //3000);
    });
}
```

**onPaymentCanceled callback example**

```
onPaymentCanceled: function(respCanceled) {
    setTimeout(function () { alert("Payment was canceled") }, 500);
}
```

### MerchantInfo Object <a href="#merchantinfo-object" id="merchantinfo-object"></a>

| **Name**       | **Type** | **Required** | **Description**                                                                                                                                                                                                                                                           |
| -------------- | -------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `merchantName` | String   | Yes          | <p><em>From Google documentation</em>:<br>Merchant name encoded as UTF-8. Merchant name is rendered in the payment sheet. In <code>TEST</code> environment, or if a merchant isn't recognized, a “Pay Unverified Merchant” message is displayed in the payment sheet.</p> |

**Merchant Info example**

```
merchantInfo: {
    merchantName: "Example Merchant"
}
```

### GPButtonLoadedResult Object <a href="#gpbuttonloadedresult-object" id="gpbuttonloadedresult-object"></a>

| **Name** | **Type**            | **Description**                                                                                                                                                                                                                                                                                             |
| -------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | [iStatus](#iStatus) | <p>There are 3 possible cases:</p><ul><li>Google Pay Button loaded successfully: <code>status = iStatus.success</code></li><li>Google Pay not supported: <code>status = iStatus.unsupported</code></li><li>An error occurred while loading Google Pay Button: <code>status = iStatus.error</code></li></ul> |
| `reason` | String              | If Google Pay Button failed to load this field will be populated with the reason.                                                                                                                                                                                                                           |

### BillingParameters Object <a href="#billingparameters-object" id="billingparameters-object"></a>

| **Name**                   | **Type**                                          | **Required** | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| -------------------------- | ------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `transactionId`            | String                                            | No           | <p><em>From Google documentation</em>:<br>A unique ID that identifies a transaction attempt.<br>If not provided will be automatically generated by iFields API. Will be sent back on paymentRequest..transactionInfo response object.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `allowedAuthMethods`       | String\[]                                         | No           | <p>If not provided will be defaulted to <code>\["PAN\_ONLY", "CRYPTOGRAM\_3DS"]</code><br><em>From Google documentation</em>:<br>Fields supported to authenticate a card transaction.</p><ul><li><code>PAN\_ONLY</code>: This authentication method is associated with payment cards stored on file with the user's Google Account. Returned payment data includes personal account number (PAN) with the expiration month and the expiration year.</li><li><code>CRYPTOGRAM\_3DS</code>: This authentication method is associated with cards stored as Android device tokens. Returned payment data includes a 3-D Secure (3DS) cryptogram generated on the device.</li></ul> |
| `allowedCardNetworks`      | String\[]                                         | No           | <p>If not provided will be defaulted to <code>\["AMEX", "DISCOVER", "MASTERCARD", "VISA"]</code><br><em>From Google documentation</em>:<br>One or more card networks that you support, also supported by the Google Pay API.</p><ul><li><code>AMEX</code></li><li><code>DISCOVER</code></li><li><code>INTERAC</code></li><li><code>JCB</code></li><li><code>MASTERCARD</code></li><li><code>VISA</code></li></ul>                                                                                                                                                                                                                                                              |
| `assuranceDetailsRequired` | Boolean                                           | No           | <p><em>From Google documentation</em>:<br>Set to <code>true</code> to request <code>assuranceDetails</code>. This object provides information about the validation performed on the returned payment data.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `billingAddressRequired`   | Boolean                                           | No           | <p><em>From Google documentation</em>:<br>Set to <code>true</code> if you require a billing address. A billing address should only be requested if it's required to process the transaction.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `billingAddressFormat`     | [GPBillingAddressFormat](#GPBillingAddressFormat) | No           | <p><em>Has an effect when billingAddressRequired is set to true</em><br><em>From Google documentation</em>:<br>Billing address format required to complete the transaction.</p><ul><li><code>MIN</code>: Name, country code, and postal code (default).</li><li><code>FULL</code>: Name, street address, locality, region, country code, and postal code.</li></ul>                                                                                                                                                                                                                                                                                                            |
| `phoneNumberRequired`      | Boolean                                           | No           | <p><em>Has an effect when billingAddressRequired is set to true</em><br><em>From Google documentation</em>:<br>Set to <code>true</code> if a phone number is required to process the transaction.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |

**Billing Parameters example**

```
billingParameters: {
    transactionId: "b65c7435-b57a-407e-a6e0-b166518d5d97",
    allowedAuthMethods: ["PAN_ONLY"],
    allowedCardNetworks: ["VISA", "MASTERCARD"],
    emailRequired: true
    billingAddressRequired: true,
    billingAddressFormat: GPBillingAddressFormat.min,
    phoneNumberRequired: true
}
```

### ShippingParameters Object <a href="#shippingparameters-object" id="shippingparameters-object"></a>

| **Name**                  | **Type**  | **Required** | **Description**                                                                                                                                                                                             |
| ------------------------- | --------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onGetShippingOptions`    | String    | No           | <p>When shipping is required you need to provide the name of <code>your</code> function that returns a list of shipping options.<br>For an example - please see below</p>                                   |
| `onGetShippingCosts`      | String    | No           | <p>When shipping is required you need to provide the name of <code>your</code> function that returns a list of shipping costs.<br>For an example - please see below</p>                                     |
| `shippingAddressRequired` | Boolean   | No           | <p><em>From Google documentation</em>:<br>Set to <code>true</code> to request a full shipping address..</p>                                                                                                 |
| `emailRequired`           | Boolean   | No           | <p><em>From Google documentation</em>:<br>Set to <code>true</code> to request an email address.</p>                                                                                                         |
| `phoneNumberRequired`     | Boolean   | No           | <p><em>From Google documentation</em>:<br>Set to <code>true</code> if a phone number is required for the provided shipping address.</p>                                                                     |
| `allowedCountryCodes`     | String\[] | No           | <p><em>From Google documentation</em>:<br>ISO 3166-1 alpha-2 country code values of the countries where shipping is allowed. If this object isn't specified, will be defaulted to <code>US</code> only.</p> |

**Shipping Parameters example**

```
shippingParams: {
    allowedCountryCodes: ['US'],
    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."
                },
            ]
        };
    }
}
```

### ShippingData Object

| **Name**             | **Type**                                         | **Description**                                                                                   |
| -------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| `shippingAddress`    | [ShippingAddress](#shippingaddress-object)       | An Address containing `countryCode`, `postalCode`, `locality`(city), `administrativeArea`(state). |
| `shippingOptionData` | [ShippingOptionData](#shippingoptiondata-object) | An object containing a selected option                                                            |

**ShippingData object example**

```
{
  "shippingAddress": {
    "countryCode": "US",
    "postalCode": "10601",
    "locality": "White Plains",
    "administrativeArea": "NY"
  },
  "shippingOptionData": {
    "id": "shipping-001"
  }
}
```

### ShippingAddress Object

| **Name**             | **Type** | **Description**                                                                                   |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `postalCode`         | String   | <p><em>From Google documentation</em>:<br>The postal or ZIP code.</p>                             |
| `countryCode`        | String   | <p><em>From Google documentation</em>:<br>ISO 3166-1 alpha-2 country code.</p>                    |
| `locality`           | String   | <p><em>From Google documentation</em>:<br>City, town, neighborhood, or suburb.</p>                |
| `administrativeArea` | String   | <p><em>From Google documentation</em>:<br>A country subdivision, such as a state or province.</p> |

### ShippingOptionData Object

| **Name** | **Type** | **Description**                |
| -------- | -------- | ------------------------------ |
| `id`     | String   | id of selected shipping option |

### ButtonOptions Object <a href="#buttonoptions-object" id="buttonoptions-object"></a>

| **Name**         | **Type**                              | **Required** | **Description**                                                                                                                                                                                                                                                                                                                                                        |
| ---------------- | ------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `buttonColor`    | [GPButtonColor](#GPButtonColor)       | No           | <p><em>From Google documentation</em>:</p><ul><li><code>default</code>: A Google-selected default value. Currently <code>black</code> but it may change over time (default).</li><li><code>black</code>: A black button suitable for use on white or light backgrounds.</li><li><code>white</code>: A white button suitable for use on colorful backgrounds.</li></ul> |
| `buttonType`     | [GPButtonType](#GPButtonType)         | No           | <p><em>From Google documentation</em>:</p><ul><li><code>buy</code>: "Buy with Google Pay" button (default).</li><li><code>donate</code>: "Donate with Google Pay" button.</li><li><code>plain</code>: Google Pay button without additional text.</li></ul>                                                                                                             |
| `buttonSizeMode` | [GPButtonSizeMode](#GPButtonSizeMode) | No           | <p><em>From Google documentation</em>:</p><ul><li><code>static</code>: Button has a static width and height (default).</li><li><code>fill</code>: Button size changes to fill the size of its container.</li></ul>                                                                                                                                                     |

**Button Options example**

```
buttonOptions: {
    buttonColor: GPButtonColor.white,
    buttonType: GPButtonType.buy,
    buttonSizeMode: GPButtonSizeMode.full
}
```
