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

# Webhooks firmados (HMAC-SHA256)

> Recibe eventos en tiempo real cuando se emite un DTE o cambia su estado ante el SII, con firma criptográfica y reintentos automáticos.

Los webhooks te permiten reaccionar automáticamente cuando un DTE es emitido o cambia de estado ante el SII, sin hacer polling.

## Eventos disponibles

| Evento | Cuándo se dispara |
| - | - |
| `dte.emitido` | Un documento fue emitido y confirmado (incluye folio, montos y URLs de PDF/XML). |
| `dte.estado_actualizado` | El estado SII de un documento cambió (por ejemplo, de `pendiente` a `aceptado` o `rechazado`). |
| `dte.webhook_test` | Evento manual disparado desde `POST /v1/webhooks/{id}/test` para validar tu receptor. |

## Registrar y probar un webhook

**1. Registra tu URL HTTPS**

Llama a `POST /v1/webhooks`. Puedes registrar hasta **5 endpoints activos por modo** (`live` y `test` están aislados). Guarda el campo `secret` (`whsec_...`) inmediatamente: se entrega una sola vez.

```bash theme={null}
curl -X POST https://dte.ia-erp.cl/v1/webhooks \
  -H "Authorization: Bearer sk_test_..." \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tu-tienda.cl/api/webhooks/ia-erp",
    "eventos": ["dte.emitido", "dte.estado_actualizado"],
    "descripcion": "Producción tienda"
  }'
```

**2. Envía un evento de prueba**

Dispara un `dte.webhook_test` firmado para confirmar conectividad y firma antes de salir a producción:

```bash theme={null}
curl -X POST https://dte.ia-erp.cl/v1/webhooks/{id}/test \
  -H "Authorization: Bearer sk_test_..."
```

## Verificar la firma `X-IAERP-Signature`

Cada entrega incluye tres encabezados:

* `X-IAERP-Event`: nombre del evento (`dte.emitido`, `dte.estado_actualizado`, `dte.webhook_test`)
* `X-IAERP-Delivery-ID`: UUID único de la entrega (úsalo para deduplicar en tu receptor)
* `X-IAERP-Signature`: `t=<unix_timestamp>,v1=<hex_hmac_sha256>` donde el mensaje firmado es `<t>.<raw_body>`

```ts TypeScript (SDK @ia-erp/dte) theme={null}
import { verificarFirmaWebhook } from "@ia-erp/dte";

export async function POST(request: Request) {
  const rawBody = await request.text();
  const sig = request.headers.get("X-IAERP-Signature");

  const ok = await verificarFirmaWebhook(rawBody, sig, process.env.IAERP_WEBHOOK_SECRET!);
  if (!ok) return new Response("Firma inválida", { status: 401 });

  const event = JSON.parse(rawBody);
  // Procesa event.evento y event.datos de forma idempotente usando event.id
  return new Response("OK", { status: 200 });
}
```

```python Python (SDK ia-erp-dte) theme={null}
import os
from ia_erp_dte import verificar_firma_webhook

def handle_webhook(raw_body: bytes, signature_header: str | None) -> int:
    if not verificar_firma_webhook(raw_body, signature_header, os.environ["IAERP_WEBHOOK_SECRET"]):
        return 401
    return 200
```

> [!TIP]
>
> Responde con HTTP `2xx` en menos de 8 segundos. Si tu servidor responde `5xx` o hay timeout, IA ERP reintenta automáticamente con backoff exponencial (30 s, 5 min, 30 min y 2 h; hasta 5 intentos).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.