# Visão geral

> Receba um POST assinado quando algo acontecer, em vez de perguntar.

## Cadastrar um endpoint

```bash
curl https://api.ingot.com.br/webhooks/endpoints \
  -H "Authorization: ApiKey $CORE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "customer_id": "id-da-sua-empresa",
    "url": "https://sua-empresa.com.br/webhooks/core",
    "events": ["transaction.settled", "transaction.failed", "transaction.returned"]
  }'
```

A URL precisa ser HTTPS. A resposta traz o `secret` do endpoint **uma única vez**: é com ele que você verifica a assinatura.

## O que chega

Headers:

```text
content-type: application/json
x-corebanking-event-id: 3b1f9c2e-8d4a-4e7b-9f10-6c2d8e5a1b7c
x-corebanking-signature: t=1763575200,v1=5f2b…c9e1
```

Corpo:

```json
{
  "event_id": "3b1f9c2e-8d4a-4e7b-9f10-6c2d8e5a1b7c",
  "event_type": "transaction.settled",
  "occurred_at": "2026-11-19T18:00:00.000Z",
  "data": {
    "transactionId": "c0a8…",
    "accountId": "7f0c…",
    "customerId": "e21b…",
    "type": "pix",
    "direction": "outbound",
    "amountCents": "15990",
    "status": "settled",
    "providerRef": "E1234…",
    "counterpartyKeyMasked": "lo***@exemplo.com.br",
    "reason": null,
    "heldFunds": false
  }
}
```

Dados pessoais nunca saem em claro: documentos e chaves Pix chegam mascarados. Use os ids para buscar o detalhe pela API.

## Verificar a assinatura

A assinatura é um HMAC-SHA256, em hexadecimal, de `{t}.{corpo cru}` com o secret do endpoint. Verifique sobre o corpo exatamente como chegou, antes de fazer parse.

Node.js:

```javascript
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verify(secret, rawBody, header, toleranceSeconds = 300) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const t = Number(parts.t);
  if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  const given = Buffer.from(parts.v1 ?? '', 'hex');
  return given.length === 32 && timingSafeEqual(given, Buffer.from(expected, 'hex'));
}
```

Python:

```python
import hmac, hashlib, time

def verify(secret: str, raw_body: bytes, header: str, tolerance: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    t = int(parts.get("t", 0))
    if not t or abs(time.time() - t) > tolerance:
        return False
    msg = f"{t}.".encode() + raw_body
    expected = hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))
```

## Entrega e reentrega

- Responda 2xx rápido e processe depois. Qualquer outra resposta, ou nenhuma em 10 segundos, conta como falha.
- Uma entrega que falhou é tentada de novo por cerca de 24 horas: 10 tentativas, a primeira na hora e as outras 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h, 8 h e 8 h depois da anterior. Um servidor fora do ar por uma tarde recebe tudo quando volta.
- Esgotadas as tentativas, a entrega fica como `dead`. Ela não se perde: reenvie pela API (abaixo) ou peça à instituição, que reenvia pelo painel, em Integração › Entregas.
- A mesma entrega pode chegar mais de uma vez: use `event_id` para descartar duplicadas. Um reenvio leva o mesmo `event_id` e o mesmo corpo.
- `occurred_at` é quando o evento aconteceu, igual em toda tentativa; o `t` da assinatura é o momento do envio.
- A ordem não é garantida. Para o estado atual, consulte a transação pela API.

## Ver o que chegou e reenviar

Cada evento enviado a um endpoint é uma entrega, com a tentativa em que está, o código HTTP que o seu servidor respondeu e o erro. Liste as que esgotaram as tentativas e reenvie quando o seu servidor voltar:

Entregas que falharam:

```bash
curl "https://api.ingot.com.br/webhooks/deliveries?status=dead&endpoint_id=id-do-endpoint" \
  -H "Authorization: ApiKey $CORE_API_KEY"
```

Reenviar uma:

```bash
curl -X POST https://api.ingot.com.br/webhooks/deliveries/id-da-entrega/resend \
  -H "Authorization: ApiKey $CORE_API_KEY"
```

Reenviar todas as que falharam de um endpoint:

```bash
curl -X POST https://api.ingot.com.br/webhooks/endpoints/id-do-endpoint/resend-failed \
  -H "Authorization: ApiKey $CORE_API_KEY"
```

O reenvio de todas vai até 500 por chamada, das mais antigas para as mais novas; quando sobram, a resposta traz `"more": true`. Elas saem algumas por vez, sem atropelar o seu servidor que acabou de voltar.
