# Webhooks

A webhook is an address on your system that we call when something happens in your organisation. Instead of asking the API again and again, you wait for us to tell you.

There are two kinds of delivery:

- **Signed events**: signed with your webhook's own secret, retried when your system is down, and logged so you can see and replay every delivery.
- **The original monthly usage webhook** (`monthly_location_usage`): sent once, unsigned, with its original body. It is kept exactly as it was, so existing integrations keep working.

## Events you can subscribe to

| Event | Signed | When it is sent | What `data` contains |
|---|---|---|---|
| `webhook.test` | Yes | Only when you send a test event. Never sent by itself. | A `message` and the `webhook` (`id`, `name`). |
| `monthly_location_usage` | No (original) | After each monthly subscription payment, once per active building with entrances. | Not wrapped: the body is the site (`location`), the `building` and its usage as `items` (see below). |

More signed events are on the way: doors opened or refused, intercom calls, people added or changed, alarms, devices going offline and more. They will appear in the event list below as soon as they are live.

**The always up-to-date list** is in the API: `GET /api/webhooks/event-types` returns every event with its `type`, `version`, `group`, `title`, `description`, whether it is `signed` (or `legacy`), and a `sample` of its `data`.

```bash
curl https://go.thebuilding.cloud/api/webhooks/event-types \
  -H "Authorization: Bearer $TBC_KEY" \
  -H "Accept: application/json"
```

## Set one up

**In the dashboard** (Organisation account): open your **Profile**, choose **Webhooks**, add the address, choose the event and save. **Test Webhook** sends a sample delivery straight away and shows what we sent and what your system answered. The page offers the original monthly usage event today; picking signed events, the secret and the delivery log are coming to the page next. Until then, use the API for them.

**With the API**: create the webhook with `POST /api/webhooks`. Send `events` as a list of event types (a comma list still works):

```bash
curl -X POST https://go.thebuilding.cloud/api/webhooks \
  -H "Authorization: Bearer $TBC_KEY" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{"name": "My endpoint", "url": "https://example.com/tbc/webhook", "events": ["webhook.test"], "status": 1}'
```

The answer contains `signing_secret` (it starts with `whsec_`). **Copy it now: it is shown only this once.** Store it like a password, in your server's settings, never in a web page or an app.

