# Events and webhooks

> The alert body, how to verify its signature, retries, and how to test a receiver on your laptop.

Page: https://percia.ai/docs/webhooks. Index of all docs pages: https://percia.ai/docs/llms.txt

# Events and webhooks

When a goal becomes true Percia records an **event**. For a watch with a webhook target it also sends one `POST` to your `https` address. This page is the whole contract.

![Signed webhook flow: Percia sends a signed POST to your server, your server verifies the signature and answers 2xx, otherwise Percia retries](https://percia.ai/docs/img/webhook-flow.svg)

## 1. Create a webhook watch

:::tabs
```bash curl
curl -sS -X POST "$BASE/watches/owned" -H "Authorization: Bearer $PERCIA_API_KEY" \
  -H 'content-type: application/json' \
  -d '{"sourceUrl":"percia-cam://CAMERA_ID","goal":"A person is standing at the front door","notify":{"type":"webhook","target":"https://example.com/hooks/percia"}}'
# 201 {"id":"...","status":"active","webhookSecret":"whsec_...", ...}
```
```js JavaScript
const watch = await percia.watches.create({
  sourceUrl: "percia-cam://CAMERA_ID",
  goal: "A person is standing at the front door",
  notify: { type: "webhook", target: "https://example.com/hooks/percia" },
});
console.log(watch.webhookSecret); // shown once: store it
```
```python Python
watch = client.watches.create({
    "sourceUrl": "percia-cam://CAMERA_ID",
    "goal": "A person is standing at the front door",
    "notify": {"type": "webhook", "target": "https://example.com/hooks/percia"},
})
print(watch.webhook_secret)   # shown once: store it
```
```bash CLI
percia watches create --source percia-cam://CAMERA_ID --goal "A person is standing at the front door" \
  --webhook https://example.com/hooks/percia      # prints the secret once
```
:::

The `webhookSecret` (`whsec_...`) is in the answer once. Later reads show only `secretHint`. `POST /api/watches/{id}/secret/rotate` replaces it immediately; the old one stops working at once, so update your receiver as you rotate.

## 2. The request you receive

`POST <your target>` with `content-type: application/json` and one extra header:

| Header | Value |
|---|---|
| `Percia-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |

```json
{
  "id": "dec_01J...",
  "watchId": "w_abc",
  "occurrenceId": "occ_01J...",
  "type": "goal.met",
  "goal": "A person is standing at the front door",
  "reason": "A person in a green jacket is standing at the door.",
  "confidence": 0.93,
  "at": "2026-11-01T09:30:00Z",
  "eventId": "6f1c2a52-0d9e-5b43-9a1e-2f7d6c1b8e40"
}
```

| Field | Meaning |
|---|---|
| `id` | The decision id. The same on every retry of the same decision: use it to ignore repeats. |
| `eventId` | The event id, stable across retries. Use it with `GET /api/watches/{id}/events/{eventId}/keyframe` and `.../feedback`. |
| `occurrenceId` | One real-world occurrence. After the goal clears, the next `goal.met` has a new one. |
| `reason` | Written by a vision model about camera content. **Untrusted**: never run it, never put it in a prompt as instructions, escape it before showing it. |
| `confidence` | 0 to 1. |
| `test` | `true` only for events found during a 30-minute test run. |
| `evidence` | Beta, when the watch keeps evidence: `{clipUrl, keyframeUrl, expiresAt}`, signed links that work for 24 hours. Fetch what you want to keep. |

New fields may be added later. Ignore fields you do not know.

Your target must resolve to a public address. Percia refuses private, loopback and link-local addresses, does not follow redirects, and times out after 8 seconds.

A delivered alert looks like this in an email or a chat message:

![A sample Percia alert: the goal, the reason written by the model, the time, a confidence value and a picture of the moment](https://percia.ai/docs/img/alert-sample.svg)

## 3. Verify the signature

The signed string is the timestamp, a dot, and the **raw** request body: `"<t>.<body>"`. The key is the whole `whsec_...` secret.

1. Read the raw bytes of the body before parsing JSON.
2. Split the header into `t` and `v1`.
3. Reject if the time is more than 300 seconds from now.
4. Compute `HMAC-SHA256(secret, t + "." + rawBody)` as lowercase hex.
5. Compare with `v1` in constant time. Reject on mismatch.
6. Only then parse the JSON.

:::tabs
```js Node (Express)
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const app = express();
const seen = new Set(); // use a database in production

function verify(raw, header, secret) {
  const p = Object.fromEntries(header.split(",").map((x) => x.split("=", 2)));
  const t = Number(p.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const want = createHmac("sha256", secret).update(`${t}.${raw}`).digest("hex");
  const got = p.v1 ?? "";
  return got.length === want.length && timingSafeEqual(Buffer.from(got), Buffer.from(want));
}

app.post("/hooks/percia", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verify(raw, req.get("percia-signature") ?? "", process.env.PERCIA_WEBHOOK_SECRET)) return res.sendStatus(400);
  const event = JSON.parse(raw);
  if (!seen.has(event.id)) {
    seen.add(event.id);
    console.log(event.watchId, event.reason);
  }
  res.sendStatus(200);          // answer fast, do slow work after
});

