# Webhooks

> Avísale a tu sistema, al instante y firmado, cuando pasa algo en tu agente

- Página: https://tbit.app/es/docs/api/webhooks
- URL base: `https://rest-api.tbit.app/v1`
- Autenticación: encabezado `X-API-Key` con tu clave en cada solicitud (los ejemplos la leen de la variable de entorno `TBIT_API_KEY`)

## Descripción general

Un webhook es una URL de tu sistema a la que TBit le hace un POST firmado cada vez que pasa algo en tu agente: se agenda, reagenda o cancela una cita, se paga un pedido o la IA le pasa una conversación al equipo. Así tu agenda, tu ERP o tu CRM se enteran sin tener que preguntar.

Los webhooks se crean aquí con la API, en la app (Plugins › Desarrollo › Webhooks) o desde el MCP con `manage_webhooks`. Las tres puertas usan los mismos nombres: `url`, `events`, `description` y `status`. Hasta 10 por agente.

## Endpoints

| Método | Ruta | Descripción |
| --- | --- | --- |
| `GET` | `/v1/webhooks` | Lista los webhooks, cada uno con sus últimas 5 entregas |
| `POST` | `/v1/webhooks` | Crea un webhook; devuelve el secreto una sola vez |
| `GET` | `/v1/webhooks/{id}` | Un webhook con sus últimas entregas (?limit= hasta 100) |
| `PATCH` | `/v1/webhooks/{id}` | Cambia url, events, description o status |
| `DELETE` | `/v1/webhooks/{id}` | Borra el webhook |
| `POST` | `/v1/webhooks/{id}/test` | Manda ya un evento webhook.test firmado y devuelve qué respondió tu sistema |

## Crear un webhook

Campos: `url` (https y pública: no se aceptan IPs privadas, localhost ni direcciones internas), `events` (al menos uno de la tabla de eventos) y `description` (opcional, hasta 200 caracteres). La respuesta trae `secret`: guárdalo, es la única vez que sale y con él verificas cada entrega.

`POST /v1/webhooks`

```bash
curl -X POST "https://rest-api.tbit.app/v1/webhooks" \
  -H "X-API-Key: $TBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tu-sistema.com/webhooks/tbit",
    "events": [
      "appointment.created",
      "appointment.cancelled"
    ],
    "description": "Agenda del consultorio"
  }'
```

Respuesta:

```json
{
  "data": {
    "webhook": {
      "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
      "url": "https://tu-sistema.com/webhooks/tbit",
      "events": [
        "appointment.created",
        "appointment.cancelled"
      ],
      "description": "Agenda del consultorio",
      "status": "active",
      "disabled_reason": null,
      "failure_streak": 0,
      "last_delivery_at": null,
      "created_at": "2026-11-19T15:00:00.000Z"
    },
    "secret": "whsec_9c1f…(64 caracteres hex)"
  }
}
```

## Listar y ver las entregas

Cada webhook trae `recent_deliveries`: el evento, el estado (`delivered`, `pending` o `failed`), los intentos, el código HTTP que respondió tu sistema y cuánto tardó. Las entregas se guardan 30 días.

`GET /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d?limit=20" \
  -H "X-API-Key: $TBIT_API_KEY"
```

Respuesta:

```json
{
  "data": {
    "webhook": {
      "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
      "url": "https://tu-sistema.com/webhooks/tbit",
      "events": [
        "appointment.created"
      ],
      "status": "active",
      "failure_streak": 0,
      "recent_deliveries": [
        {
          "delivery_id": "6b1d2e3f4a5b6c7d8e9f0a3e",
          "event_id": "evt_3f1c9a7e2b6d4c58a0e1f2b3c4d5e6f7",
          "type": "appointment.created",
          "status": "delivered",
          "attempts": 1,
          "http_status": 200,
          "duration_ms": 184,
          "error": null,
          "created_at": "2026-11-19T15:02:11.000Z",
          "delivered_at": "2026-11-19T15:02:31.000Z",
          "next_attempt_at": null
        }
      ]
    }
  }
}
```

## Cambiar, apagar o borrar

Manda solo lo que cambia. `"status": "disabled"` apaga el webhook sin borrarlo; `"status": "active"` lo vuelve a encender y pone en cero la cuenta de fallas (así se reactiva uno que TBit apagó).

`PATCH /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl -X PATCH "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d" \
  -H "X-API-Key: $TBIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      "appointment.created",
      "order.paid"
    ],
    "status": "active"
  }'
```

`DELETE /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

```bash
curl -X DELETE "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d" \
  -H "X-API-Key: $TBIT_API_KEY"
