# Webhooks (/docs/guides/webhooks)

> Get a signed HTTPS request when documents render, fail or expire and when batches finish, and verify it before you act on it.

Webhooks tell your server when something happens to a document or a batch, so you don't have to poll. Druckling sends a signed JSON `POST` to your HTTPS endpoint for each event. Requests follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec, so the official SDKs, the Standard Webhooks libraries or a few lines of your own code can verify them.

## Event types [#event-types]

| Event | Sent when | `data` |
| --- | --- | --- |
| `document.rendered` | A document finished rendering. | The document, with a signed download `url`. |
| `document.failed` | A document failed: its payload didn't validate, or rendering failed. | The document, with an `error`. |
| `document.expired` | A document's file was deleted after the [retention period](/docs/concepts/documents). | The document, with `status: "expired"` and no `url`. |
| `batch.completed` | A [batch](/docs/guides/batches) finished as `completed`, `failed` or `canceled`. Sent once per batch. | The batch, with `counts` and `zip_url`. |
| `webhook.ping` | You clicked **Send test event** in the dashboard. You can't subscribe to it. | `{ "object": "ping", "endpoint_id": "whe_…", "message": "…" }` |

Documents send these events however they were created: synchronous and asynchronous renders, batch items, and renders from the dashboard. A synchronous request whose payload fails validation answers `422` and also sends `document.failed`. The one exception is batch items that are canceled or never start rendering: they don't send `document.failed`, and the batch's `batch.completed` covers them.

## Add an endpoint [#add-an-endpoint]

Endpoints belong to the workspace and to one mode. A test endpoint only receives events from test-mode documents and batches, a live endpoint only live ones. A workspace can have up to 20 endpoints.

### In the dashboard [#in-the-dashboard]

Open **Developers › Webhooks** and click **Add endpoint**. Enter the URL, an optional description, the events to send, and the mode (**Test** or **Live**). The signing secret appears once the endpoint is added; you can reveal it again later from the endpoint's page.

### With the API [#with-the-api]

[`POST /v1/webhook_endpoints`](/docs/api-reference/webhooks/create) creates an endpoint in the API key's mode. It needs a **Full access** key; a **Render only** key gets `403`.

```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/webhook_endpoints \
  -H "Authorization: Bearer $DRUCKLING_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhooks/druckling",
    "events": ["document.rendered", "document.failed", "batch.completed"],
    "description": "Invoice mailer"
  }'
```

```ts tab="TypeScript"
import Druckling from "@druckling/sdk";

const druckling = new Druckling();

const endpoint = await druckling.webhookEndpoints.create({
  url: "https://example.com/webhooks/druckling",
  events: ["document.rendered", "document.failed"],
  description: "Invoice mailer",
});
console.log(endpoint.id, endpoint.secret);
```

```python tab="Python"
from druckling import Druckling

client = Druckling()

endpoint = client.webhook_endpoints.create(
    url="https://example.com/webhooks/druckling",
    events=["document.rendered", "document.failed", "batch.completed"],
    description="Invoice mailer",
)
print(endpoint.id, endpoint.secret)
```

```php tab="PHP"
<?php
use Druckling\Druckling;

$druckling = new Druckling();

$endpoint = $druckling->webhookEndpoints->create(
    url: 'https://example.com/webhooks/druckling',
    events: ['document.rendered', 'document.failed', 'batch.completed'],
    description: 'Invoice mailer',
);
echo $endpoint->id, ' ', $endpoint->secret, PHP_EOL;
```

The answer is `201` with the endpoint and its `secret` (`whsec_…`). The API returns the secret only in this response, so store it now, for example as `DRUCKLING_WEBHOOK_SECRET`.

<Callout type="info" title="batch.completed in the SDKs">

The SDKs' event types only list the `document.*` events so far. In TypeScript, `"batch.completed"` in `events` is a type error, so subscribe to it with cURL or in the dashboard; the Python and PHP SDKs pass it through as is. All three SDKs verify `batch.completed` deliveries like any other event; see [Handle batch events](#handle-batch-events).

</Callout>

