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

# Webhooks

> Recibe notificaciones en tiempo real cuando ocurren eventos

Los webhooks te notifican cuando algo relevante ocurre: un tenant completa su activación, los folios están por agotarse, o un certificado está por vencer.

## Agregar endpoint

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST https://api.example.com/api/v1/webhooks/endpoints \
    -H "Authorization: Bearer sk_live_..." \
    -H "Content-Type: application/json" \
    -d '{
      "url": "https://tu-app.com/webhooks/facturacion",
      "filterTypes": [
        "tenant.credentials.updated",
        "folio.low",
        "certificate.expiring"
      ]
    }'
  ```

  ```javascript Node.js theme={null}
  await fetch('https://api.example.com/api/v1/webhooks/endpoints', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk_live_...',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      url: 'https://tu-app.com/webhooks/facturacion',
      filterTypes: [
        'tenant.credentials.updated',
        'folio.low',
        'certificate.expiring',
      ],
    }),
  })
  ```
</CodeGroup>

## Eventos disponibles

| Evento                       | Descripción               | Cuándo se dispara                                               |
| ---------------------------- | ------------------------- | --------------------------------------------------------------- |
| `tenant.credentials.updated` | Credenciales configuradas | Cuando un tenant completa la activación (certificado + API key) |
| `folio.low`                  | Folios bajos              | Cuando el stock de folios baja del umbral configurado           |
| `certificate.expiring`       | Certificado por vencer    | 30 días antes del vencimiento del certificado digital           |
| `dte.status.changed`         | Estado DTE cambiado       | Cuando el SII acepta o rechaza un DTE enviado                   |

## Payload

Cada evento envía un POST con este formato:

```json theme={null}
{
  "event": "tenant.credentials.updated",
  "timestamp": "2024-03-15T14:00:00Z",
  "data": {
    "tenantId": "uuid",
    "apiKey": { "configured": true },
    "certificate": { "configured": true }
  }
}
```

## Verificar firma

Los webhooks incluyen un header `webhook-signature` que puedes verificar con tu signing secret (disponible en el dashboard).

```javascript theme={null}
import crypto from 'crypto'

function verifyWebhook(payload, signature, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('base64')
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  )
}
```

## Reintentos

Los webhooks se entregan con reintentos automáticos (powered by [Svix](https://www.svix.com)):

* 5 intentos con backoff exponencial
* Si tu endpoint responde con status ≥ 400 o timeout (30s), se reintenta
* Puedes ver el historial de entregas en **Logs → Webhooks** del dashboard

## Gestionar endpoints

### Listar

```bash theme={null}
curl https://api.example.com/api/v1/webhooks/endpoints \
  -H "Authorization: Bearer sk_live_..."
```

### Eliminar

```bash theme={null}
curl -X DELETE https://api.example.com/api/v1/webhooks/endpoints/{endpointId} \
  -H "Authorization: Bearer sk_live_..."
```

### Ver mensajes

```bash theme={null}
curl https://api.example.com/api/v1/webhooks/messages?limit=20 \
  -H "Authorization: Bearer sk_live_..."
```
