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

# Crear Pago

> Aprende a crear pagos usando el endpoint POST /stores/{storeId}/payments.

## 📌 Endpoint

`POST /stores/{storeId}/payments`

Crea un pago para uno o varios productos de la tienda.

***

## 🔐 Autenticación

Ruta pública. La suscripción activa del dueño de la tienda se valida internamente.

***

## 🧾 Parámetros de ruta

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `storeId` | string | ✅ | ID de la tienda |

***

## 🧍 Body (JSON)

| Campo | Tipo | Obligatorio | Reglas |
| - | - | - | - |
| `name` | string | ✅ | 3–50 caracteres |
| `email` | string | ✅ | email válido, 12–100 caracteres |
| `cpf` | string | ❌ | hasta 24 caracteres |
| `gateway` | string | ✅ | ver gateways soportados, hasta 50 caracteres |
| `coupon` | string | ❌ | código del cupón, acepta null o vacío, hasta 32 caracteres |
| `metadata` | object | ❌ | objeto libre |
| `idempotencyKey` | string | ❌ | clave de idempotencia; evita crear el mismo pago dos veces, hasta 255 caracteres (también acepta el header `Idempotency-Key`) |
| `items` | object\[] | ✅ | al menos 1 elemento |

***

### 🧩 items\[]

| Campo | Tipo | Obligatorio | Reglas |
| - | - | - | - |
| `productId` | string | ✅ | ID del producto |
| `quantity` | number | ✅ | mínimo 1, máximo 50 |
| `billingCycleMonths` | number | ❌ | duración del ciclo de cobro en meses (`1` a `60`) |

***

## 💳 Gateways soportados

El campo `gateway` sigue el patrón `<PROVEEDOR>_ORDER_<MÉTODO>`:

| Valor | Proveedor | Método |
| - | - | - |
| `MERCADOPAGO_ORDER_PIX` | Mercado Pago | PIX |
| `MERCADOPAGO_ORDER_CARD` | Mercado Pago | Tarjeta |
| `MERCADOPAGO_ORDER_BOLETO` | Mercado Pago | Boleto |
| `MERCADOPAGO_ORDER_SALDO` | Mercado Pago | Saldo |
| `ASAAS_ORDER_PIX` | Asaas | PIX |
| `ASAAS_ORDER_CARD` | Asaas | Tarjeta |
| `ASAAS_ORDER_BOLETO` | Asaas | Boleto |
| `EFI_BANK_ORDER_PIX` | EFI Bank | PIX |
| `EFI_BANK_ORDER_CARD` | EFI Bank | Tarjeta |
| `EFI_BANK_ORDER_BOLETO` | EFI Bank | Boleto |
| `STRIPE_ORDER_PIX` | Stripe | PIX |
| `STRIPE_ORDER_CARD` | Stripe | Tarjeta |
| `STRIPE_ORDER_BOLETO` | Stripe | Boleto |

> **Nota:** el gateway necesita estar **activo** en la tienda y con credenciales configuradas. La tienda solo recibe los métodos que habilitó en las credenciales (`paymentMethods`).

### URLs de retorno de Stripe

Para crear una sesión de Stripe Checkout, puedes enviar `successUrl` y `cancelUrl` (válidas con `http://` o `https://`) dentro de `metadata`. Cuando se omiten, la API usa el dominio configurado en la tienda (`store.Domain`) o recurre a la URL base de la plataforma (`SiteBaseURL`) cuando `store.Domain` está vacío.

***

## 💳 Parcelamiento en tarjeta

Para cobrar la tarjeta en **cuotas**, informa el número de cuotas en `metadata.gateway.card.installmentCount`:

```json theme={null}
{
  "metadata": {
    "gateway": {
      "card": {
        "installmentCount": 6
      }
    }
  }
}
```

