# Webhooks

> Get notified when extractions finish, verify the Parsefox-Signature header and handle retries.

Webhooks tell your service when a job finishes, so you don't have to poll.

## Register an endpoint

In the console open **Webhooks** and choose **Add endpoint**, or call the API:

```bash
curl "$PARSEFOX_BASE_URL/v1/webhooks" \
  -H "Authorization: Bearer $PARSEFOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/parsefox/webhook", "events": ["extraction.completed", "extraction.failed"]}'
```

The response contains the signing `secret` (`whsec_…`) **once**. Store it like the API
key, for example in `PARSEFOX_WEBHOOK_SECRET`. Leave out `events` to receive all of
them.

- Endpoints belong to the mode of the key that created them: test keys create test
  endpoints that receive test events only.
- Both live and test endpoints must be public `https` URLs. Test deliveries use
  the real network, so private and loopback addresses are blocked in both modes.
- Up to 16 endpoints per account. `PATCH /v1/webhooks/{id}` changes the URL, events or
  `enabled`; `POST /v1/webhooks/{id}/rotate-secret` issues a new secret.
- Rotation takes effect at once: every delivery after it, including retries, carries a
  single `v1=` signature made with the new secret. Deploy the new secret to your
  receiver promptly; deliveries rejected in between are retried for up to 24 hours.

## Events

| Event | Sent when |
|---|---|
| `extraction.completed` | A job finished with `completed` or `completed_with_unresolved`. Check `review_required`. |
| `extraction.failed` | A job failed. `last_error` explains why. |
| `extraction.cancelled` | A job was cancelled. |
| `schema_suggestion.completed` | A schema suggestion is ready. |
| `schema_suggestion.failed` | A schema suggestion failed. |

## Payload

```json
{
  "id": "evt_5d1c0f2a9b7e4c3d",
  "object": "event",
  "type": "extraction.completed",
  "mode": "live",
  "created_at": "2026-10-20T17:30:09Z",
  "data": {
    "object": {
      "object": "extraction",
      "job_id": "job_ff48e2ee7a2e",
      "document_id": "doc_a624f2b16bfc",
      "status": "completed_with_unresolved",
      "review_required": true,
      "schema": { "id": "sch_8f73a8efa4f34f87", "version": 2 },
      "metadata": { "order_id": "A-1042" },
      "links": { "result": "/v1/extractions/job_ff48e2ee7a2e/result" }
    }
  }
}
```

`data.object` is the same job object that `GET /v1/extractions/{job_id}` returns
(shortened above). The event does not contain extracted values; fetch them from
`links.result`.

Each request carries these headers:

| Header | Value |
|---|---|
| `Parsefox-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |
| `Parsefox-Event-Id` | The event `id`; the same for every retry. |
| `Parsefox-Event-Type` | The event `type`. |
| `Parsefox-Delivery-Id` | This delivery attempt. |

## Verify the signature

The signature is an HMAC-SHA256 of `"<t>.<raw request body>"` keyed with the whole
secret string (including `whsec_`). Compute it over the raw bytes you received,
before parsing JSON, compare in constant time and reject timestamps older than five
minutes.

### Python

```python
import hashlib
import hmac
import time


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

In FastAPI, read the body with `await request.body()`; in Flask use
`request.get_data()`.

### TypeScript

```typescript
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyParsefoxSignature(secret: string, header: string, body: Buffer, tolerance = 300): boolean {
  const parts = Object.fromEntries(
    header.split(",").map((item) => {
      const index = item.indexOf("=");
      return [item.slice(0, index), item.slice(index + 1)];
    }),
  );
  const timestamp = Number(parts.t);
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > tolerance) return false;
  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest("hex");
  const received = Buffer.from(String(parts.v1 ?? ""));
  return received.length === expected.length && timingSafeEqual(received, Buffer.from(expected));
}
```

In Express, use `express.raw({ type: "application/json" })` for the webhook route so
`req.body` is the raw `Buffer`.

## Respond and retry

- Respond with any `2xx` within 10 seconds. Do the slow work (fetching the result,
  writing to your database) after responding, for example in a queue.
- Anything else, including redirects and timeouts, is a failed attempt. Parsefox
  retries after 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h and 8 h, for up to 24
  hours after the event.
- Deliveries can arrive more than once and out of order. Use `Parsefox-Event-Id` to
  ignore duplicates, and treat the job `status` as the source of truth.
- The console shows every delivery with its response code, and lets you resend one
  (`POST /v1/webhook-deliveries/{id}/resend`). `GET /v1/webhooks/{id}/deliveries`
  lists them.

## Test locally

With a **test key**, register a public HTTPS endpoint or use an HTTPS tunnel to
your local receiver. Test jobs finish in a few seconds and send real, signed events. Name the file
`needs_review.pdf` or `failed.pdf` to receive the other outcomes (see
[Test mode](/docs/test-mode.md)).

On a self-hosted development instance only, an operator can set
`AI_IDP_CLOUD_WEBHOOKS_ALLOW_PRIVATE=true` to allow HTTP and localhost receivers.
Leave this setting off on public deployments.