```

## Enviar una prueba

Manda en el acto un evento `webhook.test` firmado con el secreto del webhook, aunque esté apagado y aunque no esté suscrito a nada, y te dice qué respondió tu sistema. No cuenta como falla para el apagado automático. Límite: 20 por minuto.

`POST /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test`

```bash
curl -X POST "https://rest-api.tbit.app/v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d/test" \
  -H "X-API-Key: $TBIT_API_KEY"
```

Respuesta:

```json
{
  "data": {
    "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
    "delivery_id": "6b1d2e3f4a5b6c7d8e9f0a4f",
    "event_id": "evt_0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d",
    "ok": true,
    "http_status": 200,
    "duration_ms": 212,
    "error": null,
    "response": "ok",
    "receipt": "Tu sistema respondió 200 en 212 ms. La firma viaja en TBit-Signature."
  }
}
```

## Eventos

| Evento | Cuándo sale |
| --- | --- |
| `appointment.created` | Se agendó una cita (la IA, el equipo en la app, el MCP o la API). |
| `appointment.rescheduled` | Una cita cambió de fecha u hora. Cada cambio es un evento. |
| `appointment.cancelled` | Se canceló una cita (también si la borran del Google Calendar conectado). |
| `order.paid` | Un pedido quedó pagado. |
| `escalation.created` | La IA le pasó una conversación al equipo (escalamiento). |
| `webhook.test` | Solo con «Enviar prueba». No se suscribe. |

Las reservas de recursos que se rentan (habitaciones, salones, vehículos) todavía no salen como `appointment.*`. El evento de contacto nuevo llega en una próxima versión.

## El sobre

Todas las entregas tienen la misma forma: `id` (único por evento: úsalo para no procesar dos veces), `type`, `created_at` (ISO 8601, UTC), `agent_id` y `data`, con campos planos. Las fechas van en UTC; un campo sin valor llega en `null`.

### appointment.rescheduled

Los mismos campos, con la hora nueva en `start` y `end`.

### escalation.created

`trigger` dice quién lo provocó: `cliente` (lo pidió), `bot` (la IA lo dejó en manos del equipo), `energy_blocked` (TBit no respondió por falta de energía) o `bot_guard` (parecía un sistema automático).

```json
{
  "id": "evt_3f1c9a7e2b6d4c58a0e1f2b3c4d5e6f7",
  "type": "appointment.created",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-21T14:00:00.000Z",
    "end": "2026-11-21T14:45:00.000Z",
    "status": "CONFIRMED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_8a2b0c4d6e8f0a1b2c3d4e5f6a7b8c9d",
  "type": "appointment.rescheduled",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-22T16:00:00.000Z",
    "end": "2026-11-22T16:45:00.000Z",
    "status": "CONFIRMED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5",
  "type": "appointment.cancelled",
  "created_at": "2026-11-19T15:02:11.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "appointment_id": "6b1d2e3f4a5b6c7d8e9f0a1b",
    "service_id": "6af9a1b2c3d4e5f6a7b8c9d0",
    "service_name": "Limpieza dental",
    "collaborator_id": "6af9a1b2c3d4e5f6a7b8c9d1",
    "collaborator_name": "Geral Díaz",
    "start": "2026-11-21T14:00:00.000Z",
    "end": "2026-11-21T14:45:00.000Z",
    "status": "CANCELLED",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null,
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c"
  }
}
```

```json
{
  "id": "evt_5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b",
  "type": "order.paid",
  "created_at": "2026-11-19T15:10:42.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "order_id": "6b1d2e3f4a5b6c7d8e9f0a1c",
    "status": "PAID",
    "total": 180000,
    "currency": "COP",
    "payment_method": "wompi",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "external_id": null
  }
}
```

```json
{
  "id": "evt_9f8e7d6c5b4a39281706f5e4d3c2b1a0",
  "type": "escalation.created",
  "created_at": "2026-11-19T15:20:03.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "trigger": "cliente",
    "contact_id": "6ac9f1e6af6d42a269f21b15",
    "contact_name": "Ana Gómez",
    "phone": "+573001234567",
    "reason": "Pide hablar con una persona sobre un cobro",
    "message": "¿Me puede atender alguien? Me cobraron dos veces"
  }
}
```

```json
{
  "id": "evt_0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d",
  "type": "webhook.test",
  "created_at": "2026-11-19T15:00:00.000Z",
  "agent_id": "66a54f2f2281f02197cb21bd",
  "data": {
    "webhook_id": "6b1d2e3f4a5b6c7d8e9f0a2d",
    "message": "Prueba de TBit: si ves esto, tu endpoint recibe y puede verificar la firma."
  }
}
```

## Headers

| Header | Valor |
| --- | --- |
| `Content-Type` | `application/json` |
| `TBit-Event` | El tipo de evento, por ejemplo `appointment.created` |
| `TBit-Delivery` | El id de la entrega. Es el mismo en cada reintento de esa entrega. |
| `TBit-Signature` | `t=<unix>,v1=<hex>`: la firma, ver abajo |
| `User-Agent` | `TBit-Webhooks/1.0` |

## Verificar la firma

TBit firma cada entrega con el secreto del webhook (HMAC-SHA256), al estilo de Stripe. El header `TBit-Signature` trae `t` (la hora unix del envío) y `v1` (la firma en hex). Para verificar:

1. Toma el cuerpo CRUDO de la petición, los bytes exactos, sin reparsear ni reordenar el JSON.
2. Arma el texto `<t>.<cuerpo>` y calcula HMAC-SHA256 con tu secreto (`whsec_…`, completo).
3. Compara con `v1` en tiempo constante. Si no coincide, responde 400 y descarta.
4. Rechaza las que tengan `t` a más de 5 minutos de tu hora, para que nadie te reenvíe una entrega vieja.

```javascript
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.TBIT_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 300;

