# Receiving webhooks

> Check that each delivery comes from Flavio, answer fast and handle repeats.

Flavio sends each event of an account to the URL of its webhooks ([Create a webhook](https://www.flavioagent.com/docs/webhooks/index.md#create-webhook)) as
a `POST` with the event in JSON, the envelope that [Events](https://www.flavioagent.com/docs/events/index.md) describes:

```http
POST /flavio HTTP/1.1
Host: hooks.example-builder.com
Content-Type: application/json
User-Agent: Flavio-Webhooks/1.0
X-Flavio-Signature: t=1764500000,v1=5f2c8e0b9d4a7c1e3f6b8a0d2c4e6f8a1b3d5f7a9c0e2b4d6f8a0c2e4b6d8f0a

{"id":"2b8f41d0c9e44a1b8c6d3e0f1a2b3c4d5e6f7081","type":"plan.ready","created_at":"2026-11-04T11:04:52Z","account":"{uuid}","source":"flavio","l1":"Plan ready","l2":"Flavio wrote version 3 of the plan after the goals changed.","details":{"plan_version":3}}
```

### Check the signature

1. Take `t` and `v1` from the header `X-Flavio-Signature`.
2. Compute the HMAC-SHA256, in hexadecimal, of `t`, a dot and the body exactly as it arrived, with
   the `secret` of the webhook. Parsing the JSON first and writing it again changes the body.
3. Compare it with `v1` in constant time, and reject a `t` more than five minutes old.

```js
// Node.js (Express): read the body raw, as it arrived.
import crypto from "node:crypto";

app.post("/flavio", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("X-Flavio-Signature") ?? "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((part) => part.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.FLAVIO_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`)
    .digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
  const valid =
    v1?.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
  if (!fresh || !valid) return res.sendStatus(400);

  res.sendStatus(204);
  queue.add(JSON.parse(req.body)); // The work, afterwards.
});
```

```python
# Python (Flask)
import hashlib, hmac, json, os, time
from flask import request

@app.post("/flavio")
def flavio():
    parts = dict(p.split("=", 1) for p in request.headers.get("X-Flavio-Signature", "").split(","))
    body = request.get_data()  # The body raw, as it arrived.
    expected = hmac.new(os.environ["FLAVIO_WEBHOOK_SECRET"].encode(),
                        parts.get("t", "").encode() + b"." + body, hashlib.sha256).hexdigest()
    fresh = abs(time.time() - int(parts.get("t", "0"))) < 300
    if not fresh or not hmac.compare_digest(parts.get("v1", ""), expected):
        return "", 400
    queue.put(json.loads(body))  # The work, afterwards.
    return "", 204
```

```php
<?php
// PHP
$body = file_get_contents("php://input"); // The body raw, as it arrived.
parse_str(str_replace(",", "&", $_SERVER["HTTP_X_FLAVIO_SIGNATURE"] ?? ""), $parts);
$expected = hash_hmac("sha256", ($parts["t"] ?? "") . "." . $body, getenv("FLAVIO_WEBHOOK_SECRET"));
$fresh = abs(time() - (int) ($parts["t"] ?? 0)) < 300;
if (!$fresh || !hash_equals($expected, $parts["v1"] ?? "")) {
    http_response_code(400);
    exit;
}
http_response_code(204);
enqueue(json_decode($body, true)); // The work, afterwards.
```

### Answer fast, work afterwards

Answer with a `2xx` within 10 seconds, before doing anything slow: keep the event and work on it
afterwards. Any other answer, or none, is retried with longer and longer waits for 24 hours; after
that the event is not sent again. Everything is also on the timeline of the account.

### Repeats and order

The same event can arrive twice: keep the `id` of the ones you handled and skip a repeat. Events can
arrive out of order: sort them by `created_at`. An event carries ids, not the objects: to know how
something stands now, read it.

### Try it

[Test a webhook](https://www.flavioagent.com/docs/webhooks/index.md#test-webhook) sends a `webhook.test` event within a minute. How it went shows in
`last_status` and `last_error` of the webhook.
