# Webhooks

Instead of asking `GET /v1/leads?updated_since=…` every few minutes, let us call you: a webhook endpoint receives a `POST` for every [event](https://docs.creator-guard.com/events/) it subscribes to, within seconds.

## Add an endpoint

In the portal (**Settings → API → Webhooks**, second factor needed) or with a key that has `webhooks:manage`:

curl:

```bash
curl -X POST https://api.creator-guard.com/v1/webhook-endpoints \
  -H "Authorization: Bearer $CG_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "url": "https://hooks.example.com/creator-guard",
    "event_types": ["lead.stage_changed", "consent.granted", "commission.paid"],
    "description": "CRM sync"
  }'
```

JavaScript:

```js
// Node.js 20+ as an ES module (.mjs, or "type": "module"): built-in fetch + top-level await.
// Server-side only: the key must never reach a browser.
const body = {
  "url": "https://hooks.example.com/creator-guard",
  "event_types": ["lead.stage_changed", "consent.granted", "commission.paid"],
  "description": "CRM sync"
};

const res = await fetch('https://api.creator-guard.com/v1/webhook-endpoints', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CG_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(), // keep it and send it again when you retry
  },
  body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
console.log(res.status, data);
```

Python:

```python
# pip install requests
import os
import uuid
import requests

body = {
    "url": "https://hooks.example.com/creator-guard",
    "event_types": ["lead.stage_changed", "consent.granted", "commission.paid"],
    "description": "CRM sync",
}

res = requests.request(
    "POST",
    "https://api.creator-guard.com/v1/webhook-endpoints",
    headers={"Authorization": f"Bearer {os.environ['CG_API_KEY']}", "Idempotency-Key": str(uuid.uuid4())},
    json=body,
    timeout=30,
)
data = res.json()
if not res.ok:
    raise RuntimeError(f"{res.status_code} {data['error']['code']}: {data['error']['message']}")
print(res.status_code, data)
```

`event_types` lists the types you want, or `["*"]` for all of them. The answer contains the signing secret (`whsec_…`) **once** — store it next to your API key. If you send the same request again with the same `Idempotency-Key`, the replayed answer has `secret: null`; the secret of the first answer is the one that counts.

**An endpoint carries only what its key may read.** The event types you subscribe to must be readable with the scopes of the key that creates (or changes) the endpoint — `lead.*`, `listing.approved`, `photo.*`, `consent.*` and `age_confirmation.confirmed` need `leads:read`, `commission.*` needs `earnings:read`, `agreement.published` needs `account:read`, `api_key.expiring` needs `keys:manage`; otherwise [`403 insufficient_scope`](https://docs.creator-guard.com/errors/#insufficient_scope) naming the scope. With `["*"]` the endpoint gets every type the key can read, nothing more — also later, and also on [replay](#replay). When a key changes the URL or the event types of an endpoint, the endpoint from then on carries only what that key can read; deliveries still waiting that it may no longer carry end as `failed` with `last_error: scope_removed`. This holds on every send: a delivery the endpoint may no longer carry is never sent — it ends `failed` (`scope_removed`) when it is next due, and a [retry](#retries) of it answers [`409 invalid_state`](https://docs.creator-guard.com/errors/#invalid_state). Endpoints set up in the portal (second factor) carry everything.

Rules for the URL: `https`, port 443, no user name or password in it, and a host that resolves to public addresses only. We check it now (a host we cannot look up answers [`502 upstream_failed`](https://docs.creator-guard.com/errors/#upstream_failed)) and again before every delivery. At most **10 endpoints per mode** ([`409 limit_reached`](https://docs.creator-guard.com/errors/#limit_reached)).

The portal manages **live** endpoints only. Test-mode endpoints are created with a `cg_test_` key and only get test events — see [Test mode](https://docs.creator-guard.com/test-mode/).

`POST /v1/webhook-endpoints/{id}/test` sends a [`ping`](https://docs.creator-guard.com/events/#event-ping) to this endpoint only — the quickest way to try your signature check.

## Change or delete an endpoint

`PATCH /v1/webhook-endpoints/{id}` changes `url`, `event_types`, `description` or `enabled`; a new URL is checked like on create. Every endpoint answer carries an `ETag`: send it back in `If-Match` and the change is refused with [`412 precondition_failed`](https://docs.creator-guard.com/errors/#precondition_failed) if someone else changed the endpoint in the meantime. `DELETE /v1/webhook-endpoints/{id}` removes the endpoint, its deliveries and every delivery still waiting for it.

## What we send

A test send, exactly as your server receives it:

```http
POST /creator-guard HTTP/1.1
Content-Type: application/json
User-Agent: CreatorGuard-Webhooks/1.0
CG-Event-Id: evt_aaaaaaaaaaaaaaaaaaaaaaaaaa
CG-Event-Type: ping
CG-Delivery-Id: whd_c7x2m4qk3vbn5h6tjd2wle4pza
CG-Signature: t=1791360000,v1=ac0772a3a4acdcc2fd2043ab9f18fc89e798aeb5efe9f79e5d1b3240413b7c29

{"id":"evt_aaaaaaaaaaaaaaaaaaaaaaaaaa","object":"event","type":"ping","created_at":"2026-10-07T08:00:00Z","mode":"test","api_version":"1.6.0","sequence":0,"data":{"object":{}}}
```

That signature is valid for the secret `whsec_0123456789abcdef0123456789abcdef0123456789abcdef` — our test vector, also used by the samples below. A real event carries the object it is about:

```json
{
  "id": "evt_hz5ikyc3pnhkrhlb6p7elkx2qy",
  "object": "event",
  "type": "lead.stage_changed",
  "created_at": "2026-10-10T08:00:00Z",
  "mode": "live",
  "api_version": "1.6.0",
  "sequence": 7,
  "data": { "object": { "object": "lead", "id": "lead_hz5ikyc3pnhkrhlb6p7elkx2qy", "stage": "ready", "version": 7 } },
  "previous_attributes": { "stage": "in_review" }
}
```

`data.object` is the full object (shortened above) as your account may see it **when we deliver** — fetch it again only if you need more. Every request comes from **37.187.128.185** (since 5 November 2026; before: 187.127.76.75); allow that address if your firewall needs one.

## Check the signature

`CG-Signature` holds a timestamp `t` and one `v1` per active secret: the hex HMAC-SHA256 of `"<t>.<raw body>"` with your whole secret string (`whsec_…`) as the key. Accept a request only if one `v1` matches **and** `t` is at most 5 minutes old. Use the **raw** body exactly as received — parsing and re-serialising the JSON changes the bytes and the signature no longer matches.

JavaScript (webhooks/verify.mjs):

```js
// Verify a Creator Guard webhook (Node.js 18+, no dependencies).
// rawBody: the request body exactly as received (string or Buffer) — not re-serialised JSON.
// header: the CG-Signature header. secret: your endpoint's whsec_… secret.
import { createHmac, timingSafeEqual } from 'node:crypto';

export const TOLERANCE_SECONDS = 300;

export function verifyWebhook(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
  let timestamp = null;
  const signatures = [];
  for (const part of String(header ?? '').split(',')) {
    const [key, value] = part.trim().split('=', 2);
    if (key === 't' && /^\d+$/.test(value ?? '')) timestamp = Number(value);
    if (key === 'v1' && /^[0-9a-f]{64}$/.test(value ?? '')) signatures.push(Buffer.from(value, 'hex'));
  }
  if (timestamp === null || signatures.length === 0) return false;
  if (Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false; // too old (or clock far off): a replay
  const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest();
  // One v1 per active secret: during a rotation we sign with the new and the old one.
  return signatures.some((signature) => timingSafeEqual(signature, expected));
}
```

Python (webhooks/verify.py):

```python
# Verify a Creator Guard webhook (Python 3.8+, standard library only).
# raw_body: the request body exactly as received (bytes) — not re-serialised JSON.
# header: the CG-Signature header. secret: your endpoint's whsec_… secret.
import hashlib
import hmac
import re
import time

TOLERANCE_SECONDS = 300

def verify_webhook(raw_body, header, secret, now=None):
    if isinstance(raw_body, str):
        raw_body = raw_body.encode("utf-8")
    timestamp, signatures = None, []
    for part in (header or "").split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isdigit():
            timestamp = int(value)
        if key == "v1" and re.fullmatch(r"[0-9a-f]{64}", value):
            signatures.append(value)
    if timestamp is None or not signatures:
        return False
    now = int(time.time()) if now is None else now
    if abs(now - timestamp) > TOLERANCE_SECONDS:  # too old (or clock far off): a replay
        return False
    expected = hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode("utf-8") + raw_body, hashlib.sha256).hexdigest()
    # One v1 per active secret: during a rotation we sign with the new and the old one.
    return any(hmac.compare_digest(signature, expected) for signature in signatures)
```

With Express, read the raw body for this route only:

```js
import express from 'express';
import { verifyWebhook } from './verify.mjs';

const app = express();
app.post('/creator-guard', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyWebhook(req.body, req.get('CG-Signature'), process.env.CG_WEBHOOK_SECRET)) return res.sendStatus(400);
  res.sendStatus(200); // answer first, then work: we wait at most 10 seconds
  jobs.push(JSON.parse(req.body.toString('utf8'))); // your own job queue
});
```

The [SDKs](https://docs.creator-guard.com/sdks/#webhook-signatures) have the same check built in (`verifyWebhookSignature` in TypeScript, `verify_webhook_signature` in Python); both are tested against the request above.

## Roll the secret

`POST /v1/webhook-endpoints/{id}/roll` (or **Roll secret** in the portal) issues a new secret, again shown once. For **24 hours** we sign with the new and the old one (two `v1` values), so you can switch without losing a delivery. We keep at most two secrets: roll again within those 24 hours and the newest two sign (the one before them stops at once), each roll starting a fresh 24 hours for its predecessor — so finish switching to one secret before you roll the next.

## Answer fast, process later

Any `2xx` within **10 seconds** counts as delivered. Everything else — another status, a timeout, a refused connection — is retried. Store the event, answer `200`, then do the work.

## Retries

At least once: a delivery is retried until it succeeds or 72 hours have passed. Minutes after the first attempt:

| Attempt | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Minute | 0 | 1 | 5 | 15 | 30 | 60 | 120 | 240 | 480 | 720 | 1080 | 1440 | 2160 | 2880 | 3600 | 4320 |

After the 16th attempt the delivery is `failed`. A failure on our side (we could not prepare the event) does not use up an attempt: it is tried again with a growing pause, at most hourly, and ends `failed` with `last_error: internal_error` once it is past the 72 hours — without counting toward disabling the endpoint. An endpoint whose deliveries have failed without a break for **72 hours** is disabled (`disabled_reason: failing`), and the event [`webhook_endpoint.disabled`](https://docs.creator-guard.com/events/#event-webhook_endpoint.disabled) goes to your other endpoints and into `GET /v1/events`. Fix the receiver, then `PATCH` it with `{"enabled": true}` — that starts its failure clock afresh.

`GET /v1/webhook-endpoints/{id}/deliveries` lists the deliveries of the last 30 days, newest first, each with every attempt (status code, duration, error); it pages forward only, with `starting_after`. `POST /v1/webhook-endpoints/{id}/deliveries/{d}/retry` makes one due again at once — also one that has already `failed`.

## Duplicates and order

- **Duplicates happen** (at least once): skip an event whose `CG-Event-Id` you have already processed.
- **Order is not guaranteed.** Every lead, photo and commission carries `version`, and every event about it carries the version the object reached as `sequence`. Keep the highest `sequence` you applied per object and drop an event with a lower or equal one.

## Replay

`POST /v1/webhook-endpoints/{id}/replay` with `{"from": "…", "to": "…"}` (`to` defaults to now) sends every event of that range again that the endpoint subscribes to — at most 30 days back. An endpoint holds at most **1,000 open deliveries** (waiting or being sent) after a replay: a range that would pass that is refused whole with [`409 limit_reached`](https://docs.creator-guard.com/errors/#limit_reached) (`limit: 1000`) and nothing is queued — wait for the queue to drain or pick a shorter range. Replays are spread out (four per second) and at most **10 per account and day** (test mode: 5) → [`429 rate_limited`](https://docs.creator-guard.com/errors/#rate_limited). Replayed deliveries have `replay: true`; your `sequence` check drops what you already have. Use it after an outage longer than 72 hours, or to fill a new database.

Deliveries are shared fairly: we send at most 5 deliveries to one endpoint at the same time and take turns between endpoints, so a long replay to one endpoint never holds up the events of another.