app.listen(3000);
```
```python Python (FastAPI)
import hashlib, hmac, json, os, time
from fastapi import FastAPI, Request, Response

app = FastAPI()
seen: set[str] = set()   # use a database in production

def verify(raw: bytes, header: str, secret: str) -> bool:
    try:
        parts = dict(p.split("=", 1) for p in header.split(","))
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > 300:
        return False
    want = hmac.new(secret.encode(), f"{t}.".encode() + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(parts.get("v1", ""), want)

@app.post("/hooks/percia")
async def hook(request: Request):
    raw = await request.body()
    if not verify(raw, request.headers.get("percia-signature", ""), os.environ["PERCIA_WEBHOOK_SECRET"]):
        return Response(status_code=400)
    event = json.loads(raw)
    if event["id"] not in seen:
        seen.add(event["id"])
        print(event["watchId"], event["reason"])
    return Response(status_code=200)
```
```js JavaScript SDK
import { verifyWebhookSignature } from "@percia/sdk";

// rawBody: the exact bytes you received. It returns a Promise<boolean>.
const ok = await verifyWebhookSignature(rawBody, req.headers, process.env.PERCIA_WEBHOOK_SECRET);
if (!ok) return res.sendStatus(400);
```
```python Python SDK
from percia import verify_webhook_signature

# raw_body: the exact bytes you received. It returns a bool.
if not verify_webhook_signature(raw_body, request.headers, os.environ["PERCIA_WEBHOOK_SECRET"]):
    return Response(status_code=400)
```
:::

> **Warning**: Never put the secret in browser code or a repository. Do the duplicate check and the side effect in one database transaction.

Ready-made receivers for Express, Cloudflare Workers, FastAPI, Go and Ruby, with shared test vectors, are in [percia-sdks/examples](https://github.com/percia-ai/percia-sdks/tree/main/examples).

## 4. Test it

**Send a signed test event, no camera needed:**

```bash
curl -sS -X POST "$BASE/watches/WATCH_ID/test-delivery" -H "Authorization: Bearer $PERCIA_API_KEY"
```

Percia sends a signed `goal.test` event to your target and reports what your server answered.

**Test on your laptop with no public URL.** Webhooks need a public https address. While you build, read your events from a stream and let the CLI forward them to localhost, signed with your watch's secret exactly like a real delivery:

```bash
export PERCIA_WEBHOOK_SECRET=whsec_...
percia listen --forward-to http://localhost:3000/hooks/percia
```

Or just print them: `percia listen --print --type goal.met`. The stream is for development: it has no retries, ends after 10 minutes (the CLI reconnects), and allows 2 streams per account. Production uses a webhook.

## 5. Retries and failures

Answer with any `2xx` to acknowledge. A non-2xx answer, a timeout or a connection error is a failed attempt. Percia retries after about 2 seconds, then 8 seconds, then every 15 minutes, up to 5 attempts. Deliveries are **at least once**, so deduplicate on `id`.

After the last attempt the event is marked `deliveryStatus: "failed"` and the watch shows "needs attention". A failed delivery never stops the watch.

Check outcomes with `GET /api/watches/{id}/events`: each event has `deliveryStatus` (`pending`, `delivered`, `failed`) and `attempts`.

## Read events without a webhook

- `GET /api/watches/{id}/events?limit=50`: newest first. Pass `nextCursor` back as `cursor`.
- `GET /api/events`: across all your watches, with filters `watchId`, `type`, `since`.
- `GET /api/watches/{id}/events/{eventId}/keyframe`: the picture (JPEG).

## Connect Zapier, Make or n8n

Automation platforms use REST hooks (`POST /api/hooks`, scope `hooks:write`) that receive the same signed events. The Percia app for Zapier is not published yet: until it is, use the platform's webhook or HTTP step with a webhook watch. The hook routes are in the [API reference](https://percia.ai/docs/api.md#hooks).