* **El número elegido es el que vale** — debe estar entre `1` y el `maxInstallments` configurado en el gateway de la tienda (máximo **12**). Si supera el límite, la API rechaza con `400 MAX_INSTALLMENTS_EXCEEDED`; si es inválido (\< 1 o no entero), `400 INVALID_INSTALLMENT_COUNT`.
* Cuando el lojista configuró **rangos de cuotas** (`installmentFees`) en el gateway, la tarifa del rango que contiene el `installmentCount` sustituye la tarifa plana de `fees.card` — **aplicada una única vez sobre el total**, que luego se divide igualmente entre las cuotas. Ej.: rangos 1x `0% + R$ 0`, 2–6x `3,49% + R$ 0,49`, 7–12x `3,99% + R$ 0,49`.
* **Aplicación en la gateway**: las gateways de tarjeta soportadas (Asaas y Mercado Pago) reciben el número de cuotas elegido y dividen el total (tarifa ya incluida) igualmente en las N× en todos los flujos — factura hospedada o tarjeta tokenizada. En Mercado Pago el checkout queda limitado al número elegido (`max_installments`).
* Sin el campo, la tarjeta se cobra **a la vista (1x)** con la tarifa plana de `fees.card` (en Mercado Pago, hasta el `maxInstallments` del lojista).
* El `installmentCount` queda registrado en el pago en `metadata.gateway.card.installmentCount` (junto a `gateway.FeePercentage` / `gateway.FeeAmount`), permitiendo rastrear en cuántas veces se parceló la venta.
* Los errores de parcelamiento devuelven **solo el código** (sin `message`), siguiendo el estándar de la ruta:

| Status | Código | Cuándo |
| - | - | - |
| `400` | `INVALID_INSTALLMENT_COUNT` | `installmentCount` inválido (\< 1 o no entero) |
| `400` | `MAX_INSTALLMENTS_EXCEEDED` | `installmentCount` por encima del `maxInstallments` de la tienda |

***

## 💳 Tarjeta transparente (tokenizada)

Para cobrar la tarjeta **sin redirigir** al comprador, el frontend tokeniza los datos en el navegador (SDK público de la gateway, con la public key) y envía solo el token en `metadata.card` — los datos de la tarjeta nunca pasan por la API:

```json theme={null}
{
  "metadata": {
    "card": {
      "creditCardToken": "TOKEN_GERADO_NO_FRONTEND"
    },
    "gateway": { "card": { "installmentCount": 6 } }
  }
}
```

* El token también se acepta en `metadata.gateway.card.creditCardToken`. Las cuotas siguen en `metadata.gateway.card.installmentCount` (validado contra el `maxInstallments` de la tienda).
* **Sin token, nada cambia**: el flujo cae en el checkout hospedado (redirect) como antes.
* **Mercado Pago**: con token, la API cobra directo (`POST /v1/payments`) y responde **sin** `init_point` — viene `paymentId`, `status` y `statusDetail`; el estado final se acompaña por la cola de verificación (consulta el payment en la gateway). Opcional: `paymentMethodId` e `issuerId` (el SDK del MP informa ambos).
* **Asaas**: con token (`creditCardToken`, o `creditCard` + `creditCardHolderInfo`), cobra directo; sin token, genera la factura hospedada (`invoiceUrl` / `init_point`).
* **EFI Bank**: los pagos con tarjeta requieren `metadata.gateway.card.payment_token` del SDK frontend de EFI y `metadata.gateway.card.phone_number`.
* Error de la gateway (ej.: token inválido) devuelve `502 GATEWAY_ERROR` con el campo `error` conteniendo el cuerpo del proveedor — no se crea ninguna cobranza.

***

## ✅ Ejemplo de solicitud

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "gateway": "MERCADOPAGO_ORDER_PIX",
    "coupon": "BEMVINDO10",
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

Para boleto de Mercado Pago, configura `gateway` como `MERCADOPAGO_ORDER_BOLETO`; para saldo de Mercado Pago, usa `MERCADOPAGO_ORDER_SALDO`. Ambos usan el mismo body del ejemplo PIX; solo cambia `gateway`.

