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

# Webhooks & Eventos

> Comandos para escutar, simular e depurar webhooks e eventos na AbacatePay CLI.

Comandos para escutar, simular e depurar webhooks durante o desenvolvimento.

***

### `abacatepay listen`

Escuta webhooks em tempo real e os encaminha para sua aplicação local.

```bash theme={null}
abacatepay listen [flags]
```

| Flag           | Alias | Descrição                                   | Padrão                                      |
| -------------- | ----- | ------------------------------------------- | ------------------------------------------- |
| `--forward-to` | -     | URL para onde os eventos serão encaminhados | `http://localhost:3000/webhooks/abacatepay` |
| `--mock`       | -     | Simula webhooks sem conectar à API          | `false`                                     |

<Info>
  O comando `listen` mantém uma conexão WebSocket ativa com a AbacatePay para receber eventos em tempo real. Todos os eventos recebidos são salvos no log local.

  Se você não especificar `--forward-to`, a CLI perguntará via prompt qual URL usar.
</Info>

**Exemplos:**

```bash theme={null}
# Escutar e encaminhar para o endpoint padrão
abacatepay listen

# Encaminhar para URL personalizada
abacatepay listen --forward-to http://localhost:8080/webhook

# Modo simulação (sem conexão com a API)
abacatepay listen --mock
```

<Tip>
  Use `Ctrl+C` para interromper. Todos os eventos ficam salvos e podem ser consultados com `abacatepay logs list`.
</Tip>

***

### `abacatepay trigger`

Dispara eventos de teste para simular webhooks durante o desenvolvimento.

```bash theme={null}
abacatepay trigger <event>
```

**Eventos disponíveis:**

| Evento          | Descrição                              |
| --------------- | -------------------------------------- |
| `billing.paid`  | Simula o pagamento de uma cobrança Pix |
| `payout.done`   | Simula um saque concluído com sucesso  |
| `payout.failed` | Simula uma falha em saque              |

<Warning>
  O evento `billing.paid` cria uma cobrança Pix real na API (em modo teste) e simula seu pagamento. Os eventos `payout.*` geram apenas payloads mock locais.
</Warning>

```bash theme={null}
abacatepay trigger billing.paid
```

<CodeGroup>
  ```text text theme={null}
  ╭────────────────────────────────────────────────────────────────╮
  │                                                                │
  │  🥑 Billing.paid Triggered                                     │
  │                                                                │
  │  Charge ID: pix_abc123xyz                                      │
  │  Status:    Simulated                                          │
  │  Note:      Check your 'listen' terminal for the webhook event │
  │                                                                │
  ╰────────────────────────────────────────────────────────────────╯
  ```

  ```json json theme={null}
  {
    "event": "billing.paid",
    "chargeId": "pix_abc123xyz"
  }
  ```
</CodeGroup>

<Tip>
  Execute `abacatepay listen` em outro terminal antes de usar `trigger` para receber os webhooks.
</Tip>

***

### `abacatepay events sample`

Gera um payload JSON de exemplo para um tipo de evento específico.

```bash theme={null}
abacatepay events sample <event>
```

**Eventos:** `billing.paid`, `payout.done`, `payout.failed`

```bash theme={null}
# Gerar sample de billing.paid
abacatepay events sample billing.paid

# Salvar em arquivo
abacatepay events sample billing.paid > payload.json
```

<CodeGroup>
  ```json billing.paid theme={null}
  {
    "id": "evt_abc123",
    "event": "billing.paid",
    "devMode": true,
    "data": {
      "payment": {
        "amount": 1000,
        "fee": 0,
        "method": "PIX"
      },
      "billing": {
        "id": "bill_xyz789",
        "externalId": "uuid-v4-example",
        "url": "https://abacatepay.com/pay/...",
        "amount": 1000,
        "status": "PAID"
      }
    }
  }
  ```

  ```json payout.done theme={null}
  {
    "id": "evt_def456",
    "event": "payout.done",
    "devMode": true,
    "data": {
      "transaction": {
        "id": "txn_abc123",
        "status": "COMPLETE",
        "devMode": true,
        "receiptUrl": "https://abacatepay.com/receipt/...",
        "kind": "WITHDRAW",
        "amount": 5000,
        "platformFee": 0,
        "externalId": "uuid-v4-example",
        "createdAt": "2026-01-21T10:30:00Z",
        "updatedAt": "2026-01-21T10:30:00Z"
      }
    }
  }
  ```

  ```json payout.failed theme={null}
  {
    "id": "evt_ghi789",
    "event": "payout.failed",
    "devMode": true,
    "data": {
      "transaction": {
        "id": "txn_xyz456",
        "status": "CANCELLED",
        "kind": "WITHDRAW",
        "amount": 3000,
        "platformFee": 0,
      }
    }
  }
  ```
