# वेबहुक

> जब आपके एजेंट में कुछ होता है, तो तुरंत और हस्ताक्षरित रूप से अपने सिस्टम को सूचित करें

- पेज: https://tbit.app/hi/docs/api/webhooks
- Base URL: `https://rest-api.tbit.app/v1`
- ऑथेंटिकेशन: हर request में आपकी key के साथ `X-API-Key` header (उदाहरण इसे `TBIT_API_KEY` environment variable से पढ़ते हैं)

## सामान्य विवरण

वेबहुक आपके सिस्टम का एक URL है, जिस पर TBit हर बार जब आपके एजेंट में कुछ होता है, एक हस्ताक्षरित POST करता है: कोई अपॉइंटमेंट तय होता, बदला जाता या रद्द होता है, कोई ऑर्डर भुगतान होता है या AI कोई बातचीत टीम को सौंपता है। इस तरह आपका कैलेंडर, आपका ERP या आपका CRM बिना पूछे ही जान जाता है।

वेबहुक यहाँ API से, ऐप में (Plugins › Desarrollo › Webhooks) या MCP से `manage_webhooks` के साथ बनाए जाते हैं। तीनों रास्ते एक ही नाम इस्तेमाल करते हैं: `url`, `events`, `description` और `status`। प्रति एजेंट अधिकतम 10।

## एंडपॉइंट

| मेथड | रूट | विवरण |
| --- | --- | --- |
| `GET` | `/v1/webhooks` | वेबहुक की सूची, हर एक के साथ उसके अंतिम 5 डिलीवरी |
| `POST` | `/v1/webhooks` | एक वेबहुक बनाएँ; सीक्रेट केवल एक बार लौटाता है |
| `GET` | `/v1/webhooks/{id}` | एक वेबहुक और उसकी अंतिम डिलीवरी (?limit= 100 तक) |
| `PATCH` | `/v1/webhooks/{id}` | url, events, description या status बदलें |
| `DELETE` | `/v1/webhooks/{id}` | वेबहुक हटाएँ |
| `POST` | `/v1/webhooks/{id}/test` | अभी एक हस्ताक्षरित webhook.test इवेंट भेजें और बताएं कि आपके सिस्टम ने क्या जवाब दिया |

## एक वेबहुक बनाएँ

फ़ील्ड: `url` (https और सार्वजनिक: निजी IP, localhost या आंतरिक पते स्वीकार नहीं किए जाते), `events` (इवेंट तालिका में से कम से कम एक) और `description` (वैकल्पिक, 200 अक्षरों तक)। प्रतिक्रिया में `secret` आता है: इसे सहेजें, यह केवल एक बार निकलता है और इसी से आप हर डिलीवरी सत्यापित करते हैं।

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

## डिलीवरी की सूची और देखें

हर वेबहुक में `recent_deliveries` आता है: इवेंट, स्थिति (`delivered`, `pending` या `failed`), प्रयास, आपके सिस्टम द्वारा दिया गया HTTP कोड और कितना समय लगा। डिलीवरी 30 दिनों तक सहेजी जाती हैं।

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

## बदलें, बंद करें या हटाएँ

केवल वही भेजें जो बदलता है। `"status": "disabled"` वेबहुक को हटाए बिना बंद करता है; `"status": "active"` इसे फिर से चालू करता है और विफलता की गिनती शून्य करता है (इस तरह TBit द्वारा बंद किया गया एक वेबहुक फिर से सक्रिय होता है)।

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

## एक परीक्षण भेजें

तुरंत एक `webhook.test` इवेंट वेबहुक के सीक्रेट से हस्ताक्षरित भेजता है, भले ही वह बंद हो और भले ही वह किसी चीज़ की सदस्यता न ले, और बताता है कि आपके सिस्टम ने क्या जवाब दिया। यह स्वचालित बंद करने के लिए विफलता के रूप में नहीं गिना जाता। सीमा: प्रति मिनट 20।

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

## इवेंट

| इवेंट | कब निकलता है |
| --- | --- |
| `appointment.created` | एक अपॉइंटमेंट तय हुआ (AI, ऐप में टीम, MCP या API द्वारा)। |
| `appointment.rescheduled` | एक अपॉइंटमेंट की तारीख या समय बदला। हर बदलाव एक इवेंट है। |
| `appointment.cancelled` | एक अपॉइंटमेंट रद्द हुआ (जुड़े Google Calendar से हटाने पर भी)। |
| `order.paid` | एक ऑर्डर का भुगतान हो गया। |
| `escalation.created` | AI ने एक बातचीत टीम को सौंप दी (एस्केलेशन)। |
| `webhook.test` | केवल «Enviar prueba» के साथ। सब्सक्राइब नहीं होता। |