Change the events later with `PUT /api/webhooks/{id}`. See **Webhook** in the [API reference](https://go.thebuilding.cloud/developers/reference) for every endpoint.

## What a signed delivery looks like

We send a `POST` with a JSON body. The body has the same shape for every event:

```http
POST /tbc/webhook HTTP/1.1
Content-Type: application/json
User-Agent: TheBuilding.Cloud-Webhooks/1.0
X-TBC-Event: webhook.test
X-TBC-Event-Id: evt_01jc8z6m4q7x2v9k3b5n8r1t0w
X-TBC-Delivery: dlv_01jc8z6m5a3d7f9h2k4m6p8r0s
X-TBC-Attempt: 1
X-TBC-Signature: t=1762531200,v1=5f2b…c9e1

{
  "id": "evt_01jc8z6m4q7x2v9k3b5n8r1t0w",
  "type": "webhook.test",
  "version": 1,
  "created_at": "2026-11-07T16:00:00Z",
  "organization_id": 42,
  "test": true,
  "data": {
    "message": "This is a test event from TheBuilding.Cloud.",
    "webhook": { "id": 12, "name": "My endpoint" }
  }
}
```

| Header | Meaning |
|---|---|
| `X-TBC-Event` | The event type. |
| `X-TBC-Event-Id` | The event's id, the same as `id` in the body. It stays the same on retries and replays: use it to ignore an event you have already handled. |
| `X-TBC-Delivery` | This delivery's id (`dlv_…`), as shown in the delivery log. |
| `X-TBC-Attempt` | 1 for the first try, 2 for the first retry, and so on. |
| `X-TBC-Signature` | The time we signed it (`t`) and one or more signatures (`v1`). |

`version` goes up only when an event's `data` changes in a way that could break your code. New fields can be added at any time, so ignore fields you don't know. Event data never contains PIN codes, passwords, keys, tokens or card numbers; people appear as an id and a name.

Answer with any `2xx` status within a few seconds and do the real work afterwards. We keep only your status code, never the body of your answer.

## Check the signature

Every signed delivery is signed with your webhook's secret: `v1` is the HMAC-SHA256 (hex) of the timestamp, a full stop and the raw body, exactly as received.

1. Read `t` and every `v1` from `X-TBC-Signature`.
2. Refuse the delivery if `t` is more than 5 minutes away from your clock.
3. Work out `HMAC-SHA256(secret, t + "." + raw body)` and compare it with each `v1` using a constant-time compare. Accept the delivery if one matches.

Use the raw body: parsing the JSON and encoding it again changes the bytes and the signature will not match.

In PHP:

```php
function tbcSignatureIsValid(string $secret, string $header, string $rawBody): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't' && ctype_digit($value)) {
            $t = (int) $value;
        } elseif ($key === 'v1') {
            $signatures[] = $value;
        }
    }
    if ($t === null || abs(time() - $t) > 300) {
        return false;
    }
    $expected = hash_hmac('sha256', $t.'.'.$rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

$ok = tbcSignatureIsValid(getenv('TBC_WEBHOOK_SECRET'), $_SERVER['HTTP_X_TBC_SIGNATURE'] ?? '', file_get_contents('php://input'));
```

In Node.js (Express):

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

const app = express();

app.post("/tbc/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("X-TBC-Signature") || "";
  const parts = header.split(",").map((p) => p.trim().split("="));
  const t = Number(parts.find(([k]) => k === "t")?.[1]);
  const signatures = parts.filter(([k]) => k === "v1").map(([, v]) => v);
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) return res.sendStatus(400);

  const expected = crypto.createHmac("sha256", process.env.TBC_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`).digest("hex");
  const ok = signatures.some((s) => s.length === expected.length
    && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
  if (!ok) return res.sendStatus(400);

  res.sendStatus(200); // answer first, then handle JSON.parse(req.body)
});
```

## Rotate the secret

`POST /api/webhooks/{id}/rotate-secret` makes a new secret and answers with it once (`signing_secret`; it is never shown again). For the next 24 hours every delivery carries two `v1` signatures, one made with the new secret and one with the old, so you can switch your server to the new secret without missing an event. `previous_secret_valid_until` in the answer says when the old one stops.

Webhooks made before signing existed get a secret on their first signed delivery: rotate it to see it.

## Retries, failures and Resume

- When your system answers `2xx`, the delivery has **succeeded**.
- When it times out, can't be reached, or answers `5xx` or `429`, we try again after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours. If the last try fails too, the delivery has **failed**.
- Any other answer (for example `400` or `404`) fails at once and is not retried.
- After 15 failed deliveries in a row the webhook is **paused**: nothing is sent and new events wait. The organisation gets a notice in the dashboard bell.
- When your system works again, press **Resume**: `POST /api/webhooks/{id}/resume`. The deliveries that were waiting are sent and the failure count starts again from zero.

Your system should cope with the same event arriving twice (for example after a timeout where your system did get it): use `X-TBC-Event-Id`.

## Delivery log and replay

Every delivery is kept for 30 days.

- `GET /api/webhooks/{id}/deliveries` lists one webhook's deliveries, newest first, 20 a page. Filter with `?status=pending`, `sending`, `retrying`, `succeeded` or `failed`. Each row shows the event type, status, attempts, your status code, how long it took, the reason it failed and when the next try is due.
- `GET /api/webhooks/deliveries/{delivery}` shows one delivery (`dlv_…`).
- `POST /api/webhooks/deliveries/{delivery}/replay` sends that event again as a new delivery with the same event id, for example after you fixed a bug. The webhook must be switched on and not paused. Test deliveries are not replayed: send a new test event.

## Send a test event

`POST /api/webhooks/{id}/test-event` sends a signed `webhook.test` delivery straight away (one try, `"test": true`) and answers with the result and the body we sent, so you can check your endpoint receives the delivery and verifies the signature. Send `{"event_type": "<type>"}` to get a sample of another signed event. Up to 10 test events a minute; test deliveries never count towards pausing a webhook.

```bash
curl -X POST https://go.thebuilding.cloud/api/webhooks/12/test-event \
  -H "Authorization: Bearer $TBC_KEY" \
  -H "Accept: application/json"
```

## Addresses we never call

We only call public internet addresses. An address that points to your own computer or a private network, such as `127.0.0.1`, `localhost`, `10.x.x.x`, `192.168.x.x` or a cloud server's internal metadata address, is refused and never called. We check where the name really points after looking it up, and we don't follow redirects, so a public name that leads to a private address is refused too.

A refused address shows a clear reason instead of a status code:

- on **Test Webhook** and in the delivery log, for example "The webhook address points to a private or reserved network address, which is not allowed.";
- in an automation's run history, when a **Call webhook** step uses such an address: the step fails with the same kind of reason.

To try webhooks on your own computer, use a tunnel service that gives you a public `https://` address.

Use an `https://` address. Plain `http://` still works for now, but it may be switched off later.

## The original monthly usage webhook

`monthly_location_usage` keeps its original body (no envelope, no signature) and is tried once:

```http
POST /your/webhook HTTP/1.1
Content-Type: application/json

{
  "location": "Riverside Park",
  "building": "Block B",
  "items": [
    { "name": "Per Entrance", "quantity": 2, "unit_price": 3, "description": "…" },
    { "name": "Tuya Devices", "quantity": 4, "unit_price": 0.5, "description": "Total number of Tuya smart devices in use" }
  ]
}
```

Every attempt is logged on the webhook with your system's answer or the error. Because it is not signed, use a long, unguessable address (for example with a random part in the path) and accept only `POST` with JSON.