</CodeGroup>

<Info>
  Use este comando para entender a estrutura dos payloads e configurar corretamente o parsing na sua aplicação.
</Info>

***

### `abacatepay events resend`

Reenvia um evento passado para seu endpoint de webhook local.

```bash theme={null}
abacatepay events resend <event-id> [flags]
```

| Flag           | Alias | Descrição                             | Padrão                                                      |
| -------------- | ----- | ------------------------------------- | ----------------------------------------------------------- |
| `--forward-to` | -     | URL para onde o evento será reenviado | URL original ou `http://localhost:3000/webhooks/abacatepay` |

<Info>
  O evento é buscado no arquivo de log local. O ID pode ser obtido através de `abacatepay logs list`.
</Info>

```bash theme={null}
abacatepay events resend evt_abc123xyz
```

<CodeGroup>
  ```text text theme={null}
  Webhook signing secret: whsec_abacate_local_dev_secret
  Resending event evt_abc123xyz to http://localhost:3000/webhooks/abacatepay...

  → [200 OK] billing.paid

  ╭───────────────────────────────╮
  │                               │
  │  🥑 Event resent successfully │
  │                               │
  │  ID:       evt_abc123xyz      │
  │  Status:   200 OK             │
  │  Duration: 45ms               │
  │                               │
  ╰───────────────────────────────╯
  ```

  ```json json theme={null}
  {
    "id": "evt_abc123xyz",
    "status": 200,
    "statusText": "OK",
    "duration": "45ms"
  }
  ```
</CodeGroup>

<Tip>
  O header `X-Abacate-Signature` é gerado automaticamente com assinatura válida para ambiente de desenvolvimento.
</Tip>

***

### `abacatepay logs list`

Lista o histórico de eventos de webhook gravados localmente.

```bash theme={null}
abacatepay logs list [flags]
```

| Flag      | Alias | Descrição                   | Padrão |
| --------- | ----- | --------------------------- | ------ |
| `--limit` | `-n`  | Número de entradas a exibir | `50`   |
| `--type`  | `-t`  | Filtrar por tipo de log     | -      |

**Tipos de log disponíveis:**

| Tipo                     | Descrição                       |
| ------------------------ | ------------------------------- |
| `webhook_received`       | Webhook recebido da API         |
| `webhook_forwarded`      | Webhook encaminhado com sucesso |
| `webhook_forward_failed` | Falha ao encaminhar (erro HTTP) |
| `webhook_forward_error`  | Erro de conexão ao encaminhar   |

```bash theme={null}
# Listar últimos 50 logs
abacatepay logs list

# Listar últimos 10 logs
abacatepay logs list -n 10

# Filtrar apenas webhooks recebidos
abacatepay logs list -t webhook_received
```

<CodeGroup>
  ```text table theme={null}
  ┌─────────────────────────┬─────────────────────────┬───────────────┬────────────────────────────────────┐
  │ Timestamp               │ Type                    │ ID            │ URL                                │
  ├─────────────────────────┼─────────────────────────┼───────────────┼────────────────────────────────────┤
  │ 2026-01-21T10:30:00Z    │ webhook_forwarded [200] │ evt_abc123    │ http://localhost:3000/webhooks/abacatepay │
  │ 2026-01-21T10:29:55Z    │ webhook_received        │ evt_abc123    │ http://localhost:3000/webhooks/abacatepay │
  └─────────────────────────┴─────────────────────────┴───────────────┴────────────────────────────────────┘
  ```

  ```json json theme={null}
  {
    "logs": [
      {
        "timestamp": "2026-01-21T10:30:00Z",
        "msg": "webhook_forwarded",
        "id": "evt_abc123",
        "url": "http://localhost:3000/webhooks/abacatepay",
        "statusCode": 200,
        "size_bytes": 1024,
        "raw_message": "{\"id\":\"evt_abc123\",\"event\":\"billing.paid\",...}",
        "event": "billing.paid",
        "level": "INFO"
      }
    ],
    "count": 1
  }
  ```
</CodeGroup>

***

### `abacatepay logs tail`

Exibe eventos de webhook em tempo real via streaming.

```bash theme={null}
abacatepay logs tail
```

<Info>
  Este comando conecta ao WebSocket e exibe os eventos conforme chegam, sem encaminhá-los para nenhum endpoint.
</Info>

```text theme={null}
Streaming webhook events...

Press Ctrl+C to stop

[2026-01-21T10:30:00Z] billing.paid - evt_abc123xyz
  Amount: R$ 10,00
  Status: paid

^C
Listener stopped
```

<Tip>
  Use `logs tail` para monitorar eventos sem processá-los. Para receber e encaminhar webhooks, use `abacatepay listen`.
</Tip>

***