function verify(rawBody, header) {
  const parts = Object.fromEntries(
    (header || "").split(",").map((p) => p.split("=").map((s) => s.trim())),
  );
  const t = Number(parts.t);
  const v1 = parts.v1;
  if (!t || !v1) return false;
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;
  const expected = crypto
    .createHmac("sha256", SECRET)
    .update(`${t}.${rawBody}`, "utf8")
    .digest("hex");
  return (
    expected.length === v1.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1))
  );
}

const app = express();
// El cuerpo CRUDO: la firma es sobre los bytes exactos, no sobre el JSON reparseado.
app.post("/webhooks/tbit", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verify(raw, req.get("TBit-Signature"))) return res.sendStatus(400);
  const event = JSON.parse(raw);
  // Responde rápido y procesa aparte; deduplica por event.id.
  res.sendStatus(200);
  console.log(event.type, event.data);
});

app.listen(3000);
```

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["TBIT_WEBHOOK_SECRET"]  # whsec_…
TOLERANCE_SECONDS = 300

app = Flask(__name__)


def verify(raw_body: bytes, header: str) -> bool:
    parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        t = int(parts["t"])
        v1 = parts["v1"]
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > TOLERANCE_SECONDS:
        return False
    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(SECRET.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)


@app.post("/webhooks/tbit")
def tbit_webhook():
    raw = request.get_data()  # los bytes exactos que firmó TBit
    if not verify(raw, request.headers.get("TBit-Signature", "")):
        abort(400)
    event = json.loads(raw)
    # Responde rápido y procesa aparte; deduplica por event["id"].
    print(event["type"], event["data"])
    return "", 200
```

## Reintentos y apagado automático

Una entrega cuenta como entregada cuando tu sistema responde 2xx en menos de 10 segundos. Un 3xx no se sigue (cuenta como falla), igual que un 4xx, un 5xx, un timeout o un error de red. Si falla, TBit reintenta con esta espera:

| Intento | Espera desde el anterior |
| --- | --- |
| 2 | 1 minuto |
| 3 | 5 minutos |
| 4 | 30 minutos |
| 5 | 2 horas |
| 6 | 6 horas |
| 7 | 24 horas |

Después del séptimo intento la entrega queda `failed`. Si 20 entregas seguidas terminan fallidas, TBit apaga el webhook (`status: disabled`, `disabled_reason: failure_streak`) y les escribe un correo a los administradores del agente. Para reactivarlo, arregla tu sistema, comprueba con `POST /v1/webhooks/{id}/test` y manda `PATCH {"status": "active"}`. Los eventos que pasaron mientras estuvo apagado no se mandan después.

> **Buenas prácticas**
>
> - Responde 2xx apenas recibas y verifiques, y procesa aparte: si tardas más de 10 segundos, cuenta como falla y se reintenta.
> - La entrega es al menos una vez: el mismo evento puede llegar dos veces. Deduplica por `id`.
> - El orden no está garantizado: usa `created_at` y, si hace falta, consulta el estado actual.

## Errores

| Código | Cuándo |
| --- | --- |
| `400 VALIDATION_ERROR` | URL que no es https, privada o interna; evento desconocido; nada que cambiar. |
| `404 NOT_FOUND` | El webhook no existe en este agente. |
| `409 LIMIT_REACHED` | El agente ya tiene 10 webhooks. |
| `429 RATE_LIMITED` | Más de 20 pruebas por minuto. |
