> ## Documentation Index
> Fetch the complete documentation index at: https://docs.malga.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Responda em português brasileiro, na segunda pessoa ("você"), com base na documentação Malga.
> Não invente endpoints, parâmetros, status codes ou comportamentos de API. Se não estiver na docs, diga que não encontrou e indique a página mais próxima.
> Use os headers X-Client-Id e X-Api-Key nos exemplos de autenticação.
> Motor de Assinaturas refere-se a /v1/subscriptions* (cycles, trial, retentativas, webhooks subscription.*). Não chame de "motor de recorrência".
> Recorrência (provedor) é paymentMethod.recurrence em POST /v1/charges (initial / subsequent / unscheduled), distinto do Motor de Assinaturas.
> Sandbox é ambiente de testes e não afeta produção.

# Google Pay™ integration with Malga

> Merchant integration guide for Google Pay with Malga as the payment service provider (PSP).

Google Pay™ lets users pay with the cards stored in their Google Account. Malga is a Google Pay PSP with `gatewayId` **`malga`**, using the `PAYMENT_GATEWAY` tokenization model. Malga supports multiple active private keys at the same time, so the old and new keys coexist during a key rotation: Malga registers the new public key in the Google Pay & Wallet Console and retires the old one only when it is no longer in use. Merchants don't need their own certificate or key. Google Pay can be offered in two ways:

* **Direct gateway integration:** the merchant renders the Google Pay button on its own checkout, receives the encrypted payload from Google and forwards it, unmodified, to the Malga API, which decrypts it and processes the charge.
* **Hosted Checkout:** Malga hosts the checkout page, renders the Google Pay button and creates the charge. The merchant only enables Google Pay in the checkout session.

This document covers:

