# Webhooks (referencia)

Se crean en el panel (Mi empresa → Webhooks) o con `POST /v1/webhooks { url, events, mode? }` (scope `webhooks:manage`) → `{ webhook, secret }`. El secreto `whsec_…` se ve una vez. `POST /v1/webhooks/:id/test` manda un `ping`. `POST /v1/webhooks/:id/rotate` rota el secreto.

## Petición
Cabeceras: `Remolom-Signature: t=<unix>,v1=<hex>`, `Remolom-Event: <type>`, `Remolom-Delivery: <id>`. Cuerpo `{ id, type, createdAt, test, data }`.

Tipos: `event.created`, `event.updated`, `event.cancelled`, `event.hidden` (`data = { event: EventDTO }`); `ticket.sold`, `ticket.refunded`, `ticket.transferred`, `ticket.checked_in` (`data = { eventId, orderId, tickets: [{ id, priceId, priceName, holderName, checkedInAt, gate, transferredAt, voidedAt, createdAt }] }`, sin emails); `ping` (`{ message, webhookId }`).

Reintentos tras fallo (no 2xx en 10 s, o redirección): 1 min, 5 min, 30 min, 2 h, 6 h, 12 h. Tras 3 días fallando, el endpoint se desactiva. Orden no garantizado. Deduplicar por `id`.

## Verificar (Node)
```js
import { createHmac, timingSafeEqual } from 'node:crypto'
function verify(secret, rawBody, header) {
  const { t, v1 } = Object.fromEntries(header.split(',').map((p) => p.split('=')))
  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex')
  const ok = v1?.length === expected.length && timingSafeEqual(Buffer.from(v1), Buffer.from(expected))
  return ok && Math.abs(Date.now() / 1000 - Number(t)) < 300
}
// Express: app.post('/hook', express.raw({ type: 'application/json' }), (req, res) => verify(SECRET, req.body.toString('utf8'), req.get('Remolom-Signature') ?? '') ? res.sendStatus(200) : res.sendStatus(400))
```

## Verificar (Python)
```python
import hmac, hashlib, time
def verify(secret: str, raw_body: bytes, header: str) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    expected = hmac.new(secret.encode(), f"{parts['t']}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", "")) and abs(time.time() - int(parts["t"])) < 300
```

## Verificar (PHP)
```php
function verify(string $secret, string $rawBody, string $header): bool {
  parse_str(str_replace(',', '&', $header), $p);
  $expected = hash_hmac('sha256', $p['t'] . '.' . $rawBody, $secret);
  return hash_equals($expected, $p['v1'] ?? '') && abs(time() - (int) $p['t']) < 300;
}
// $raw = file_get_contents('php://input'); $_SERVER['HTTP_REMOLOM_SIGNATURE']
```

Errores típicos: firmar `JSON.stringify(req.body)` en vez del cuerpo crudo; usar el secreto de otro webhook o uno ya rotado; reloj del servidor desfasado (> 5 min).
