# Webhooks

Push Influtics events to your own server. You register one HTTPS endpoint per
organization, choose which events you want, and Influtics `POST`s a signed JSON
payload to it whenever something changes.

This is set up in the dashboard — **Settings → Integrations → Webhooks** — not
through the public REST API, so there is no API key involved in the delivery.
Instead, each endpoint has its own **signing secret**, and every request is
signed with it. See [Verifying the signature](#verifying-the-signature).

## 📬 The delivery

```http
POST https://your-endpoint.example.com/your/path
Content-Type: application/json
X-Influtics-Event: video.created
X-Influtics-Delivery-Id: 3f2b0c9e-1c1a-4a1e-9a3a-2f5a0f1b7c11
X-Influtics-Signature: ts=1763456122;h1=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
User-Agent: Influtics-Webhooks/1.0
```

```json
{
  "id": "3f2b0c9e-1c1a-4a1e-9a3a-2f5a0f1b7c11",
  "type": "video.created",
  "organization_id": "9f1d2b6e-4a51-4a2f-8a77-0c9b1e5d3a20",
  "occurred_at": "2026-11-18T09:15:22.418Z",
  "data": {
    "video_id": "6c2a0f4e-2a10-4f77-9c3e-0b6a1d2e5f34",
    "blogger_id": "b4d9a1c8-6f2e-4a77-b3d0-1f9c2e5a7b60",
    "external_video_id": "ivan_talknow/143"
  }
}
```

| Field | Meaning |
|-------|---------|
| `id` | The delivery id. Identical to the `X-Influtics-Delivery-Id` header. **Use it as your idempotency key** — it is stable across retries *and* across a manual resend. |
| `type` | The event type — one of the four in the table below. |
| `organization_id` | Your organization's id in Influtics. |
| `occurred_at` | When the event happened (ISO-8601, UTC). |
| `data` | The event payload — **frozen** at the moment the event was recorded. It is never reshaped and never re-read, so the body you receive is the body that was produced. |

There is no `Authorization` header, and the signature covers only the timestamp
and the body — not the headers.

## 📋 Events

| Event | When it is sent | `data` fields |
|-------|------------------|---------------|
| `creator.tracked` | A creator starts being tracked. | `blogger_id` — the creator's id in Influtics.<br>`platform` — `instagram`, `tiktok`, `youtube`, …<br>`channel_username` — the creator's handle on that platform. |
| `video.created` | A video is parsed and added to tracking. **The first time you track a creator, every one of their existing posts is sent** — a creator with 40 posts produces 40 `video.created` deliveries, one per post. | `video_id` — the video's id in Influtics (stable).<br>`blogger_id` — the creator's id.<br>`external_video_id` — the platform's own id for the video. |
| `stats.updated` | A video's aggregated statistics change. | `video_id` — the video's id in Influtics.<br>`blogger_id` — **always `null`** (see the note below).<br>`external_video_id` — the platform's own id for the video. |
| `video.deleted` | A video stops being tracked — soft-deleted, hard-deleted, or its creator removed. | `video_id` — the video's id in Influtics.<br>`blogger_id` — the creator's id.<br>`external_video_id` — the platform's own id for the video. |

:::warning `stats.updated` does not carry `blogger_id`
The statistics table is keyed by the platform's video id, and resolving it back
to a creator needs a join against a table that is **not** unique per creator —
so the join is deliberately not made, and `blogger_id` is always `null`. The
`video_id` **is** resolved, so you can still correlate a stats event to a
video. If you need the creator, look it up from the `video.created` event you
already received for that `video_id`.
:::

### One delivery per video — never a batch

Events are delivered one at a time. If five videos change, your endpoint
receives **five separate requests**, each with a single video in `data` — there
is no array form and no batch endpoint. Requests for one organization are sent
at most **4 at a time** (up to 20 across all organizations), so they can
arrive overlapping and **in any order**. Use `occurred_at` and the video id to
reconcile; never assume ordering.

### `external_video_id` is not stable

`video_id` is Influtics' own identifier and never changes. `external_video_id`
is the platform's identifier for the video, and it **can be rewritten** — for
example, Telegram videos are first recorded with a username-style handle
(`ivan_talknow/143`) and later rewritten to a numeric channel id
(`1676741417/143`). **Key on `video_id`.**

## 🔐 Verifying the signature

The **signing secret** is generated when you create the endpoint, and it is
shown to you **exactly once** — copy it then, because it is never returned
again. If you lose it, rotate the secret from the dashboard.

What you receive in the dashboard is a **base64** string (44 characters).
**Base64-decode it** to get the 32 raw bytes — those bytes are the HMAC key.
Signing with the base64 text instead never matches.

Every request carries:

```
X-Influtics-Signature: ts=<unix seconds>;h1=<lowercase hex>
```

The signature is computed over the exact bytes `<ts>:<raw body>` — the
timestamp, one colon, then the request body **exactly as received**:

```
signed_string = f"{ts}:{raw_body}"
hmac          = HMAC-SHA256(key = base64_decode(secret), message = signed_string)
header        = f"ts={ts};h1={hmac.hexdigest()}"
```

:::danger Verify against the raw body
If your framework hands you a parsed object, re-serializing it changes the
bytes (key order, whitespace, unicode escaping) and the signature will not
match. **Capture the raw body before parsing.**
:::

To accept a request:

1. Parse `ts` and `h1` out of the header. `ts` must be all digits, `h1` must be
   64 lowercase hex characters.
2. Reject the request if `abs(now - ts) > 300` — a **300-second, symmetric**
   replay window (a timestamp up to 300 s in the future is accepted too).
3. Recompute the HMAC over `f"{ts}:{raw_body}"` and compare **in constant
   time**.

### JavaScript / Node.js

```js
import crypto from 'node:crypto'

const TOLERANCE_SECONDS = 300

export function verifyInfluticsDelivery({ secret, header, rawBody, now = Math.floor(Date.now() / 1000) }) {
  if (!header) return false
  const parts = Object.fromEntries(header.split(';').map((p) => p.split('=')))
  const ts = parts.ts
  const h1 = parts.h1
  if (!/^\d+$/.test(ts ?? '') || !/^[0-9a-f]{64}$/.test(h1 ?? '')) return false
  if (Math.abs(now - Number(ts)) > TOLERANCE_SECONDS) return false
  const key = Buffer.from(secret, 'base64')                     // 32 raw bytes
  const expected = crypto.createHmac('sha256', key).update(`${ts}:${rawBody}`, 'utf8').digest('hex')
  return crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(h1, 'hex'))
}
```

### Python

```python
import base64, hashlib, hmac, time

def verify_influtics_delivery(secret_b64, header, raw_body, now=None):
    now = int(time.time()) if now is None else now
    parts = dict(p.split("=", 1) for p in header.split(";"))
    ts, h1 = parts.get("ts", ""), parts.get("h1", "")
    if not ts.isdigit() or len(h1) != 64 or h1 != h1.lower():
        return False
    if abs(now - int(ts)) > 300:
        return False
    key = base64.b64decode(secret_b64)
    expected = hmac.new(key, f"{ts}:".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, h1)
```

### Example: an Express handler

```js
import express from 'express'
import { verifyInfluticsDelivery } from './verify.js'

app.post('/influtics', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body                       // a Buffer — the bytes as received
  const ok = verifyInfluticsDelivery({
    secret: process.env.INFLUTICS_WEBHOOK_SECRET,
    header: req.get('X-Influtics-Signature'),
    rawBody: raw.toString('utf8'),
  })
  if (!ok) return res.status(401).end()

  const event = JSON.parse(raw.toString('utf8'))
  console.log(event.type, event.data)
  res.status(200).end()                      // only an exact 200 counts as delivered
})
```

`express.raw()` (or your framework's equivalent) is what preserves the exact
bytes. With `express.json()` the body is already parsed and re-serializing it
changes the bytes.

### Rotating the secret

Rotating keeps the **old secret working for 24 hours**. A delivery recorded
*before* the rotation and less than 24 hours old is signed with the **previous**
secret; everything else uses the current one.

So try both during that window:

```js
const ok =
  verifyInfluticsDelivery({ secret: CURRENT_SECRET, header, rawBody }) ||
  verifyInfluticsDelivery({ secret: PREVIOUS_SECRET, header, rawBody })   // may be unset
```

Keep the previous secret for 24 hours after a rotation, then discard it. A
rotation does **not** break in-flight retries: deliveries already queued are
still delivered, signed with whichever secret applies to them. After 24 hours
the "previous secret" branch stops matching on its own.

## 🔄 Delivery semantics

| Outcome | What happens |
|---------|--------------|
| Your server answers **exactly `200`** | Delivered. Nothing else counts — `201` and `204` are failures. |
| Your server answers `410 Gone` | Dropped permanently, never retried. Use it when your endpoint has been decommissioned. |
| Anything else (`201`, `204`, `3xx`, `4xx`, `5xx`), a timeout, or a body over 256 KiB | Failure — retried. |

A failed delivery is retried **at most twice**, roughly **1 hour** and then
**4 hours** after the previous attempt (3 delivery attempts in total, over
about 5 hours). After that the event is dropped from the delivery log. A crash
on our side — we die part-way through a delivery — also consumes one of those
three attempts.

We poll for new events every **2 minutes**, so the typical end-to-end delay is a
couple of minutes. Events are never dropped for being late; they stay queued
until they are delivered or the retry budget runs out.

### Deliveries are at-least-once, and updates can be coalesced

Two things follow from how the queue works, and both matter for a sync:

- **You may receive the same event twice** — a retry after a timeout, or a
  manual resend. Deduplicate on the delivery `id`.
- **You may NOT receive every intermediate update.** If the same video's stats
  change again before the earlier change was delivered, the newer state
  **replaces** the queued one instead of queueing behind it. Treat
  `stats.updated` as *"this video's stats changed, here is a snapshot"* — not
  as an event log of every value the stats passed through.

There is no ordering guarantee, and no strict ordering between a video's
`video.created` and its `stats.updated`.

### Keep it fast

We read at most **256 KiB** of your response, and give your server **10
seconds** to answer. A slow response is treated as a failure and retried. If
your handler does real work, acknowledge first and process afterwards — and
answer `200` with an **empty body**.

## ⚙️ Setting it up

1. Open **Settings → Integrations → Webhooks** in the dashboard.
2. Enter a **public HTTPS URL** — it must be reachable from the internet. We
   refuse loopback, private and link-local addresses, cloud metadata
   addresses, and `.local` / `.internal` / single-label hostnames, and we check
   again at delivery time.
3. Tick the events you want.
4. Save. The dashboard shows your **signing secret once** — copy it.
5. Use the **Send test ping** button to check your endpoint answers `200` and
   that your verifier accepts the request.

You can pause deliveries at any time with the **Endpoint active** toggle
(a paused endpoint drops deliveries and refuses test pings), and rotate the
secret at any time.

## 📊 Inspecting deliveries

The dashboard's Webhooks section has a **Show history** expander listing every
delivery — successes and failures alike — with the event type, the status, the
number of attempts, and the last error. From there you can re-send a delivery
manually. A re-send can produce a duplicate, so make sure your handler is
idempotent.

---

**Next Step**: [Authentication →](./authentication.md)