[`GET /v1/webhook_endpoints`](/docs/api-reference/webhooks/list) and [`GET /v1/webhook_endpoints/{id}`](/docs/api-reference/webhooks/get) list and fetch the endpoints of the key's mode, and [`DELETE /v1/webhook_endpoints/{id}`](/docs/api-reference/webhooks/delete) removes one. Everything else happens in the dashboard: editing the URL, events and description, turning an endpoint off and on, revealing and rotating the secret, sending test events and resending deliveries. An endpoint's mode can't change; add a new endpoint for the other mode.

In the dashboard, only owners and admins can add, change or delete endpoints, see secrets, and send or resend events. Members can see endpoints and their deliveries. See [Team members and roles](/docs/guides/team).

### URL requirements [#url-requirements]

- The URL must start with `https://` and be at most 2,048 characters.
- The host must be reachable on the public internet. `localhost`, private and link-local IP addresses, hosts without a dot, and hosts ending in `.local`, `.internal` or `.localhost` are rejected. Before every delivery, Druckling checks again that the host resolves to a public address.
- Redirects aren't followed. A `3xx` answer counts as a failed delivery.
- Any `#fragment` is dropped.

To receive webhooks on your laptop, expose your local server through an HTTPS tunnel and register the tunnel's public URL as a test endpoint.

## What Druckling sends [#what-druckling-sends]

Each delivery is a `POST` with a JSON body and these headers:

