> ## 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.

# Cobrança instantânea

> Entenda como funciona quando o startAt é definido como a data atual

Quando você cria uma assinatura com `startAt` definido como a data atual, o motor de recorrência da Malga processa a primeira cobrança imediatamente. Este comportamento especial permite que você inicie a cobrança no mesmo dia da criação da assinatura.

<Warning>
  **Importante**: O campo `startAt` deve ser informado em formato UTC (YYYY-MM-DD).
</Warning>

## Comportamento especial

Ao definir `startAt` como a data atual, o motor de recorrência:

1. **Processa a cobrança imediatamente** após a criação da assinatura
2. **Retorna informações detalhadas** sobre o processamento na resposta da API
3. **Envia webhooks específicos** para notificar sobre o resultado da cobrança
4. **Atualiza o status** da assinatura baseado no resultado da cobrança

## Exemplo de criação com startAt sendo hoje

<CodeGroup>
  ```bash Request theme={null}
  curl --location 'https://api.malga.io/v1/subscriptions' \
  --header 'Content-Type: application/json' \
  --header 'X-Client-Id: YOUR_CLIENT_ID' \
  --header 'X-Api-Key: YOUR_API_KEY' \
  --data '{
    "name": "Assinatura Premium com Eventos",
    "merchantId": "YOUR_MERCHANT_ID",
    "customerId": "YOUR_CUSTOMER_ID",
    "referenceKey": "SUB-PREMIUM-001",
    "recurrence": {
      "interval": "monthly",
      "startAt": "2025-08-06"
    },
    "paymentMethod": {
      "type": "credit",
      "card": {
        "cardId": "YOUR_CARD_ID"
      }
    },
    "items": [
      {
        "name": "Ingresso VIP Mensal",
        "description": "Acesso VIP premium a eventos mensais",
        "amount": 29900,
        "quantity": 1,
        "sku": "VIP-EVENT-001",
        "risk": "Low",
        "categoryId": "entertainment",
        "locality": "São Paulo",
        "date": "2025-12-01",
        "type": 1,
        "genre": "Shows e Eventos",
        "tickets": {
          "quantityTicketSale": 1,
          "convenienceFeeValue": 15.5,
          "quantityFull": 1,
          "batch": 1
        },
        "location": {
          "street": "Av. Paulista",
          "number": "1000",
          "complement": "Centro de Convenções",
          "zipCode": "01310-100",
          "city": "São Paulo",
          "state": "SP",
          "country": "Brasil",
          "district": "Bela Vista",
          "reference": "Próximo ao MASP"
        }
      }
    ]
  }'
  ```

  ```json Response - Success theme={null}
  {
      "id": "subscription_id_example",
      "name": "Assinatura Premium com Eventos",
      "clientId": "YOUR_CLIENT_ID",
      "merchantId": "YOUR_MERCHANT_ID",
      "customerId": "YOUR_CUSTOMER_ID",
      "referenceKey": "SUB-PREMIUM-001",
      "currency": "BRL",
      "items": [
          {
              "name": "Ingresso VIP Mensal",
              "description": "Acesso VIP premium a eventos mensais",
              "amount": 29900,
              "quantity": 1,
              "sku": "VIP-EVENT-001",
              "risk": "Low",
              "categoryId": "entertainment",
              "locality": "São Paulo",
              "date": "2025-12-01",
              "type": 1,
              "genre": "Shows e Eventos",
              "tickets": {
                  "quantityTicketSale": 1,
                  "convenienceFeeValue": 15.5,
                  "quantityFull": 1,
                  "batch": 1
              },
              "location": {
                  "street": "Av. Paulista",
                  "number": "1000",
                  "complement": "Centro de Convenções",
                  "zipCode": "01310-100",
                  "city": "São Paulo",
                  "state": "SP",
                  "country": "Brasil",
                  "district": "Bela Vista",
                  "reference": "Próximo ao MASP"
              }
          }
      ],
      "recurrence": {
          "interval": "monthly",
          "startAt": "2025-08-05",
          "nextDueDate": "2025-09-05"
      },
      "paymentMethod": {
          "type": "credit",
          "card": {
              "cardId": "YOUR_CARD_ID"
          },
          "installments": 1
      },
      "status": "active",
      "amount": 29900,
      "liveMode": true,
      "lastCycle": {
          "id": "cycle_id_example",
          "customerId": "YOUR_CUSTOMER_ID",
          "merchantId": "YOUR_MERCHANT_ID",
          "cycle": 1,
          "attempts": 1,
          "status": "authorized",
          "isEmulated": false,
          "createdAt": "2025-08-05T17:59:45.243691Z",
          "scheduledAt": "2025-08-05",
          "executedAt": "2025-08-05",
          "paymentHistory": [
              {
                  "id": "payment_history_id_example",
                  "createdAt": "2025-08-05T17:59:45.249579Z",
                  "chargeId": "charge_id_example",
                  "attemptNumber": 1,
                  "status": "authorized",
                  "error": null
              }
          ]
      },
      "createdAt": "2025-08-05T17:59:45.219657Z",
      "updatedAt": "2025-08-05T17:59:47.02068159Z"
  }
  ```

  ```json Response - Error theme={null}
  {
      "id": "subscription_id_example",
      "name": "Assinatura Premium com Eventos",
      "clientId": "YOUR_CLIENT_ID",
      "merchantId": "YOUR_MERCHANT_ID",
      "customerId": "YOUR_CUSTOMER_ID",
      "referenceKey": "SUB-PREMIUM-001",
      "currency": "BRL",
      "items": [
          {
              "name": "Ingresso VIP Mensal",
              "description": "Acesso VIP premium a eventos mensais",
              "amount": 29900,
              "quantity": 1,
              "sku": "VIP-EVENT-001",
              "risk": "Low",
              "categoryId": "entertainment",
              "locality": "São Paulo",
              "date": "2025-12-01",
              "type": 1,
              "genre": "Shows e Eventos",
              "tickets": {
                  "quantityTicketSale": 1,
                  "convenienceFeeValue": 15.5,
                  "quantityFull": 1,
                  "batch": 1
              },
              "location": {
                  "street": "Av. Paulista",
                  "number": "1000",
                  "complement": "Centro de Convenções",
                  "zipCode": "01310-100",
                  "city": "São Paulo",
                  "state": "SP",
                  "country": "Brasil",
                  "district": "Bela Vista",
                  "reference": "Próximo ao MASP"
              }
          }
      ],
      "recurrence": {
          "interval": "monthly",
          "startAt": "2025-08-06",
          "nextDueDate": "2025-09-06"
      },
      "paymentMethod": {
          "type": "credit",
          "card": {
              "cardId": "YOUR_CARD_ID"
          },
          "installments": 1
      },
      "status": "created",
      "amount": 29900,
      "liveMode": true,
      "lastCycle": {
          "id": "cycle_id_example",
          "customerId": "YOUR_CUSTOMER_ID",
          "merchantId": "YOUR_MERCHANT_ID",
          "cycle": 1,
          "attempts": 1,
          "status": "retrying",
          "isEmulated": false,
          "createdAt": "2025-08-06T13:57:36.3877Z",
          "scheduledAt": "2025-08-06",
          "executedAt": "2025-08-06",
          "nextAttemptAt": "2025-08-07",
          "paymentHistory": [
              {
                  "id": "payment_history_id_example",
                  "createdAt": "2025-08-06T13:57:36.396306Z",
                  "chargeId": null,
                  "attemptNumber": 1,
                  "status": "failed",
                  "error": {
                      "code": 404,
                      "details": null,
                      "message": "Card not found",
                      "type": "invalid_request_error"
                  }
              }
          ]
      },
      "createdAt": "2025-08-06T13:57:36.295605Z",
      "updatedAt": "2025-08-06T13:57:36.39395571Z"
  }
  ```
