# Webhooks

> Source: https://pixelsystems.com/docs/api/webhooks


Receive a job's or a file's result at your own endpoint as soon as it is ready, instead of polling for it.

A webhook is an HTTPS `POST` that Pixel sends to a URL you register when a result is ready. Each delivery is signed and carries the same result that [Get a job's result](https://pixelsystems.com/docs/api/get-job) (`/v1/jobs/{jobId}`) returns, so you can use webhooks instead of polling, or beside it.

## Quickstart

1. [Register an endpoint](#register-an-endpoint) in the dashboard.
2. [Copy the signing secret](#the-signing-secret) into your secret store.
3. [Verify the signature](#verify-the-signature) of every request.
4. [Answer with a `2xx`](#respond-to-a-delivery) within 10 seconds.
5. [Skip events you have already handled](#deduplicate-and-order).
6. [Send a test event](#test-and-troubleshoot) and check that your endpoint accepts it.

## Register an endpoint

Members with the Developer, Admin or Owner [role](https://pixelsystems.com/docs/concepts#organization) manage endpoints in the dashboard, in an application. An application holds up to 20 endpoints.

An endpoint URL must use `https`, be at most 2048 characters, and resolve to a public address. Pixel refuses private, loopback, link-local, carrier-grade NAT and cloud metadata addresses, when you save the endpoint and again on every delivery. Each delivery carries a result, so receive it on a server you control.

To test from your own machine, which Pixel cannot reach, expose your server through a public HTTPS tunnel such as [ngrok](https://ngrok.com/docs) or [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/). A test event carries example data, so it is safe to send through one.

### The signing secret

One secret signs the deliveries of every endpoint in an application. The application's first endpoint creates it.

> [!WARNING]
> **The signing secret is shown once**
>
> The dashboard shows the secret only when it is created or regenerated. Copy it into your secret store straight away. If you lose it, [regenerate it](#rotate-the-signing-secret).

After that, the dashboard shows the secret masked to `whsec_` and its last four characters, so you can tell which secret a receiver holds.

## Events

An endpoint chooses one or both event types:

| Event | Sent when | Body |
| --- | --- | --- |
| `job.finished` | Every file in a job has a result | The job's result, exactly as [Get a job's result](https://pixelsystems.com/docs/api/get-job) (`/v1/jobs/{jobId}`) returns it: a [`JobResult`](https://pixelsystems.com/docs/api/resources#jobresult) |
| `file.finished` | A file's result is ready | That file's entry in the job's `results`: a [`FileResult`](https://pixelsystems.com/docs/api/resources#fileresult) |

Pixel sends an event once the result is readable through the API, and the body is the result itself, with no wrapper. Both events are sent for an error result too. Files uploaded in the dashboard send events as API uploads do, except an image the dashboard refuses as too small before analyzing it. Analyzing a file again sends new events, with new event ids.

### Example payload

A `job.finished` body, the one a [test event](#test-and-troubleshoot) carries:

```json
{
  "jobId": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "results": [
    {
      "file": {
        "id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
        "name": "photo.jpg",
        "size": 1834211,
        "type": "image/jpeg"
      },
      "status": "completed",
      "startedAt": "2026-06-01T12:00:01Z",
      "completedAt": "2026-06-01T12:00:14Z",
      "verdict": {
        "key": "ai_signs",
        "class": "flagged",
        "confidence": "high"
      },
      "dimensions": [
        {
          "key": "ai_detection",
          "class": "flagged",
          "assessment": "ai_signs",
          "score": 0.82,
          "confidence": "high",
          "data": {
            "provenance": {
              "issuer": "OpenAI",
              "generator": "DALL·E"
            }
          }
        },
        {
          "key": "reverse_image_search",
          "class": "clear",
          "assessment": "similar_image_online",
          "score": 0.71,
          "confidence": "high",
          "data": {
            "matches": [
              {
                "url": "https://example.com/blog/post-77",
                "imageUrl": "https://example.com/img/77.jpg",
                "source": "example.com",
                "title": "Product launch gallery",
                "confidence": 0.71
              }
            ]
          }
        }
      ]
    }
  ],
  "metadata": {
    "customer_case_id": "case-123"
  },
  "createdAt": "2026-06-01T12:00:00Z",
  "completedAt": "2026-06-01T12:00:14Z"
}
```

## Request headers

- `Content-Type`: `application/json`.
- `User-Agent`: `Pixel-Webhooks/1.0`.
- `Pixel-Event-Id`: a unique id for the event, the same on every retry and redelivery of it.
- `Pixel-Event-Type`: `job.finished` or `file.finished`. The signature does not cover it.
- `Pixel-Signature`: the timestamp and the signature.

## Verify the signature

Check every request before you trust it. The `Pixel-Signature` header has the form:

```http
Pixel-Signature: t=1780315214,v1=0ca734d0ce4978eb3d42ea949b6421a1ccf0eebeb954e25c934170512963772b
```

`t` is the time Pixel signed the request, in [Unix time](https://en.wikipedia.org/wiki/Unix_time) seconds. Each `v1` is a hex-encoded [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of the string `<t>.<raw body>`, keyed by your signing secret.

> [!WARNING]
> **Sign the raw body with the whole secret**
>
> Compute the signature over the request body exactly as it arrived, before any JSON parsing: a body that was parsed and serialized again no longer matches. Use the whole secret as the key, `whsec_` prefix included, as text. Do not decode it.

To verify:

1. Take `t` and every `v1` value from the header.
2. Compute the HMAC-SHA256 of `t`, a `.`, and the raw body.
3. Compare your result with each `v1` using a [constant-time comparison](https://en.wikipedia.org/wiki/Timing_attack), and accept the request if any one matches.
4. Reject the request if `t` is not a whole number or is more than 5 minutes from your clock, so a captured request cannot be replayed later.

The header holds one `v1` for each secret in force: two during a [secret rotation](#rotate-the-signing-secret).

### Check your code with a test vector

Your signing code should produce this `v1` from these inputs:

```text
Secret:    whsec_exampleSigningSecretForTheDocs
Timestamp: 1780315214
Body:      {"jobId":"550e8400-e29b-41d4-a716-446655440000","status":"completed"}
v1:        0ca734d0ce4978eb3d42ea949b6421a1ccf0eebeb954e25c934170512963772b
```

The body has no line break at the end. The timestamp is in the past, so leave out the 5-minute check while you test with it.

### Code examples

Each example verifies the signature, then answers with `200`.

```javascript title="server.js" tab="Node.js"
import { createHmac, timingSafeEqual } from "node:crypto";
import express from "express";

const SECRET = process.env.PIXEL_WEBHOOK_SECRET; // whsec_...
const TOLERANCE_SECONDS = 5 * 60;

function verify(rawBody, header) {
  // express.raw leaves an empty object when the
  // Content-Type is not application/json.
  if (!Buffer.isBuffer(rawBody)) return false;

  const parts = (header ?? "")
    .split(",")
    .map((part) => part.split("="));
  const t = parts.find(([key]) => key === "t")?.[1];
  const signatures = parts
    .filter(([key]) => key === "v1")
    .map(([, value]) => value);
  if (!t || signatures.length === 0) return false;

  // A timestamp that is not a whole number is rejected, not compared.
  const timestamp = Number(t);
  if (!Number.isInteger(timestamp)) return false;
  const age = Math.abs(Date.now() / 1000 - timestamp);
  if (age > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", SECRET)
    .update(`${t}.`)
    .update(rawBody)
    .digest();

  return signatures.some((signature) => {
    const received = Buffer.from(signature, "hex");
    return (
      received.length === expected.length &&
      timingSafeEqual(received, expected)
    );
  });
}

const app = express();

app.post(
  "/pixel-webhook",
  // express.raw keeps the body as the bytes Pixel sent.
  express.raw({ type: "application/json" }),
  (req, res) => {
    const header = req.get("Pixel-Signature");
    if (!verify(req.body, header)) {
      return res.sendStatus(400);
    }

    const eventId = req.get("Pixel-Event-Id");
    // job.finished or file.finished
    const eventType = req.get("Pixel-Event-Type");
    const result = JSON.parse(req.body.toString("utf8"));
    // Skip an eventId you have already handled. Otherwise store
    // the event with its type, then answer. Do slow work afterwards.
    res.sendStatus(200);
  },
);
```

```python title="app.py" tab="Python"
import hashlib
import hmac
import os
import time

from flask import Flask, request

SECRET = os.environ["PIXEL_WEBHOOK_SECRET"]  # whsec_...
TOLERANCE_SECONDS = 5 * 60

app = Flask(__name__)


def verify(raw_body: bytes, header: str) -> bool:
    pairs = [
        part.split("=", 1)
        for part in header.split(",")
        if "=" in part
    ]
    timestamps = [value for key, value in pairs if key == "t"]
    signatures = [value for key, value in pairs if key == "v1"]
    if not timestamps or not signatures:
        return False

    # A timestamp that is not a whole number is rejected, not compared.
    try:
        t = int(timestamps[0])
    except ValueError:
        return False
    if abs(time.time() - t) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(
        SECRET.encode("utf-8"),
        f"{t}.".encode("ascii") + raw_body,
        hashlib.sha256,
    ).hexdigest()

    # Compared as bytes, so a malformed signature is rejected
    # instead of raising an error.
    return any(
        hmac.compare_digest(
            expected.encode("ascii"),
            signature.encode("utf-8"),
        )
        for signature in signatures
    )


@app.post("/pixel-webhook")
def pixel_webhook():
    # get_data returns the bytes Pixel sent, before any JSON parsing.
    raw_body = request.get_data()
    header = request.headers.get("Pixel-Signature", "")
    if not verify(raw_body, header):
        return "", 400

    event_id = request.headers["Pixel-Event-Id"]
    # job.finished or file.finished
    event_type = request.headers["Pixel-Event-Type"]
    result = request.get_json()
    # Skip an event_id you have already handled. Otherwise store
    # the event with its type, then answer. Do slow work afterwards.
    return "", 200
```

## Respond to a delivery

A delivery succeeds when your endpoint answers with a `2xx` status within 10 seconds. Store the event, answer, and process it afterwards. Pixel does not follow redirects, so register the final URL.

## Deduplicate and order

Pixel delivers each event **at least once**, so the same event can arrive twice. Keep the `Pixel-Event-Id` of each event you handle and skip one you have seen.

Deliveries can also arrive **out of order**. Keep the newest result per file or job by the timestamps in the payload, such as `completedAt`, not by arrival order.

## Retries

Any other answer is a failure: a non-`2xx` status, a redirect, no answer within 10 seconds, or a connection error. Pixel retries a failed delivery after about 1, 5, 15 and 30 minutes, then after 1, 2, 4 and 8 hours, counted from the first attempt. The attempt after 8 hours is the last, and the delivery is given up 24 hours after the first.

If an endpoint's deliveries keep failing for 24 hours with no success, Pixel turns the endpoint off, gives up its deliveries still being retried, and emails the organization's Developers, Admins and Owners. A quiet spell of more than 8 hours with no attempts starts the count again. Fix the endpoint, turn it back on in the dashboard, and redeliver what you missed.

## Test and troubleshoot

Send a test event from the dashboard to an endpoint that is turned on. It is signed like any other and carries `Pixel-Event-Type: job.finished` with the [example payload](#example-payload). Its `Pixel-Event-Id` starts with `test:`, so your endpoint can recognize it and skip processing.

Each endpoint's delivery log in the dashboard shows its newest 100 deliveries, with the response status and attempt number of every try, and redelivers one on request. A redelivery carries the same `Pixel-Event-Id`. Pixel keeps a delivery for 30 days after its last attempt; after a long outage, catch up with [List jobs](https://pixelsystems.com/docs/api/list-jobs) (`/v1/jobs`).

## Rotate the signing secret

Regenerate the secret in the dashboard, which shows the new one once. The previous secret keeps signing for 24 hours, so both signatures appear in `Pixel-Signature` and a receiver that checks either keeps accepting deliveries. Deploy the new secret inside that window. Until it closes, the dashboard shows the previous secret's last four characters too, so you can tell which receivers still hold it.