| Header | Value |
| --- | --- |
| `content-type` | `application/json` |
| `user-agent` | `Druckling-Webhooks/1.0` |
| `webhook-id` | The event ID, e.g. `evt_7Lq2Vb9XmR4tKp8N`. The same for every attempt and every resend of the event. |
| `webhook-timestamp` | Unix time in seconds when this attempt was sent. |
| `webhook-signature` | `v1,` followed by the base64 signature. Several space-separated signatures while a secret is being [rotated](#rotate-the-signing-secret). |

The body is an event envelope:

| Field | Description |
| --- | --- |
| `id` | Event ID, the same as the `webhook-id` header. |
| `object` | Always `"event"`. |
| `type` | The event type, e.g. `document.rendered`. |
| `created_at` | When the event happened (ISO 8601). Retries keep this value. |
| `test_mode` | `true` for test-mode events. |
| `data` | The [document](/docs/api-reference/documents/get) or [batch](/docs/api-reference/batches/get), exactly as the API returns it. |

`data` is a snapshot taken when the event happens. Retries and resends deliver the same body.

<Tabs items={["document.rendered", "document.failed", "document.expired", "batch.completed", "webhook.ping"]}>
<Tab value="document.rendered">

```json
{
  "id": "evt_7Lq2Vb9XmR4tKp8N",
  "object": "event",
  "type": "document.rendered",
  "created_at": "2026-10-27T09:41:07.498Z",
  "test_mode": false,
  "data": {
    "id": "pdf_8Qw2kLm3nP0aB1cD",
    "object": "document",
    "status": "rendered",
    "template": "invoice-standard",
    "version": 3,
    "filename": "INV-2041.pdf",
    "format": "pdf",
    "content_type": "application/pdf",
    "image": null,
    "pages": 1,
    "size_bytes": 36033,
    "url": "https://files.example.com/pdf_8Qw2kLm3nP0aB1cD.pdf?signature=…",
    "expires_at": "2026-11-26T09:41:07.498Z",
    "error": null,
    "einvoice": null,
    "batch": null,
    "language": "en",
    "test_mode": false,
    "created_at": "2026-10-27T09:41:06.210Z"
  }
}
```

</Tab>
<Tab value="document.failed">

```json
{
  "id": "evt_3Fm8QzT1vK6nRw2Y",
  "object": "event",
  "type": "document.failed",
  "created_at": "2026-10-27T09:44:19.031Z",
  "test_mode": false,
  "data": {
    "id": "pdf_2Vn7RtY4kQ9mXc1B",
    "object": "document",
    "status": "failed",
    "template": "invoice-standard",
    "version": 3,
    "filename": "INV-2042.pdf",
    "format": "pdf",
    "content_type": "application/pdf",
    "image": null,
    "pages": null,
    "size_bytes": null,
    "url": null,
    "expires_at": null,
    "error": {
      "code": "schema_validation_failed",
      "message": "Required field customer.address was missing from the request payload",
      "field": "customer.address"
    },
    "einvoice": null,
    "batch": null,
    "language": "en",
    "test_mode": false,
    "created_at": "2026-10-27T09:44:19.012Z"
  }
}
```

</Tab>
<Tab value="document.expired">

```json
{
  "id": "evt_9Kc4WpN2xL7tQm5R",
  "object": "event",
  "type": "document.expired",
  "created_at": "2026-11-27T03:17:12.640Z",
  "test_mode": false,
  "data": {
    "id": "pdf_8Qw2kLm3nP0aB1cD",
    "object": "document",
    "status": "expired",
    "template": "invoice-standard",
    "version": 3,
    "filename": "INV-2041.pdf",
    "format": "pdf",
    "content_type": "application/pdf",
    "image": null,
    "pages": 1,
    "size_bytes": 36033,
    "url": null,
    "expires_at": "2026-11-26T09:41:07.498Z",
    "error": null,
    "einvoice": null,
    "batch": null,
    "language": "en",
    "test_mode": false,
    "created_at": "2026-10-27T09:41:06.210Z"
  }
}
```

</Tab>
<Tab value="batch.completed">

```json
{
  "id": "evt_5Rn2XqK8wT1mZp4L",
  "object": "event",
  "type": "batch.completed",
  "created_at": "2026-10-27T09:52:41.902Z",
  "test_mode": false,
  "data": {
    "id": "bat_3Hk9QmZ1xT7pLw2V",
    "object": "batch",
    "status": "completed",
    "template": "invoice-standard",
    "version": 3,
    "filename_pattern": "invoice-{{invoice.number}}.pdf",
    "counts": { "total": 250, "pending": 0, "rendered": 248, "failed": 2, "canceled": 0 },
    "zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…",
    "zip_size_bytes": 9035112,
    "zip_expires_at": "2026-11-26T09:52:41.902Z",
    "error": null,
    "test_mode": false,
    "created_at": "2026-10-27T09:48:02.114Z",
    "finished_at": "2026-10-27T09:52:41.902Z"
  }
}
```

</Tab>
<Tab value="webhook.ping">

```json
{
  "id": "evt_2Zt8LqW4mN7xKp3V",
  "object": "event",
  "type": "webhook.ping",
  "created_at": "2026-10-27T09:30:00.000Z",
  "test_mode": true,
  "data": {
    "object": "ping",
    "endpoint_id": "whe_4Fq9LmZ2xR8tKpWc",
    "message": "Test event from Druckling. Verify the signature, then answer with any 2xx status."
  }
}
```

</Tab>
</Tabs>

A `document.*` event for a batch item has `data.batch` set to `{ "id": "bat_…", "index": 12 }`, the item's position in the batch.

## Verify signatures [#verify-signatures]

Anyone who knows your endpoint's URL can send it requests, so check every request's signature before you trust it. Druckling signs each attempt like this:

1. Take the part of the secret after `whsec_` and base64-decode it. That's the HMAC key.
2. Build the signed content: `{webhook-id}.{webhook-timestamp}.{body}`, with the **raw** request body exactly as received.
3. Compute HMAC-SHA256 over it and base64-encode the result.
4. Send it in `webhook-signature` as `v1,<signature>`.

To verify, recompute the signature and compare it in constant time with each `v1,` entry of the header; one match is enough. Also reject requests whose `webhook-timestamp` is more than 5 minutes from your clock, which stops old requests from being replayed. That's the tolerance the SDKs use by default.

<Callout type="warn" title="Use the raw body">

Verify the body bytes exactly as they arrived. Parsing the JSON and serializing it again changes whitespace or key order and breaks the signature. In Express, use `express.raw()` on the webhook route; in Next.js, read `await request.text()`; in Flask, `request.get_data()`; in PHP, `file_get_contents('php://input')`.

</Callout>

### With an SDK [#with-an-sdk]

Each SDK has a verify helper that checks the signature and the timestamp and returns the parsed event, or throws when anything is off. See [SDKs](/docs/sdks) to install one.

| SDK | Function | Throws |
| --- | --- | --- |
| TypeScript | `verifyWebhook(rawBody, headers, secret, { toleranceSeconds? })` | `WebhookVerificationError` |
| Python | `verify_webhook(raw_body, headers, secret, *, tolerance=300)` | `WebhookVerificationError` |
| PHP | `Webhook::verify($rawBody, $headers, $secret, $tolerance = 300)` | `WebhookVerificationException` |

```ts tab="Next.js" title="app/api/webhooks/druckling/route.ts"
import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk";

export async function POST(request: Request) {
  let event;
  try {
    event = await verifyWebhook(await request.text(), request.headers, process.env.DRUCKLING_WEBHOOK_SECRET!);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 });
    throw error;
  }

  if (event.type === "document.rendered") {
    await enqueueInvoiceEmail(event.id, event.data.id);
  } else if (event.type === "document.failed") {
    await notifyTeam(event.id, event.data.id, event.data.error?.message);
  }
  return new Response(null, { status: 204 });
}
```

```ts tab="Express" title="server.ts"
import express from "express";
import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk";

const app = express();

app.post("/webhooks/druckling", express.raw({ type: "application/json" }), async (req, res, next) => {
  try {
    const event = await verifyWebhook(req.body, req.headers, process.env.DRUCKLING_WEBHOOK_SECRET!);
    if (event.type === "document.rendered") await enqueueInvoiceEmail(event.id, event.data.id);
    res.sendStatus(204);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return res.sendStatus(400);
    next(error);
  }
});
```

```python tab="Flask" title="app.py"
import os

from flask import Flask, request
from druckling import WebhookVerificationError, verify_webhook

app = Flask(__name__)
SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"]


@app.post("/webhooks/druckling")
def druckling_webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers, SECRET)
    except WebhookVerificationError:
        return "Invalid signature", 400

    if event.type == "document.rendered":
        enqueue_invoice_email(event.id, event.document.id)
    elif event.type == "document.failed":
        notify_team(event.id, event.document.id, event.document.error.message)
    return "", 204
```

```python tab="FastAPI" title="main.py"
import os

from fastapi import FastAPI, HTTPException, Request, Response
from druckling import WebhookVerificationError, verify_webhook

app = FastAPI()
SECRET = os.environ["DRUCKLING_WEBHOOK_SECRET"]


@app.post("/webhooks/druckling")
async def druckling_webhook(request: Request) -> Response:
    try:
        event = verify_webhook(await request.body(), request.headers, SECRET)
    except WebhookVerificationError:
        raise HTTPException(status_code=400, detail="Invalid signature")

    if event.type == "document.rendered":
        await enqueue_invoice_email(event.id, event.document.id)
    return Response(status_code=204)
```

```php tab="PHP" title="webhook.php"
<?php
require __DIR__ . '/vendor/autoload.php';

use Druckling\Exception\WebhookVerificationException;
use Druckling\Model\WebhookEvent;
use Druckling\Webhook;

try {
    $event = Webhook::verify(
        file_get_contents('php://input'),
        getallheaders(),
        (string) getenv('DRUCKLING_WEBHOOK_SECRET'),
    );
} catch (WebhookVerificationException $e) {
    http_response_code(400);
    exit;
}

if ($event->type === WebhookEvent::DOCUMENT_RENDERED) {
    enqueueInvoiceEmail($event->id, $event->document->id);
} elseif ($event->type === WebhookEvent::DOCUMENT_FAILED) {
    notifyTeam($event->id, $event->document->id, $event->document->error?->message);
}

http_response_code(204);
```

`enqueueInvoiceEmail` and `notifyTeam` stand for your own code. Pass the event ID along so the work can be [deduplicated](#duplicates-and-ordering).

The event object mirrors the envelope. In TypeScript, `event.data` is the document. In Python and PHP, `event.document` (`$event->document`) is the parsed document for `document.*` events and `None` (`null`) otherwise, while `event.data` (`$event->data`) is always the raw `data` object. In PHP, `$_SERVER` works as the headers array too.

### Handle batch events [#handle-batch-events]

`batch.completed` verifies like any other event, but the SDKs don't have a type for it yet, so read the batch from the raw `data`:

```ts tab="TypeScript"
interface BatchData {
  id: string;
  status: "completed" | "failed" | "canceled";
  counts: { total: number; rendered: number; failed: number; canceled: number };
  zip_url: string | null;
}

if ((event.type as string) === "batch.completed") {
  const batch = event.data as unknown as BatchData;
  if (batch.status === "completed") await enqueueZipDownload(event.id, batch.id);
}
```

```python tab="Python"
if event.type == "batch.completed":
    batch = event.data
    if batch["status"] == "completed":
        enqueue_zip_download(event.id, batch["id"])
```

```php tab="PHP"
if ($event->type === 'batch.completed' && $event->data['status'] === 'completed') {
    enqueueZipDownload($event->id, $event->data['id']);
}
```

The SDKs' document types also don't include `batch` yet. Read `event.data.batch` through a cast in TypeScript, or from `event.data["batch"]` and `$event->data['batch']` in Python and PHP.

### By hand [#by-hand]

Without an SDK, verification takes a few lines of standard library code. Each example takes the raw body, the three `webhook-*` headers and the `whsec_…` secret, and returns the parsed event.

```js tab="Node.js" title="verify-webhook.mjs"
import crypto from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verifyRerenderWebhook(rawBody, headers, secret) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) throw new Error("Missing webhook headers");
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
    throw new Error("Timestamp outside the tolerance");
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.`).update(rawBody).digest();

  const valid = signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const given = Buffer.from(signature, "base64");
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
  if (!valid) throw new Error("No matching signature");
  return JSON.parse(rawBody);
}
```

```python tab="Python" title="verify_webhook.py"
import base64
import hashlib
import hmac
import json
import time

