# Webhooks

> Let your system know, instantly and signed, when something happens in your agent

- Page: https://tbit.app/docs/api/webhooks
- Base URL: `https://rest-api.tbit.app/v1`
- Authentication: `X-API-Key` header with your key on every request (the examples read it from the `TBIT_API_KEY` environment variable)

## Overview

A webhook is a URL in your system that TBit sends a signed POST to every time something happens in your agent: an appointment is scheduled, rescheduled or canceled, an order is paid or the AI hands a conversation to the team. That way your calendar, your ERP or your CRM find out without having to ask.

Webhooks are created here with the API, in the app (Plugins › Development › Webhooks) or from the MCP with `manage_webhooks`. All three doors use the same names: `url`, `events`, `description` and `status`. Up to 10 per agent.

## Endpoints

| Method | Path | Description |
| --- | --- | --- |
| `GET` | `/v1/webhooks` | Lists the webhooks, each with its last 5 deliveries |
| `POST` | `/v1/webhooks` | Creates a webhook; returns the secret only once |
| `GET` | `/v1/webhooks/{id}` | A webhook with its last deliveries (?limit= up to 100) |
| `PATCH` | `/v1/webhooks/{id}` | Changes url, events, description or status |
| `DELETE` | `/v1/webhooks/{id}` | Deletes the webhook |
| `POST` | `/v1/webhooks/{id}/test` | Sends a signed webhook.test event right away and returns what your system responded |

## Create a webhook

Fields: `url` (https and public: private IPs, localhost and internal addresses are not accepted), `events` (at least one from the events table) and `description` (optional, up to 200 characters). The response includes `secret`: save it, it is the only time it comes out and with it you verify every delivery.

`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"
  }'
```

Response:

```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)"
  }
}
```

## List and view deliveries

Each webhook includes `recent_deliveries`: the event, the status (`delivered`, `pending` or `failed`), the attempts, the HTTP code your system responded with and how long it took. Deliveries are kept for 30 days.

`GET /v1/webhooks/6b1d2e3f4a5b6c7d8e9f0a2d`

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

Response:

```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
        }
      ]
    }
  }
}
```

## Change, turn off or delete

Send only what changes. `"status": "disabled"` turns the webhook off without deleting it; `"status": "active"` turns it back on and resets the failure count (that is how you reactivate one that TBit turned off).

`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"
```

## Send a test

Sends a `webhook.test` event right away, signed with the webhook secret, even if it is off and even if it is not subscribed to anything, and tells you what your system responded. It does not count as a failure for the automatic shutdown. Limit: 20 per minute.

`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"
```

Response:

```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."
  }
}
```

## Events

| Event | When it fires |
| --- | --- |
| `appointment.created` | An appointment was booked (by the AI, the team in the app, MCP or the API). |
| `appointment.rescheduled` | An appointment changed date or time. Each change is an event. |
| `appointment.cancelled` | An appointment was cancelled (also if they delete it from the connected Google Calendar). |
| `order.paid` | An order was paid. |
| `escalation.created` | The AI handed a conversation to the team (escalation). |
| `webhook.test` | Only with “Send test”. It is not subscribed. |

Bookings of resources that are rented (rooms, halls, vehicles) do not come out yet as `appointment.*`. The new contact event arrives in a future version.

## The envelope

All deliveries have the same shape: `id` (unique per event: use it so you do not process twice), `type`, `created_at` (ISO 8601, UTC), `agent_id` and `data`, with flat fields. Dates go in UTC; a field with no value arrives as `null`.

### appointment.rescheduled

The same fields, with the new time in `start` and `end`.

### escalation.created

`trigger` says who caused it: `cliente` (asked for it), `bot` (the AI left it in the team's hands), `energy_blocked` (TBit did not reply for lack of energy) or `bot_guard` (it looked like an automatic system).

```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 | Value |
| --- | --- |
| `Content-Type` | `application/json` |
| `TBit-Event` | The event type, for example `appointment.created` |
| `TBit-Delivery` | The delivery id. It is the same on every retry of that delivery. |
| `TBit-Signature` | `t=<unix>,v1=<hex>`: the signature, see below |
| `User-Agent` | `TBit-Webhooks/1.0` |

## Verify the signature

TBit signs every delivery with the webhook secret (HMAC-SHA256), Stripe style. The header `TBit-Signature` brings `t` (the unix time of the send) and `v1` (the signature in hex). To verify:

1. Take the RAW body of the request, the exact bytes, without reparsing or reordering the JSON.
2. Build the text `<t>.<cuerpo>` and compute HMAC-SHA256 with your secret (`whsec_…`, complete).
3. Compare with `v1` in constant time. If it does not match, respond 400 and discard.
4. Reject any with `t` more than 5 minutes from your time, so nobody can resend you an old delivery.

```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
```

## Retries and automatic shutdown

A delivery counts as delivered when your system responds 2xx in less than 10 seconds. A 3xx is not followed (it counts as a failure), same as a 4xx, a 5xx, a timeout or a network error. If it fails, TBit retries with this wait:

| Attempt | Wait since the previous one |
| --- | --- |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 6 hours |
| 7 | 24 hours |

After the seventh attempt the delivery is `failed`. If 20 deliveries in a row end up failing, TBit turns off the webhook (`status: disabled`, `disabled_reason: failure_streak`) and sends an email to the agent administrators. To reactivate it, fix your system, check with `POST /v1/webhooks/{id}/test` and send `PATCH {"status": "active"}`. Events that happened while it was off are not sent afterwards.

> **Best practices**
>
> - Respond 2xx as soon as you receive and verify, and process separately: if you take more than 10 seconds, it counts as a failure and is retried.
> - Delivery is at least once: the same event can arrive twice. Deduplicate by `id`.
> - The order is not guaranteed: use `created_at` and, if needed, check the current state.

## Errors

| Code | When |
| --- | --- |
| `400 VALIDATION_ERROR` | URL that is not https, private or internal; unknown event; nothing to change. |
| `404 NOT_FOUND` | The webhook does not exist in this agent. |
| `409 LIMIT_REACHED` | The agent already has 10 webhooks. |
| `429 RATE_LIMITED` | More than 20 tests per minute. |