### 💳 Ejemplo con Asaas (PIX)

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "cpf": "12345678909",
    "gateway": "ASAAS_ORDER_PIX",
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

Para boleto de Asaas, usa la misma solicitud y cambia `gateway` por `ASAAS_ORDER_BOLETO`. Para tarjeta alojada, usa `ASAAS_ORDER_CARD`; para un cobro directo con tarjeta, envía también un token y los datos del titular según la sección **Tarjeta transparente (tokenizada)**.

### 💳 Ejemplo con EFI Bank (PIX)

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "cpf": "12345678909",
    "gateway": "EFI_BANK_ORDER_PIX",
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

Para boleto, usa `EFI_BANK_ORDER_BOLETO`. La tarjeta EFI requiere tokenización en el frontend y el teléfono del comprador:

```json theme={null}
{
  "name": "João Silva",
  "email": "joao@email.com",
  "cpf": "12345678909",
  "gateway": "EFI_BANK_ORDER_CARD",
  "metadata": {
    "gateway": {
      "card": {
        "payment_token": "TOKEN_GENERADO_POR_EL_SDK_EFI",
        "phone_number": "11999999999",
        "installmentCount": 1
      }
    }
  },
  "items": [
    { "productId": "PRODUCT_ID", "quantity": 1 }
  ]
}
```

### 💳 Ejemplo con Stripe Checkout (PIX)

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "gateway": "STRIPE_ORDER_PIX",
    "metadata": {
      "successUrl": "https://tienda.ejemplo.com/pago/exito",
      "cancelUrl": "https://tienda.ejemplo.com/pago/cancelado"
    },
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

Para tarjeta o boleto en Stripe, cambia `gateway` por `STRIPE_ORDER_CARD` o `STRIPE_ORDER_BOLETO`. Si `successUrl` o `cancelUrl` se omiten, la API usa el dominio de la tienda (`store.Domain`) o `SiteBaseURL` cuando la tienda no tiene un dominio configurado.

### 💳 Ejemplo con Tarjeta parcelada (6x, Mercado Pago)

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "cpf": "12345678909",
    "gateway": "MERCADOPAGO_ORDER_CARD",
    "metadata": {
      "gateway": { "card": { "installmentCount": 6 } }
    },
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

***

## 🧩 Snippet (cURL)

```bash theme={null}
curl -s -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/payments" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "João Silva",
    "email": "joao@email.com",
    "gateway": "MERCADOPAGO_ORDER_PIX",
    "coupon": "BEMVINDO10",
    "items": [
      { "productId": "PRODUCT_ID", "quantity": 1 }
    ]
  }'
```

***

## 📦 Respuestas

### 201 — Pago via gateway (PIX / Mercado Pago)

```json theme={null}
{
  "status": true,
  "data": {
    "service": {
      "type": "MERCADOPAGO",
      "method": "MERCADOPAGO_ORDER_PIX",
      "payment": "PIX"
    },
    "payment": {
      "uuid": "8cf7de6e-4c92-4baf-b978-2f9195f2e0e2",
      "init_point": "https://www.mercadopago.com.br/...",
      "qr_code": {
        "image": "base64...",
        "base_64": "00020126..."
      }
    }
  }
}
```

### 201 — Pago via gateway (Tarjeta / Mercado Pago)

```json theme={null}
{
  "status": true,
  "data": {
    "service": {
      "type": "MERCADOPAGO",
      "method": "MERCADOPAGO_ORDER_CARD",
      "payment": "CARD"
    },
    "payment": {
      "uuid": "8cf7de6e-4c92-4baf-b978-2f9195f2e0e2",
      "init_point": "https://www.mercadopago.com.br/checkout/..."
    }
  }
}
```

### 201 — Pago via gateway (PIX / Asaas)

