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

# Webhooks: ClearPago → comerciante

> O que o comerciante implementa: endpoint receptor, Digital-Signature ECDSA P-256 SHA-256, eventos, retry e boas práticas.

## O que você implementa

Um endpoint `POST` público acessível via **HTTPS** que recebe notificações assinadas da ClearPago. A plataforma envia um `POST` com `Content-Type: application/json` e o header `Digital-Signature` em cada evento relevante.

**Você não implementa** os webhooks de entrada do parceiro BaaS — esses ficam dentro da plataforma.

## Registrar seu endpoint

Antes de receber notificações, registre sua URL:

```bash theme={null}
curl -X POST https://api.clearpago.com.br/webhook \
  -H "Authorization: Bearer <seu_api_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://seu-sistema.com/webhooks/pix",
    "events": ["pix_cash_in", "pix_cash_out", "pix_cash_in_reversal", "pix_cash_out_reversal"]
  }'
```

`TODO: confirmar o corpo exato de POST /webhook com a spec interna.`

## Formato HTTP da notificação

```http theme={null}
POST https://seu-sistema.com/webhooks/pix
Content-Type: application/json
Digital-Signature: <base64(ECDSA P-256 SHA-256(rawBody))>
```

## Eventos suportados

| `event_type`            | Condição de disparo                           |
| ----------------------- | --------------------------------------------- |
| `pix_cash_in`           | Cash-in atinge `PAID` ou `FAILED`             |
| `pix_cash_out`          | Cash-out atinge `CONFIRMED` ou `FAILED`       |
| `pix_cash_in_reversal`  | Refund-in atinge `CONFIRMED` ou `FAILED`      |
| `pix_cash_out_reversal` | Cash-out previamente `CONFIRMED` é `REVERSED` |

## Payloads por evento

### `pix_cash_in`

```json theme={null}
{
  "event_type": "pix_cash_in",
  "event": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "correlation_id": "req-001",
    "external_id": "pedido-12345",
    "transaction_id": "12345",
    "status": "PAID",
    "value_cents": 15075,
    "end_to_end_id": "E00416968202504011200rjzxxzSSTD9",
    "payer_name": "João da Silva",
    "fee_amount_cents": 5,
    "confirmed_at": "2026-04-01T12:10:00.000000000Z",
    "created_at": "2026-04-01T12:00:00.000000000Z"
  }
}
```

### `pix_cash_out`

```json theme={null}
{
  "event_type": "pix_cash_out",
  "event": {
    "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
    "correlation_id": "transfer-001",
    "external_id": "saque-789",
    "transaction_id": "54321",
    "status": "CONFIRMED",
    "value_cents": 50000,
    "end_to_end_id": "E07136847202504011200O7654ABCD12",
    "fee_amount_cents": 10,
    "confirmed_at": "2026-04-01T12:30:00.000000000Z",
    "created_at": "2026-04-01T12:00:00.000000000Z"
  }
}
```

### `pix_cash_in_reversal`

```json theme={null}
{
  "event_type": "pix_cash_in_reversal",
  "event": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "correlation_id": "req-001",
    "external_id": "estorno-12345",
    "transaction_id": "11111",
    "status": "CONFIRMED",
    "value_cents": 15075,
    "end_to_end_id": "D07136847202504011500O5222ZRBI5A",
    "fee_amount_cents": 1,
    "confirmed_at": "2026-04-01T15:05:00.000000000Z",
    "created_at": "2026-04-01T15:00:00.000000000Z"
  }
}
```

<Warning>
  **`event.id` em `pix_cash_in_reversal`** é o UUID do **cash-in original**, não do refund-in. O `event.external_id` é o `externalId` do refund-in. Para idempotência, use `transaction_id` + `end_to_end_id` do estorno.
</Warning>

### `pix_cash_out_reversal`

```json theme={null}
{
  "event_type": "pix_cash_out_reversal",
  "event": {
    "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
    "correlation_id": "transfer-001",
    "external_id": "saque-789",
    "transaction_id": "54321",
    "status": "REVERSED",
    "value_cents": 50000,
    "end_to_end_id": "D07136847202504021600O9999ABCD99",
    "fee_amount_cents": 0,
    "confirmed_at": "2026-04-02T09:05:00.000000000Z",
    "created_at": "2026-04-01T12:00:00.000000000Z"
  }
}
```

## Resposta esperada

* **Tempo:** responda `2xx` em **menos de 5 segundos**.
* **Código:** `200` ou `204`.
* **Corpo:** pode ser vazio.
* **Em caso de erro:** `5xx` gera retentativa com backoff; `4xx` pode não gerar retentativa.

## Segurança

1. [Verificar `Digital-Signature`](/guides/verify-webhook-signatures) **antes de qualquer lógica**.
2. Rejeitar com `401` se inválida.
3. Usar **HTTPS** com certificado público válido.
4. Nunca processar payload sem assinatura verificada.

## Retry e backoff

A plataforma realiza retentativas em caso de `5xx` ou timeout usando **backoff exponencial**. Por isso:

* Handlers **devem ser idempotentes**.
* Responda `2xx` assim que a assinatura for verificada; não aguarde o processamento completo.

## Canais de entrega

| Tipo de operação   | Canal                                 | Característica                               |
| ------------------ | ------------------------------------- | -------------------------------------------- |
| Cash-in, refund-in | **Outbox** (commit-first)             | Entrega durável, latência baixa a moderada   |
| Cash-out, reversão | **Pool de goroutines** + fallback SQS | Geralmente baixa latência; SQS em alta carga |

Não assuma ordem garantida entre eventos. Deduplicação é sempre necessária.

## Referências

* [Guia: registrar webhooks](/guides/register-merchant-webhooks)
* [Guia: verificar assinaturas](/guides/verify-webhook-signatures)
* [Referência de eventos (tabela completa)](/webhooks/webhook-event-reference)
* [Webhooks: parceiro → ClearPago](/webhooks/partner-to-clearpago)
