Webhooks

Registre um endpoint HTTPS. Aporta entrega eventos com assinatura HMAC e retries com backoff.

Registrar

curl -s https://api.aporta.cc/v1/webhooks/create \
  -H "Authorization: Bearer sk_test_…" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://sua-api.com/webhooks/aporta",
    "events": ["checkout.completed", "checkout.refunded"]
  }'
  • URL deve ser https://, porta 443 ou 8443, num host público da internet. Endereços internos (loopback, redes privadas, link-local, *.internal) são recusados ao salvar e de novo a cada entrega.
  • Resposta inclui secret whsec_… (guarde-o): só o create e o rotate-secret mostram o secret inteiro; list, get e update devolvem mascarado
  • Catálogo: GET /v1/webhooks/events (público)

Verificar X-Aporta-Signature

Cada entrega inclui o header X-Aporta-Signature: t=<unix>,v1=<hex>. O valor v1 é HMAC-SHA256 (hex) de `${t}.${rawBody}` usando o secret whsec_… do endpoint. Use o body bruto (string), não o JSON re-serializado. Rejeite assinaturas com skew > 5 minutos.

  • Header: X-Aporta-Signature: t=<unix>,v1=<hex>
  • Payload assinado: `${t}.${rawBody}`
  • Algoritmo: HMAC-SHA256 com o secret whsec_…
  • Timeout de entrega: 30s · User-Agent Aporta-Webhooks/0.1

Payload de exemplo

{
  "id": "evt_01JABC…",
  "event": "checkout.completed",
  "apiVersion": 1,
  "devMode": true,
  "createdAt": "2026-10-03T15:04:05.000Z",
  "data": {
    "checkout": {
      "id": "chk_01JXYZ…",
      "amount": 1000,
      "status": "PAID",
      "methods": ["PIX"],
      "paidAt": "2026-10-03T15:04:04.000Z",
      "url": "https://aporta.cc/c/chk_01JXYZ…"
    }
  }
}

O body assinado é exatamente esse JSON (sem espaços extras além dos gerados pelo servidor). Trate id do evento como chave de idempotência.

Receita de teste (Node)

import { createHmac } from "node:crypto";
import { verifyWebhook } from "@aporta/sdk";

// 1) Simular assinatura localmente
const secret = "whsec_seu_secret";
const rawBody = JSON.stringify({
  id: "evt_test",
  event: "checkout.completed",
  apiVersion: 1,
  devMode: true,
  createdAt: new Date().toISOString(),
  data: { checkout: { id: "chk_test", amount: 1000, status: "PAID" } },
});
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", secret)
  .update(`${t}.${rawBody}`, "utf8")
  .digest("hex");
const header = `t=${t},v1=${v1}`;

// 2) Verificar (igual ao seu endpoint)
const event = verifyWebhook(secret, rawBody, header);
console.log(event.event); // checkout.completed

// 3) Ou com curl + header real após um pagamento sandbox:
// curl -i https://sua-api.com/webhooks/aporta \
//   -H "Content-Type: application/json" \
//   -H "X-Aporta-Signature: t=…,v1=…" \
//   -d @payload.json

Receita rápida (curl + openssl)

BODY='{"id":"evt_test","event":"checkout.completed","apiVersion":1,"devMode":true,"createdAt":"2026-10-03T12:00:00.000Z","data":{}}'
T=$(date +%s)
V1=$(printf '%s' "$T.$BODY" | openssl dgst -sha256 -hmac "whsec_seu_secret" | awk '{print $2}')
echo "X-Aporta-Signature: t=$T,v1=$V1"

curl -s https://sua-api.com/webhooks/aporta \
  -H "Content-Type: application/json" \
  -H "X-Aporta-Signature: t=$T,v1=$V1" \
  -d "$BODY"

SDK verify

import { Aporta, verifyWebhook } from "@aporta/sdk";

const event = verifyWebhook(
  whsec,
  rawBody,
  req.headers.get("x-aporta-signature")!,
);
// ou: Aporta({ secret }).webhooks.verify(whsec, rawBody, header)

Retries & backoff

Até 5 tentativas por delivery (índice 0 = imediato):

  • Agenda padrão: 0 → 5s → 30s → 2m → 10m
  • Retry em: HTTP 5xx, 408, 429, ou erro de rede/timeout
  • Sem retry em outros 4xx (exceto 408/429) nem em 3xx: redirects não são seguidos
  • Erro de rede aparece só como Delivery failed; destino que passou a apontar para endereço interno fica Destination not allowed
  • 410 Gone → endpoint desabilitado (disabledAt), sem novas entregas
  • Status da delivery: pending · success · failed · abandoned
  • Reenvio manual: POST /v1/checkouts/resend-webhook (por checkout) ou POST /v1/webhooks/redeliver { deliveryId }

Poller in-process (sem Redis no MVP). Em multi-machine pode haver double-delivery — use o id do evento de forma idempotente.

Eventos

  • Checkout: checkout.completed · refunded · expired · disputed
  • Transparent: transparent.completed · refunded · disputed
  • Subscription: completed · cancelled · plan_changed · renewed · trial_started
  • Payout / transfer / crypto: payout.* · transfer.* · crypto.receive.completed · crypto.send.*

Lista completa: GET /v1/webhooks/events.

Veja também erros e checkouts.