```json theme={null}
{
  "status": true,
  "data": {
    "service": {
      "type": "ASAAS",
      "method": "ASAAS_ORDER_PIX",
      "payment": "PIX"
    },
    "payment": {
      "uuid": "8cf7de6e-4c92-4baf-b978-2f9195f2e0e2",
      "id": "pay_edji4wdwby9402g3",
      "status": "PENDING",
      "environment": "SANDBOX",
      "init_point": "https://www.asaas.com/i/edji4wdwby9402g3",
      "invoiceUrl": "https://www.asaas.com/i/edji4wdwby9402g3",
      "copyPastePix": "00020126...",
      "pixQrCode": {
        "encodedImage": "base64...",
        "payload": "00020126...",
        "expirationDate": "2026-09-08"
      }
    }
  }
}
```

> Para **Asaas**, acompaña el `status` / `id` via `metadata.gateway` en el filtro de pagos (la cola de verificación consulta la gateway directamente). La factura hospedada (`invoiceUrl` / `init_point`) permite al comprador pagar por PIX, tarjeta o boleto sin tokenización.

### 201 — Pago gratuito

```json theme={null}
{
  "data": {
    "service": {
      "type": "FREE_PAYMENT",
      "method": "FREE_PAYMENT",
      "payment": "FREE_PAYMENT"
    },
    "payment": {
      "uuid": "8cf7de6e-4c92-4baf-b978-2f9195f2e0e2"
    }
  }
}
```

### 200 — Replay de idempotencia (`Idempotency-Key` / `idempotencyKey`)

Cuando la solicitud reutiliza una clave ya procesada en la tienda (vía header `Idempotency-Key` o campo `idempotencyKey` en el body), la API no crea un pago duplicado y devuelve HTTP **`200`** con el payload original guardado de la creación:

```json theme={null}
{
  "status": true,
  "data": {
    "service": {
      "type": "MERCADOPAGO",
      "method": "MERCADOPAGO_ORDER_PIX",
      "payment": "PIX"
    },
    "payment": {
      "uuid": "8cf7de6e-4c92-4baf-b978-2f9195f2e0e2",
      "init_point": "https://www.mercadopago.com.br/...",
      "qr_code": {
        "image": "base64...",
        "base_64": "00020126..."
      }
    }
  }
}
```

> Si la respuesta original aún no se ha guardado, el fallback `200` devuelve `{"status": true, "data": {"payment": {"uuid": "...", "status": "..."}}}`.

***

## ⚠️ Errores

| Status | Código | Descripción |
| - | - | - |
| `400` | `INVALID_DATA` | Body inválido o campo ausente |
| `400` | `INVALID_INSTALLMENT_COUNT` | Número de cuotas inválido (\< 1 o no entero) |
| `400` | `MAX_INSTALLMENTS_EXCEEDED` | `installmentCount` por encima del `maxInstallments` de la tienda |
| `400` | `GATEWAY_NOT_ENABLED` | Gateway no habilitado en la tienda |
| `400` | `INVALID_COUPON` | Cupón no existe o no aplicable a los productos |
| `400` | `COUPON_EXPIRED` | Cupón expirado o sin usos |
| `400` | `COUPON_AFFILIATE_ONLY` | Cupón restringido a códigos de afiliado específicos |
| `400` | `COUPON_PAYMENT_METHOD_INVALID` | Cupón no permitido para el gateway/método elegido |
| `400` | `COUPON_ALREADY_USED` | Cupón de uso único ya utilizado por este cliente (email o CPF) |
| `400` | `COUPON_MIN_ORDER_AMOUNT` | Subtotal del pedido por debajo del monto mínimo del cupón |
| `400` | `COUPON_MIN_ITEMS_QUANTITY` | Cantidad total de elementos por debajo del mínimo del cupón |
| `400` | `OUT_OF_STOCK` | Stock insuficiente (incluye el campo `productId`) |
| `400` | `PRODUCT_DISABLED` | Producto deshabilitado para compra (incluye el campo `productId`) |
| `401` | `UNAUTHENTICATED` | Error al identificar al propietario de la tienda al validar el plan |
| `403` | `NO_ACTIVE_SUBSCRIPTION` | Suscripción del propietario de la tienda inactiva o expirada |
| `404` | `STORE_NOT_FOUND` | Tienda no encontrada |
| `404` | `PRODUCT_NOT_FOUND` | Producto no encontrado (incluye el campo `productId`) |
| `429` | `RATE_LIMIT_EXCEEDED` | Límite de solicitudes por minuto del plan excedido |
| `500` | `GATEWAY_ERROR` | Error interno al procesar la respuesta de la gateway (incluye el campo `error`) |
| `500` | `INTERNAL_SERVER_ERROR` | Error interno |
| `502` | `GATEWAY_ERROR` | Error devuelto por el proveedor de pago (incluye el campo `error` con el cuerpo del proveedor) |
| `503` | `SERVICE_UNAVAILABLE` | Servicio temporalmente no disponible |