</CodeGroup>

<Info>
  **Sobre o campo `lastCycle`**: O campo `lastCycle` sempre está presente nas respostas individuais de assinatura (GET, CREATE, UPDATE), mesmo quando não há cobrança instantânea. Quando não existem faturas, o campo será `null`. Nos exemplos acima, o campo contém um objeto porque há cobrança instantânea, mas em outros cenários você pode receber `"lastCycle": null`.
</Info>

## Webhooks específicos

Quando você cria uma assinatura com cobrança instantânea, você receberá webhooks específicos:

### Ordem de eventos

1. Quando a assinatura é criada: **`subscription.created`**;
2. Quando a cobrança é processada:
   * **`subscription.activated`** (em caso de sucesso);
   * **`subscription.cycle_failed`** (quando há falha no processamento da cobrança);
3. **`subscription.unpaid`** (após esgotar todas as tentativas de cobrança da fatura).

### Novo webhook: subscription.cycle\_failed

Este webhook é enviado quando uma fatura de cobrança falha após todas as retentativas:

```json theme={null}
{
  "id": "webhook_event_id_example",
  "apiVersion": "1.1",
  "object": "subscription",
  "event": "cycle_failed",
  "createdAt": "2025-08-06T13:57:36.672Z",
  "data": {
    "subscription": {
      "id": "subscription_id_example",
      "name": "Assinatura Premium com Eventos",
      "clientId": "YOUR_CLIENT_ID",
      "merchantId": "YOUR_MERCHANT_ID",
      "customerId": "YOUR_CUSTOMER_ID",
      "referenceKey": "SUB-PREMIUM-001",
      "currency": "BRL",
      "items": [
        {
          "name": "Ingresso VIP Mensal",
          "description": "Acesso VIP premium a eventos mensais",
          "amount": 29900,
          "quantity": 1,
          "sku": "VIP-EVENT-001",
          "risk": "Low",
          "categoryId": "entertainment",
          "locality": "São Paulo",
          "date": "2025-12-01",
          "type": 1,
          "genre": "Shows e Eventos",
          "tickets": {
            "quantityTicketSale": 1,
            "convenienceFeeValue": 15.5,
            "quantityFull": 1,
            "batch": 1
          },
          "location": {
            "street": "Av. Paulista",
            "number": "1000",
            "complement": "Centro de Convenções",
            "zipCode": "01310-100",
            "city": "São Paulo",
            "state": "SP",
            "country": "Brasil",
            "district": "Bela Vista",
            "reference": "Próximo ao MASP"
          }
        }
      ],
      "recurrence": {
        "interval": "monthly",
        "startAt": "2025-08-06",
        "nextDueDate": "2025-09-06"
      },
      "paymentMethod": {
        "type": "credit",
        "card": {
          "cardId": "YOUR_CARD_ID"
        },
        "installments": 1
      },
      "status": "created",
      "amount": 29900,
      "liveMode": true,
      "createdAt": "2025-08-06T13:57:36.295605Z",
      "updatedAt": "2025-08-06T13:57:36.393955Z",
      "lastCycle": {
        "id": "cycle_id_example",
        "customerId": "YOUR_CUSTOMER_ID",
        "merchantId": "YOUR_MERCHANT_ID",
        "cycle": 1,
        "attempts": 1,
        "status": "pending",
        "isEmulated": false,
        "createdAt": "2025-08-06T13:57:36.3877Z",
        "scheduledAt": "2025-08-06",
        "paymentHistory": [
          {
            "id": "payment_history_id_example",
            "createdAt": "2025-08-06T13:57:36.396306294Z",
            "chargeId": null,
            "attemptNumber": 1,
            "status": "pending",
            "error": null
          }
        ]
      }
    },
    "errorCode": 404
  }
}
```

## Observações importantes

* **Campo `lastCycle`**: Sempre presente nas respostas individuais de subscription (GET, CREATE, UPDATE). Pode ser `null` se não houver cycles, ou um objeto completo com os detalhes do último cycle. Na cobrança instantânea, o campo conterá informações sobre o cycle processado imediatamente.
* **Status da assinatura**:
  * Sucesso: `active`
  * Erro: `created` (permanece até [retentativas esgotadas](/documentations/more/recurrence/engine#retentativas-e-recuperação-de-falhas))
* **Status da fatura**:
  * Sucesso: `authorized`
  * Erro: `retrying`
* **Payment History**: Contém detalhes de cada tentativa, incluindo erros
* **Next Attempt**: Indica quando será a próxima tentativa de cobrança

## Próximos passos

<CardGroup cols={2}>
  <Card title="Gerenciar assinatura" icon="gear" href="/documentations/more/recurrence/engine/managing">
    Aprenda como gerenciar assinaturas após a criação
  </Card>

  <Card title="Configurar webhooks" icon="webhook" href="/documentations/more/recurrence/engine/webhooks">
    Configure webhooks para receber notificações em tempo real
  </Card>
</CardGroup>