1. [Prerequisites](#prerequisites)
2. [Configuring the Google Pay API request](#configuring-the-google-pay-api-request), including `gateway` and `gatewayMerchantId`
3. [Supported authentication methods and card networks](#supported-authentication-methods-and-card-networks)
4. [3D Secure for PAN\_ONLY](#3d-secure-for-pan_only)
5. [Full example](#full-example)
6. [Extracting the payload and sending it to Malga](#extracting-the-payload-and-sending-it-to-malga)
7. [Charge lifecycle](#charge-lifecycle)
8. [Enabling Google Pay for a merchant (direct integration)](#enabling-google-pay-for-a-merchant-direct-integration)
9. [Enabling Google Pay on Hosted Checkout](#enabling-google-pay-on-hosted-checkout)
10. [Terms and policies](#terms-and-policies)

## Prerequisites

* Malga credentials (`X-Client-Id` and `X-Api-Key`) and the merchant's `merchantId` at Malga. See [Authentication](https://docs.malga.io/documentations/welcome/authentication.md).
* Google Pay enabled for the merchant by Malga, as described in [Enabling Google Pay for a merchant](#enabling-google-pay-for-a-merchant-direct-integration).
* For the direct integration, basic knowledge of the Google Pay API developer documentation for [Web](https://developers.google.com/pay/api/web/) or for [Android](https://developers.google.com/pay/api/android/).

## Configuring the Google Pay API request

The Google Pay integration uses two Google Pay API objects:

* `IsReadyToPayRequest`: checks whether the buyer can pay with Google Pay and lets you show the button.
* `PaymentDataRequest`: requests the payment and tells Google that the token must be generated for Malga.

### Values for Malga

| Parameter | Value |
| - | - |
| `tokenizationSpecification.type` | `PAYMENT_GATEWAY` |
| `tokenizationSpecification.parameters.gateway` | `malga` |
| `tokenizationSpecification.parameters.gatewayMerchantId` | The merchant's `merchantId` at Malga |
| `allowedAuthMethods` | `["PAN_ONLY", "CRYPTOGRAM_3DS"]` |
| `allowedCardNetworks` | `["AMEX", "DISCOVER", "ELO", "MASTERCARD", "VISA"]` |
| `environment` (`PaymentsClient`) | `TEST` with Malga Sandbox, `PRODUCTION` with Malga production |
| `merchantInfo.merchantId` | The Google merchant ID (Google Pay & Wallet Console) |

### tokenizationSpecification

```json theme={null}
{
  "type": "PAYMENT_GATEWAY",
  "parameters": {
    "gateway": "malga",
    "gatewayMerchantId": "YOUR_MALGA_MERCHANT_ID"
  }
}
```

> [!WARNING]
>
> The `gatewayMerchantId` must be the same `merchantId` you use to create charges at Malga. It is **not** the Google merchant ID (`merchantInfo.merchantId`), which comes from the Google Pay & Wallet Console. Malga rejects a token whose `gatewayMerchantId` doesn't match the `merchantId` of the charge.

## Supported authentication methods and card networks

### allowedAuthMethods

Malga supports both Google Pay authentication methods. Include both in `allowedAuthMethods`:

| authMethod | How Malga processes it |
| - | - |
| **PAN\_ONLY** | The card is processed as a regular card charge. To request 3D Secure, see [3D Secure for PAN\_ONLY](#3d-secure-for-pan_only). |
| **CRYPTOGRAM\_3DS** | The payment arrives as a network token, with cryptogram and ECI. The provider configured for the merchant must support network tokens. Otherwise, the charge is declined with the `payment_not_supported` code. |

> [!WARNING]
>
> To avoid `payment_not_supported` declines, confirm with Malga that the merchant's provider supports network tokens before keeping `CRYPTOGRAM_3DS` in `allowedAuthMethods`.

**Country of settlement:** Malga does not restrict settlement to a fixed list of countries. The supported settlement countries and regions depend entirely on the provider (acquirer) configured for the merchant at Malga. Confirm with Malga which countries the merchant's provider settles in.

### allowedCardNetworks

Malga accepts the `AMEX`, `DISCOVER`, `ELO`, `MASTERCARD` and `VISA` networks. The provider configured for the merchant must also accept the card network: if the provider does not accept it, the charge is not processed.

**Country of settlement:** Malga does not restrict settlement to a fixed list of countries. The supported settlement countries and regions depend entirely on the provider (acquirer) configured for the merchant at Malga. Confirm with Malga which countries the merchant's provider settles in.

> [!NOTE]
>
> List only the networks the merchant's provider accepts. Google Pay shows the buyer only cards from the networks you list.

## 3D Secure for PAN\_ONLY

A `PAN_ONLY` credential is a card number without a cryptogram, so the issuer has not authenticated the buyer. In the direct integration, to request 3D Secure 2 for these payments, send the `threeDSecure2` object in the same `POST /v1/charges` request that carries `googlePayPaymentData`. `CRYPTOGRAM_3DS` credentials already carry a cryptogram and ECI, so they don't need this step.

To enable it:

1. **Ask Malga to enable 3D Secure 2** on a provider configured for the merchant. The provider must support 3DS2 (see the [list of supported providers](https://docs.malga.io/documentations/type-tables/payment-methods-by-providers.md)). If no provider supports it, the charge is rejected.
2. **Collect the buyer's browser data** on your checkout (user agent, accept header, language, screen size, color depth, time zone, Java/JavaScript flags and IP) and send it to your server together with the Google Pay token.
3. **Add `threeDSecure2` to the charge**, as described in [3D Secure 2 with the provider](https://docs.malga.io/documentations/3dsecure2-adyen/charge.md). To know when it's needed, set `assuranceDetailsRequired: true` in the card `parameters` of the `PaymentDataRequest`. Google then returns `paymentData.paymentMethodData.info.assuranceDetails`; when `cardHolderAuthenticated` is `false` (as with PAN\_ONLY credentials), send `threeDSecure2`.
4. **Handle the result.** If the issuer approves without a challenge, the charge is returned as `authorized` or `pre_authorized`. If it requires a challenge, the charge is returned as `pending`, the buyer completes the challenge, and is sent back to your `redirectURL`. The final status arrives via [webhook](https://docs.malga.io/documentations/webhooks/webhook1-0.md).

```bash theme={null}
curl --location --request POST 'https://api.malga.io/v1/charges' \
  --header 'X-Client-Id: YOUR_CLIENT_ID' \
  --header 'X-Api-Key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "merchantId": "YOUR_MALGA_MERCHANT_ID",
    "amount": 150,
    "currency": "BRL",
    "statementDescriptor": "Order #123",
    "capture": true,
    "paymentMethod": {
      "paymentType": "google_pay",
      "installments": 1
    },
    "paymentSource": {
      "sourceType": "wallet",
      "googlePayPaymentData": { "...": "the parsed Google Pay token" }
    },
    "threeDSecure2": {
      "redirectURL": "https://www.yourstore.com/checkout/return",
      "requestorURL": "https://www.yourstore.com",
      "browser": {
        "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...",
        "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "language": "en-US",
        "colorDepth": 24,
        "screenHeight": 1080,
        "screenWidth": 1920,
        "timeZoneOffset": "180",
        "javaEnabled": false,
        "javaScriptEnabled": true,
        "ip": "203.0.113.45"
      },
      "cardHolder": {
        "email": "buyer@example.com",
        "mobilePhone": "5511999999999"
      }
    }
  }'
```

> [!NOTE]
>
> For Google Pay, send `threeDSecure2` without a `setupId`, as in the example above. If you already authenticate with your own 3DS server, send the result in `threeDSecure2.mpi` instead ([3DS with an external MPI](https://docs.malga.io/documentations/3ds2-malga/3ds-mpi-externo.md)).

## Full example

The example below builds the `IsReadyToPayRequest` and the `PaymentDataRequest` with Malga's values, following the [Google Pay API for Web tutorial](https://developers.google.com/pay/api/web/guides/tutorial).

> [!WARNING]
>
> The example uses `environment: 'TEST'` and fictitious data, compatible with Malga Sandbox. Nothing is actually charged and production is not affected. When going live, switch to `PRODUCTION` and use the Google merchant ID and the Malga production `merchantId`.

```javascript theme={null}
const baseRequest = {
  apiVersion: 2,
  apiVersionMinor: 0,
};

const tokenizationSpecification = {
  type: 'PAYMENT_GATEWAY',
  parameters: {
    gateway: 'malga',
    gatewayMerchantId: 'YOUR_MALGA_MERCHANT_ID',
  },
};

const baseCardPaymentMethod = {
  type: 'CARD',
  parameters: {
    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
    allowedCardNetworks: ['AMEX', 'DISCOVER', 'ELO', 'MASTERCARD', 'VISA'],
  },
};

const cardPaymentMethod = {
  ...baseCardPaymentMethod,
  tokenizationSpecification,
};

// Use 'PRODUCTION' with Malga production.
const paymentsClient = new google.payments.api.PaymentsClient({
  environment: 'TEST',
});

// IsReadyToPayRequest: decides whether to show the Google Pay button.
const isReadyToPayRequest = {
  ...baseRequest,
  allowedPaymentMethods: [baseCardPaymentMethod],
};

paymentsClient
  .isReadyToPay(isReadyToPayRequest)
  .then((response) => {
    if (response.result) {
      // Show the Google Pay button, e.g. with paymentsClient.createButton(...)
    }
  })
  .catch(console.error);

// PaymentDataRequest: requests the payment.
const paymentDataRequest = {
  ...baseRequest,
  allowedPaymentMethods: [cardPaymentMethod],
  transactionInfo: {
    totalPriceStatus: 'FINAL',
    totalPrice: '1.50',
    currencyCode: 'BRL',
    countryCode: 'BR',
  },
  merchantInfo: {
    merchantName: 'My Store',
    // Google merchant ID (Google Pay & Wallet Console).
    // In TEST, Google accepts a test value.
    merchantId: 'YOUR_GOOGLE_MERCHANT_ID',
  },
};
```

### Billing address

Malga doesn't require a billing address or phone number from Google Pay to process the charge, so the example doesn't set `billingAddressRequired`, `billingAddressParameters` or `phoneNumberRequired`. If you collect the customer's address yourself, send it in the charge as usual (for example, in `fraudAnalysis.customer.billingAddress`).

## Extracting the payload and sending it to Malga

After the buyer confirms the payment, `loadPaymentData` returns `paymentData`. The encrypted payload is in `paymentData.paymentMethodData.tokenizationData.token`, which is a **JSON string**.

```javascript theme={null}
paymentsClient
  .loadPaymentData(paymentDataRequest)
  .then((paymentData) => {
    // Encrypted JSON string, generated by Google for Malga.
    const token = paymentData.paymentMethodData.tokenizationData.token;

    // Send it to YOUR server, without changing its content.
    return fetch('/your-backend/google-pay/charge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token }),
    });
  })
  .catch(console.error);
```

> [!WARNING]
>
> Never call `POST /v1/charges` directly from the browser: the request requires the `X-Api-Key`, which is a secret key. Send the token to your server and create the charge from there.

On your server, convert the string into an object with `JSON.parse` and send the result in `paymentSource.googlePayPaymentData` when [creating the charge](https://docs.malga.io/api-reference/charges/realizar-nova-cobranca.md):

```javascript theme={null}
const googlePayPaymentData = JSON.parse(token);

const response = await fetch('https://api.malga.io/v1/charges', {
  method: 'POST',
  headers: {
    'X-Client-Id': 'YOUR_CLIENT_ID',
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    merchantId: 'YOUR_MALGA_MERCHANT_ID',
    amount: 150,
    currency: 'BRL',
    statementDescriptor: 'Order #123',
    capture: false,
    paymentMethod: {
      paymentType: 'google_pay',
      installments: 1,
    },
    paymentSource: {
      sourceType: 'wallet',
      googlePayPaymentData,
    },
  }),
});
```

> [!NOTE]
>
> The Malga `amount` is in cents: `150` is R\$ 1.50, the same value as `totalPrice: '1.50'` in the `PaymentDataRequest`.

Or, with cURL:

```bash theme={null}
curl --location --request POST 'https://api.malga.io/v1/charges' \
  --header 'X-Client-Id: YOUR_CLIENT_ID' \
  --header 'X-Api-Key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "merchantId": "YOUR_MALGA_MERCHANT_ID",
    "amount": 150,
    "currency": "BRL",
    "statementDescriptor": "Order #123",
    "capture": false,
    "paymentMethod": {
      "paymentType": "google_pay",
      "installments": 1
    },
    "paymentSource": {
      "sourceType": "wallet",
      "googlePayPaymentData": {
        "protocolVersion": "ECv2",
        "signature": "<token signature>",
        "intermediateSigningKey": {
          "signedKey": "<token signedKey>",
          "signatures": ["<signedKey signature>"]
        },
        "signedMessage": "<token signedMessage>"
      }
    }
  }'
```

> [!NOTE]
>
> Do not decrypt, validate or change the token: Malga receives exactly what Google returned. The object sent in `googlePayPaymentData` has the same shape as the JSON returned in `tokenizationData.token`. Malga accepts `protocolVersion` `ECv2` only, and each token can be used in a single charge.

## Charge lifecycle

A Google Pay charge is processed as a card charge through the provider configured in the merchant's smart flow.

* It is registered with status `authorized`, `pre_authorized` or `failed` (or `pending` while a 3D Secure challenge is in progress).
* **Pre-authorization and capture:** send `capture: false` to reserve the amount (`pre_authorized`) and capture it later through the [capture endpoint](https://docs.malga.io/api-reference/charges/capturar-cobranca-pre-autorizada.md). Send `capture: true` to authorize and capture at once (`authorized`). The acquirer may automatically undo a pre-authorization that is not captured within 7 days.
* **Full or partial refund:** send the [void request](https://docs.malga.io/api-reference/charges/estornar-cobranca-aprovada.md), optionally with an `amount` lower than the original to refund part of it.

### Status notifications

| Object | Event | Description |
| - | - | - |
| `transaction` | `pending` | The charge was created at Malga |
| `transaction` | `pre_authorized` | The payment was pre-authorized, with the amount reserved |
| `transaction` | `authorized` | The payment was authorized |
| `transaction` | `failed` | The charge was declined before authorization, with no refund |
| `transaction` | `canceled` | The charge was canceled before capture, with no refund |
| `transaction` | `voided` | The charge was canceled after authorization, producing a refund |
| `transaction` | `charged_back` | The charge was disputed for fraud |

## Enabling Google Pay for a merchant (direct integration)

1. **Register in the Google Pay & Wallet Console.** Register your business in the [Google Pay & Wallet Console](https://pay.google.com/business/console) and get the production **Google merchant ID**. It must be sent in `merchantInfo.merchantId`.
2. **Follow Google's guidelines.** Build the integration with the Google Pay API developer documentation for [Web](https://developers.google.com/pay/api/web/) or [Android](https://developers.google.com/pay/api/android/). Follow the Google Pay brand guidelines for [Web](https://developers.google.com/pay/api/web/guides/brand-guidelines) or [Android](https://developers.google.com/pay/api/android/guides/brand-guidelines) and the integration checklist for [Web](https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist) or [Android](https://developers.google.com/pay/api/android/guides/test-and-deploy/integration-checklist). Submit your integration for Google's approval before using `PRODUCTION`.
3. **Publish your integration.** Request production access and obtain your Google merchant ID (`merchantInfo.merchantId`) in the Google Pay & Wallet Console by following Google's guide for [Web: Publish your integration](https://developers.google.com/pay/api/web/guides/test-and-deploy/publish-your-integration) or [Android: Publish your integration](https://developers.google.com/pay/api/android/guides/test-and-deploy/publish-your-integration).
4. **Ask Malga to enable it.** Ask Malga to enable Google Pay for your `merchantId` and a compatible provider. Confirm that the provider accepts the networks you will show and, if you use `CRYPTOGRAM_3DS`, that it supports network tokens.
5. **Accept Google's terms.** Read and accept the [Google Pay API Acceptable Use Policy](https://payments.developers.google.com/terms/aup) and the [Google Pay API Terms of Service](https://payments.developers.google.com/terms/sellertos).
6. **Test in Sandbox and go live.** Use `environment: 'TEST'` with [Malga Sandbox](https://docs.malga.io/documentations/welcome/testing.md). In production, use `environment: 'PRODUCTION'` with Malga production.

## Enabling Google Pay on Hosted Checkout

With Hosted Checkout, Malga hosts the payment page and integrates the Google Pay API on it. The merchant doesn't write Google Pay code, register in the Google Pay & Wallet Console or have its own Google merchant ID: the Google Pay account and the Google merchant ID belong to Malga. If the merchant serves the checkout on its own domain, Malga registers that domain with Google.

The hosted checkout is a redirect flow: send the buyer to the checkout URL. It can't be embedded in an `<iframe>` on your site, because it is served with `Content-Security-Policy: frame-ancestors 'self'` and `X-Frame-Options: SAMEORIGIN`, so the iframe attributes `allow="payment *"` and `sandbox` don't apply.

1. **Ask Malga to enable Google Pay** for your `merchantId`, with a provider that accepts the card networks you want to offer.

2. **Accept Google's terms.** Before offering Google Pay to your buyers, read and accept the [Google Pay API Acceptable Use Policy](https://payments.developers.google.com/terms/aup) and the [Google Pay API Terms of Service](https://payments.developers.google.com/terms/sellertos).

3. **Add Google Pay to the checkout session.** When you create the session, include an item with `paymentType: "google_pay"` and `installments` in `paymentMethods`. Google Pay can be offered alongside the other payment methods, including in sessions that use `multiple`.

   ```json theme={null}
   "paymentMethods": [
     { "paymentType": "credit", "installments": 1 },
     { "paymentType": "google_pay", "installments": 1 }
   ]
   ```

4. **Test in Sandbox.** Validate the flow in [Malga Sandbox](https://docs.malga.io/documentations/welcome/testing.md) before going live; Sandbox payments don't affect production.

What the hosted checkout does for each payment:

* Calls `isReadyToPay` and shows the official Google Pay button (`createButton`) only when Google confirms the buyer can pay.
* Builds the `PaymentDataRequest` with `gateway: "malga"`, the session's `merchantId` as `gatewayMerchantId`, the merchant's name as `merchantInfo.merchantName`, `allowedAuthMethods` `PAN_ONLY` and `CRYPTOGRAM_3DS`, and `allowedCardNetworks` `AMEX`, `DISCOVER`, `ELO`, `MASTERCARD` and `VISA`.
* Collects the customer's billing address (street, number, district, city, state, ZIP/postal code and country) and phone number in its own form, before showing the payment methods. It doesn't request them from Google Pay (`billingAddressRequired` isn't set) and uses the address from the form for the charge.
* Creates the charge with `paymentSource.sourceType: "wallet"` and the token in `googlePayPaymentData`, as described in [Extracting the payload and sending it to Malga](#extracting-the-payload-and-sending-it-to-malga).

## Terms and policies

By using Google Pay, you agree to Google's terms:

* [Google Pay API Acceptable Use Policy](https://payments.developers.google.com/terms/aup)
* [Google Pay API Terms of Service](https://payments.developers.google.com/terms/sellertos)


## Related topics

- [Pagamentos instantâneos com Pix na Malga](https://docs.malga.io/documentations/payment-methods/pix.md)
- [Começando em meios de pagamento](https://docs.malga.io/documentations/payment-methods/intro.md)
- [Sobre a Malga](https://docs.malga.io/documentations/welcome/introduction.md)
- [Configurando o Google Pay](https://docs.malga.io/documentations/payment-methods/google-pay/configurando-google-pay.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.