किराए पर दिए जाने वाले संसाधनों (कमरे, हॉल, वाहन) की बुकिंग अभी `appointment.*` के रूप में नहीं निकलती। नए संपर्क का इवेंट अगले संस्करण में आएगा।

## लिफ़ाफ़ा

सभी डिलीवरी का एक ही रूप है: `id` (प्रति इवेंट अद्वितीय: इसे दो बार प्रोसेस न करने के लिए उपयोग करें), `type`, `created_at` (ISO 8601, UTC), `agent_id` और `data`, सपाट फ़ील्ड के साथ। तारीखें UTC में होती हैं; बिना मान वाला फ़ील्ड `null`.

### appointment.rescheduled

वही फ़ील्ड, नए समय के साथ `start` और `end`.

### escalation.created

`trigger` बताता है कि इसे किसने शुरू किया: `cliente` (उसने माँगा), `bot` (AI ने इसे टीम के हाथ में छोड़ दिया), `energy_blocked` (ऊर्जा की कमी से TBit ने जवाब नहीं दिया) या `bot_guard` (यह स्वचालित सिस्टम जैसा लगा)।

```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 | मान |
| --- | --- |
| `Content-Type` | `application/json` |
| `TBit-Event` | इवेंट का प्रकार, उदाहरण के लिए `appointment.created` |
| `TBit-Delivery` | डिलीवरी की id। उस डिलीवरी के हर पुनःप्रयास में यह वही रहती है। |
| `TBit-Signature` | `t=<unix>,v1=<hex>`: हस्ताक्षर, नीचे देखें |
| `User-Agent` | `TBit-Webhooks/1.0` |

## हस्ताक्षर सत्यापित करें

TBit हर डिलीवरी पर webhook के सीक्रेट से हस्ताक्षर करता है (HMAC-SHA256), Stripe की शैली में। Header `TBit-Signature` में `t` (भेजने का unix समय) और `v1` (hex में हस्ताक्षर) होता है। सत्यापित करने के लिए:

1. request का RAW body लें, सटीक bytes, JSON को दोबारा parse या reorder किए बिना।
2. टेक्स्ट बनाएं `<t>.<cuerpo>` और अपने secret से HMAC-SHA256 निकालें (`whsec_…`, पूरा)।
3. इससे तुलना करें `v1` constant time में। अगर मेल न खाए, 400 लौटाएं और छोड़ दें।
4. उन्हें अस्वीकार करें जिनमें `t` आपके समय से 5 मिनट से ज़्यादा दूर हो, ताकि कोई पुरानी 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
```

## फिर से कोशिश और अपने आप बंद होना

एक delivery तब delivered मानी जाती है जब आपका सिस्टम 10 सेकंड से कम में 2xx लौटाए। 3xx का पीछा नहीं किया जाता (यह failure माना जाता है), 4xx, 5xx, timeout या network error की तरह। अगर fail हो, TBit इस इंतज़ार के साथ फिर कोशिश करता है:

| कोशिश | पिछली से इंतज़ार |
| --- | --- |
| 2 | 1 मिनट |
| 3 | 5 मिनट |
| 4 | 30 मिनट |
| 5 | 2 घंटे |
| 6 | 6 घंटे |
| 7 | 24 घंटे |

सातवीं कोशिश के बाद delivery `failed` हो जाती है। अगर लगातार 20 deliveries fail होती हैं, TBit webhook बंद कर देता है (`status: disabled`, `disabled_reason: failure_streak`) और agent के administrators को ईमेल भेजता है। इसे फिर चालू करने के लिए, अपना सिस्टम ठीक करें, `POST /v1/webhooks/{id}/test` से जाँचें और भेजें `PATCH {"status": "active"}`। बंद रहने के दौरान हुए events बाद में नहीं भेजे जाते।

> **अच्छे तरीके**
>
> - जैसे ही receive और verify करें 2xx लौटाएं, और अलग से process करें: अगर 10 सेकंड से ज़्यादा लगे, failure माना जाता है और फिर कोशिश होती है।
> - Delivery कम से कम एक बार होती है: वही event दो बार आ सकता है। इससे deduplicate करें `id`.
> - क्रम की गारंटी नहीं है: उपयोग करें `created_at` और, अगर ज़रूरत हो, मौजूदा स्थिति देखें।

## त्रुटियाँ

| कोड | कब |
| --- | --- |
| `400 VALIDATION_ERROR` | URL जो https नहीं, private या internal है; अज्ञात event; बदलने के लिए कुछ नहीं। |
| `404 NOT_FOUND` | इस agent में webhook मौजूद नहीं है। |
| `409 LIMIT_REACHED` | agent के पास पहले से 10 webhooks हैं। |
| `429 RATE_LIMITED` | प्रति मिनट 20 से ज़्यादा परीक्षण। |