> En los errores `400 OUT_OF_STOCK`, `400 PRODUCT_DISABLED` y `404 PRODUCT_NOT_FOUND`, la respuesta incluye el campo `productId` identificando el elemento (`{"code": "...", "productId": "..."}`).


## OpenAPI

````yaml POST /stores/{storeId}/payments
openapi: 3.1.0
info:
  title: caBRAPI
  version: 1.0.0
servers:
  - url: https://api.cabrapi.com.br/v1
security: []
paths:
  /stores/{storeId}/payments:
    post:
      tags:
        - Payments
      summary: Create payment
      operationId: createPayment
      parameters:
        - $ref: '#/components/parameters/StoreId'
        - in: header
          name: Idempotency-Key
          required: false
          description: Optional idempotency key to prevent duplicate charges.
          schema:
            type: string
            maxLength: 255
      requestBody:
        required: true
        description: Charge details (items, customer, gateway).
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - email
                - gateway
                - items
              properties:
                name:
                  type: string
                  minLength: 3
                  maxLength: 50
                email:
                  type: string
                  format: email
                  minLength: 12
                  maxLength: 100
                cpf:
                  type: string
                  maxLength: 24
                  nullable: true
                gateway:
                  type: string
                  minLength: 1
                  maxLength: 50
                coupon:
                  type: string
                  maxLength: 32
                  nullable: true
                idempotencyKey:
                  type: string
                  maxLength: 255
                  nullable: true
                metadata:
                  nullable: true
                  type: object
                items:
                  type: array
                  minItems: 1
                  items:
                    type: object
                    required:
                      - productId
                      - quantity
                    properties:
                      productId:
                        type: string
                        minLength: 1
                        maxLength: 50
                      quantity:
                        type: integer
                        minimum: 1
                        maximum: 50
                      billingCycleMonths:
                        type: integer
                        minimum: 1
                        maximum: 60
                        nullable: true
      responses:
        '200':
          content:
            application/json:
              schema:
                properties:
                  data:
                    type: object
                  status:
                    example: true
                    type: boolean
                required:
                  - data
                type: object
          description: Idempotent replay of an already-created payment.
        '201':
          content:
            application/json:
              schema:
                properties:
                  data:
                    type: object
                  status:
                    example: true
                    type: boolean
                required:
                  - data
                type: object
          description: Payment created.
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Invalid request.
        '401':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Unauthorized (missing store owner or unavailable database).
        '403':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Forbidden (inactive plan or insufficient permissions).
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Resource not found.
        '429':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Rate limit exceeded.
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Internal server error.
        '502':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Upstream gateway or storage error.
        '503':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Service unavailable.
      security: []
components:
  parameters:
    StoreId:
      in: path
      name: storeId
      required: true
      schema:
        type: string
        minLength: 1
        maxLength: 50
  schemas:
    Error:
      properties:
        code:
          example: STORE_NOT_FOUND
          type: string
      required:
        - code
      type: object

````

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