TOLERANCE_SECONDS = 5 * 60


def verify_druckling_webhook(raw_body: bytes, headers, secret: str) -> dict:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        raise ValueError("Missing webhook headers")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        raise ValueError("Timestamp outside the tolerance")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(raw_body)
    raise ValueError("No matching signature")
```

```php tab="PHP" title="verify-webhook.php"
<?php
function verifyRerenderWebhook(string $rawBody, string $id, string $timestamp, string $signatures, string $secret): array
{
    if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) {
        throw new RuntimeException('Timestamp outside the tolerance');
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true));

    foreach (explode(' ', $signatures) as $entry) {
        [$version, $signature] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $signature)) {
            return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
        }
    }

    throw new RuntimeException('No matching signature');
}

$event = verifyRerenderWebhook(
    file_get_contents('php://input'),
    $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
    (string) getenv('DRUCKLING_WEBHOOK_SECRET'),
);
```

The Node.js version expects lowercase header names, as in Node's `req.headers`, and a body that is a string or a `Buffer`. The Python version expects a case-insensitive mapping such as Flask's `request.headers`. Python 3.9 or later is needed for `removeprefix`.

Check your implementation against this signed request. With the clock set to the timestamp, it must verify, and changing a single byte of the body must make it fail:

```text
secret:            whsec_MfKQ9r8GKYqrTFLSBT3AmRGeT8ksXcRnjbJ0K9oQBXg=
webhook-id:        evt_2Zt8LqW4mN7xKp3V
webhook-timestamp: 1793093400
webhook-signature: v1,UiRQtira4saHgvPj2tLXnRoUorJPqmF9nQz18r+tObg=
body:              {"id":"evt_2Zt8LqW4mN7xKp3V","object":"event","type":"webhook.ping","created_at":"2026-10-27T09:30:00.000Z","test_mode":true,"data":{"object":"ping","endpoint_id":"whe_4Fq9LmZ2xR8tKpWc","message":"Test event from Druckling. Verify the signature, then answer with any 2xx status."}}
```

The SDKs can also produce signatures for your own tests: `signWebhook(secret, id, timestamp, body)` in TypeScript, `sign_webhook(secret, msg_id, timestamp, body)` in Python, and `Webhook::sign($secret, $msgId, $timestamp, $body)` in PHP.

## Responses and retries [#responses-and-retries]

A delivery succeeds when your endpoint answers with any `2xx` status within 10 seconds. Druckling doesn't interpret the response body; it only keeps the start of it for the [delivery log](#delivery-logs-and-resending).

Anything else counts as a failure and is retried: another status code, including `3xx` redirects; no answer within 10 seconds; or a connection or TLS error. Druckling makes up to 7 attempts over about 8.6 hours:

| Attempt | Sent |
| --- | --- |
| 1 | Right away |
| 2 | 10 seconds after attempt 1 |
| 3 | 1 minute after attempt 2 |
| 4 | 5 minutes after attempt 3 |
| 5 | 30 minutes after attempt 4 |
| 6 | 2 hours after attempt 5 |
| 7 | 6 hours after attempt 6 |

If attempt 7 fails too, the delivery is marked failed. You can still [resend](#delivery-logs-and-resending) it from the dashboard. Each attempt is signed afresh with a new `webhook-timestamp`; the `webhook-id` and the body stay the same.

- **`410 Gone`** stops retries for that delivery right away and turns the endpoint off. Answer `410` only when you want Druckling to stop sending.
- **Turning an endpoint off** cancels its pending retries. Events that happen while it's off aren't delivered later, not even after you turn it back on.
- **Deleting an endpoint** stops its pending deliveries and removes its delivery history.

Druckling doesn't turn endpoints off after other failures, so a broken endpoint keeps receiving attempts. Keep an eye on **Last 7 days** in the endpoint list.

### Duplicates and ordering [#duplicates-and-ordering]

- **Duplicates.** The same event can reach you more than once, for example after a timeout on your side or a manual resend. Store the `webhook-id` of the events you've processed and skip repeats.
- **Ordering.** Events can arrive in any order. A batch's `batch.completed` can arrive before some of its items' `document.rendered`. Decide what to do from `data.status`, not from the order of arrival.

## Delivery logs and resending [#delivery-logs-and-resending]

Open an endpoint under **Developers › Webhooks** to see its recent deliveries, all or only failed ones. Each delivery shows the event type, its status (pending, succeeded or failed), the number of attempts, when the next retry is due, the request body that was sent, and your endpoint's response status and the start of its body (up to 2,000 characters). The endpoint list shows each endpoint's successful and failed deliveries over the last 7 days. Delivery history is kept for 30 days.

- **Resend** sends a delivery's event again right away, with the same `webhook-id` and body, so your deduplication recognizes it. It's a single attempt: if it fails, it isn't retried. The endpoint must be turned on.
- **Send test event** delivers a `webhook.ping` event once, with no retries, whatever events the endpoint subscribes to. Use it to check your URL and your signature code.

Only owners and admins can resend and send test events.

## Rotate the signing secret [#rotate-the-signing-secret]

Rotate a secret when it may have leaked, or as routine hygiene. On the endpoint's page under **Developers › Webhooks**, open the **⋯** menu and choose **Rotate signing secret**. The new secret is shown right away.

For the next 24 hours, every request is signed with both secrets, so `webhook-signature` carries two entries:

```text
webhook-signature: v1,<signature with the new secret> v1,<signature with the old secret>
```

Verification passes as long as one of them matches, which the SDK helpers and the examples above already handle. Deploy the new secret to your server within those 24 hours; after that, only the new secret signs.

Rotation is only available in the dashboard. With the API alone, create a second endpoint for the same URL, make your server accept both endpoints' secrets, then delete the old endpoint. While both exist, each event arrives twice with the same `webhook-id`, so your [deduplication](#duplicates-and-ordering) drops the copy.

## Best practices [#best-practices]

- **Verify first, then answer quickly.** Check the signature, store or queue the event, and return `2xx` right away. Do slow work, such as sending emails or downloading files, in the background, well within the 10-second limit.
- **Deduplicate on `webhook-id`.** Make your processing idempotent so a repeated event does no harm.
- **Fetch fresh data before you act on it.** The `url` in a `document.rendered` event was signed when the event happened and works for up to 7 days, and resends deliver the same body. Before downloading, fetch the document again with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get) for a fresh link; do the same for a batch's `zip_url` with [`GET /v1/batches/{id}`](/docs/api-reference/batches/get).
- **Keep test and live apart.** Use separate endpoints and secrets for each mode, and check `test_mode` before triggering anything with real-world effects.
- **Reconcile now and then.** If missing an event would be costly, also check periodically through the API, for example by [listing documents](/docs/api-reference/documents/list) with `status=failed`.
