# Webhooks: partner integration guide

After you follow this guide, your system (an ERP, a buyer's or importer's traceability system) receives a signed HTTPS
`POST` from CropPath within seconds of a lot being sealed, recalled or withdrawn, a lab result being recorded, a
shipment departing, a lot's trust tier changing, or a mismatch report being filed, and it can prove that each request
really came from CropPath and was not changed or replayed.

Webhooks follow the [Standard Webhooks](https://www.standardwebhooks.com/) signing scheme. Everything below is taken
from CropPath's code and the OpenAPI document (`/developers/openapi.json` on the developer portal, section
`webhooks`); the numbers are the code's constants.

| You need to... | Go to |
| --- | --- |
| know what you will receive | [1. What you get](#1-what-you-get) |
| get an endpoint registered | [2. Set up](#2-set-up) |
| check that a request is genuine | [3. Verify every request](#3-verify-every-request) and [4. Code samples](#4-code-samples) |
| answer and process deliveries | [5. Responding and processing](#5-responding-and-processing) |
| change the secret | [6. Rotating the secret](#6-rotating-the-secret) |
| try it before going live | [7. Testing](#7-testing) |
| fix a failing endpoint | [8. Troubleshooting](#8-troubleshooting) |
| review your receiver | [9. Security checklist](#9-security-checklist) |

---

## 1. What you get

### Events

A subscription chooses one or more of these event types. Each event is recorded in the same database transaction as
the change it reports, so you never get an event for a change that was rolled back, and no committed change of a
chosen type goes unannounced to an **active** subscription.

| Type | When it fires | `data` fields |
| --- | --- | --- |
| `lot.sealed` | a lot is closed and its manifest signed | `lot`, `public_id`, `facility`, `sealed_at`, `manifest_sha256`, `fruit_count`, `event_count` |
| `lot.recalled` | a lot is recalled (`kind: recall`) | `lot`, `public_id`, `kind`, `reason`, `scope`, `recalled_at`, `cartons`, `shipments` |
| `lot.withdrawn` | a lot is withdrawn (`kind: withdrawal`) | same fields as `lot.recalled` |
| `lab_result.recorded` | a lab report of the lot's sampling is stored (signed by the lab or entered in its portal) | `lot`, `sampling_id`, `lab`, `report_no`, `market`, `signed_at`, `passed` |
| `shipment.departed` | a shipment leaves its facility | `shipment`, `facility`, `container`, `border_gate`, `destination`, `departed_at`, `lots` |
| `lot.trust_tier_changed` | a recompute moves the lot's displayed trust tier (never for a lot's first snapshot) | `lot`, `public_id`, `tier`, `previous_tier`, `status`, `changed_at` |
| `report.filed` | a consumer files a mismatch report on one of the tenant's fruits | `report_id`, `lot`, `fruit`, `category`, `filed_at` |

Enumerated values:

- `kind`: `recall`, `withdrawal`. `reason`: `contamination`, `pathogen`, `foreign_matter`, `labelling`, `quality`,
  `regulatory`, `traceability`, `other`. `scope`: `consumer`, `retail`, `wholesale`.
- `tier`, `previous_tier`: `self_declared`, `device_recorded`, `cross_checked`, `lab_verified` (lowest first).
  `status`: `normal`, `on_hold`.
- `category`: `label_peeled`, `scanned_many`, `ripeness_off`, `other`.
- `market`: a two-letter market code. Every time (`*_at`, `created_at`) is UTC, ISO 8601 with milliseconds.

New event types and new enum values may be added within API v1 ([versioning policy](versioning.md)): ignore a type you
do not know (answer 2xx) and treat an unknown enum value as "other".

Payloads carry identifiers, states and times only. They never carry personal data or free text: no staff note, no
reporter's note or contact. Read anything else through the API (section 5).

### The request

Every delivery is an HTTP/1.1 `POST` to your URL with these headers and a JSON body:

| Header | Value |
| --- | --- |
| `Content-Type` | `application/json` (the body is UTF-8) |
| `User-Agent` | `CropPath-Webhooks/1` |
| `webhook-id` | the event id, `evt_` + 32 hex digits. The same on every attempt and every redelivery of that event |
| `webhook-timestamp` | Unix seconds of **this attempt** (a retry has a new timestamp and a new signature) |
| `webhook-signature` | `v1,` + base64 of the HMAC-SHA256 signature (section 3) |

The body is the event: `{"created_at", "data", "id", "tenant", "type"}`, compact JSON with sorted keys. `id` equals
`webhook-id`, `created_at` is when the change happened, `tenant` is the CropPath tenant whose subscription it is. The
body is stored once and sent byte for byte the same on every attempt.

One real example of each event body (pretty-printed here; on the wire it is one compact line):

<details>
<summary><code>lot.sealed</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "event_count": 260,
    "facility": "VN-TGPH-021",
    "fruit_count": 128,
    "lot": "LO-260928-014",
    "manifest_sha256": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
    "public_id": "9f86d081884c7d659a2feaa0c55ad015",
    "sealed_at": "2026-09-28T10:15:00.000Z"
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "lot.sealed"
}
```

</details>

<details>
<summary><code>lot.recalled</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "cartons": 41,
    "kind": "recall",
    "lot": "LO-260928-014",
    "public_id": "9f86d081884c7d659a2feaa0c55ad015",
    "reason": "contamination",
    "recalled_at": "2026-10-02T03:00:00.000Z",
    "scope": "consumer",
    "shipments": 1
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "lot.recalled"
}
```

</details>

<details>
<summary><code>lot.withdrawn</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "cartons": 41,
    "kind": "withdrawal",
    "lot": "LO-260928-014",
    "public_id": "9f86d081884c7d659a2feaa0c55ad015",
    "reason": "contamination",
    "recalled_at": "2026-10-02T03:00:00.000Z",
    "scope": "consumer",
    "shipments": 1
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "lot.withdrawn"
}
```

</details>

<details>
<summary><code>lab_result.recorded</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "lab": "LAB-VN-118",
    "lot": "LO-260928-014",
    "market": "CN",
    "passed": true,
    "report_no": "KN-LO-260928-014",
    "sampling_id": 12,
    "signed_at": "2026-09-29T02:00:00.000Z"
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "lab_result.recorded"
}
```

</details>

<details>
<summary><code>shipment.departed</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "border_gate": "Hữu Nghị",
    "container": "MSKU1234565",
    "departed_at": "2026-09-29T09:00:00.000Z",
    "destination": "CN",
    "facility": "VN-TGPH-021",
    "lots": [
      "LO-260928-014"
    ],
    "shipment": "SH-LO-260928-014"
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "shipment.departed"
}
```

</details>

<details>
<summary><code>lot.trust_tier_changed</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "changed_at": "2026-10-01T05:30:00.000Z",
    "lot": "LO-260928-014",
    "previous_tier": "cross_checked",
    "public_id": "9f86d081884c7d659a2feaa0c55ad015",
    "status": "on_hold",
    "tier": "self_declared"
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "lot.trust_tier_changed"
}
```

</details>

<details>
<summary><code>report.filed</code></summary>

```json
{
  "created_at": "2026-10-01T05:30:00.000Z",
  "data": {
    "category": "ripeness_off",
    "filed_at": "2026-10-01T05:29:58.000Z",
    "fruit": "Q-14-37",
    "lot": "LO-260928-014",
    "report_id": 5
  },
  "id": "evt_6f1c2d3e4a5b46c7889900aabbccddee",
  "tenant": "coop-dl",
  "type": "report.filed"
}
```

</details>

The full schemas are in the OpenAPI document (`webhooks` section, schemas `WebhookEvent*` and `Webhook*Data`) and on the
developer portal's webhook events page (`/en/developers/reference/webhook-events`).

### Delivery semantics

- **Fast, but not on the request path.** A periodic job (every 5 seconds unless the deployment changes it) sends due
  deliveries, at most 10 per run, oldest first. Expect the first attempt within seconds of the change.
- **2xx = delivered.** Any 2xx status within 10 seconds delivers the event. Anything else is a failed attempt: another
  status (a 3xx redirect included: redirects are not followed), no answer, a connection or TLS error, or a timeout.
  The response body is read (up to 64 KiB) and ignored.
- **At least once.** You can receive the same event more than once: a 2xx that got lost on the way back, a retry that
  crossed your answer, a redelivery from the delivery log. Deduplicate on `webhook-id` (section 5).
- **No ordering guarantee.** Deliveries are sent oldest due first, but a retried delivery waits for its backoff while
  newer events go ahead, a subscription that fails is skipped for the rest of that job run, and a redelivery is sent
  whenever it is requested. Do not assume that `lot.sealed` arrives before `shipment.departed` for the same lot. Use the
  times in `data` (and `created_at`) to order events, and read the current state through the API when order matters.
- **One subscription at a time.** When an attempt to your endpoint fails, the job sends nothing more to that
  subscription in the same run, so a failing endpoint is not hammered.

### Retries

A failed attempt is retried with exponential backoff: 1 minute, doubling, at most 6 hours apart, for **12 attempts**
in total. The delay is counted from the start of the previous attempt; each attempt can start up to one job interval
later than shown.

| Attempt | Delay after the previous attempt | Time since the first attempt |
| --- | --- | --- |
| 1 | (the event is due at once) | 0 |
| 2 | 1 min | 1 min |
| 3 | 2 min | 3 min |
| 4 | 4 min | 7 min |
| 5 | 8 min | 15 min |
| 6 | 16 min | 31 min |
| 7 | 32 min | 1 h 3 min |
| 8 | 1 h 4 min | 2 h 7 min |
| 9 | 2 h 8 min | 4 h 15 min |
| 10 | 4 h 16 min | 8 h 31 min |
| 11 | 6 h | 14 h 31 min |
| 12 | 6 h | 20 h 31 min |

After the 12th failed attempt (about 20.5 hours after the first) the delivery is `failed` and is not tried again by
itself. An admin can **redeliver** it from the delivery log (section 7) within the retention period.

### Automatic disabling

The subscription counts failed attempts in a row across all its deliveries (`consecutive_failures`); any successful
delivery resets the count to 0. At **50 failed attempts in a row** the subscription is disabled
(`status: disabled`, `disabled_reason: failures`) and its pending deliveries are failed with `subscription_disabled`.

While a subscription is disabled (by failures or by an admin), **no events are recorded for it**: changes that happen
during that time are never queued for it and cannot be redelivered. After you fix your endpoint, ask the admin to
enable it again (section 8), redeliver the failed deliveries you need, and read the changes of the disabled period
through the API.

### Retention

Delivered and failed deliveries are deleted 30 days after they were queued, and events older than 30 days are deleted
once they have no delivery left. A delivery can be redelivered only while it is still in the log. Pending deliveries
are never deleted.

---

## 2. Set up

### Endpoint requirements

Your endpoint must meet every one of these, or CropPath refuses the URL or counts the attempt as failed:

| Requirement | What CropPath does |
| --- | --- |
| `https://` only, at most 2048 characters | `http://` is refused when the subscription is created or changed |
| no credentials (`user:password@`), no fragment (`#...`), no space or control character | refused at creation; a path and a query string are allowed (a query may carry your own token: CropPath's audit log keeps only the URL's host) |
| a host name (not `localhost`) or a public IP address | refused at creation |
| **every** address the host name resolves to is a public address | loopback, private (10/8, 172.16/12, 192.168/16, fc00::/7), link-local (169.254/16 including cloud metadata, fe80::/10), shared (100.64/10), reserved, documentation, multicast and unspecified addresses are refused; one private address among public ones is enough to refuse the name. Checked at creation and **again before every attempt** (`blocked_address`), and CropPath connects to the address it checked |
| a valid TLS certificate for the host name, from a publicly trusted CA | verified against CropPath's system trust store with the URL's host name; a self-signed or expired certificate or a name mismatch fails with `tls_error`. CropPath does not present a client certificate |
| answers directly, no redirect | a 3xx answer is a failed attempt (`http_status`) |
| answers 2xx within **10 seconds** | the 10 seconds cover connecting, the TLS handshake, sending and reading the answer (`timeout`) |
| accepts a JSON body of a few hundred bytes | the body is the event (section 1) |

CropPath does not use a proxy for deliveries. This guide does not list CropPath's outgoing IP addresses: authenticate
deliveries by their signature, not by their source address.

### Who creates the subscription

Subscriptions belong to a CropPath tenant (for example the packing house you work with). They can be managed by:

- a **tenant admin** in the admin console, or
- your integration through the API, with an **API token** of the role `tenant_admin`, or an **OAuth2 access token**
  of an API client with the role `tenant_admin` holding the scope `webhook_admin` (the scope is granted only by name).

Ask the tenant admin which way you will use. A token or role without that permission gets `403`.

### Create the subscription in the admin console

1. Sign in as a tenant admin and open **Settings → API tokens**. The **Webhooks** section is on that page.
2. Choose **Add webhook**.
3. Enter the **HTTPS address that receives the webhook**, tick the **Events to send**, and optionally a **Note**
   (one line, at most 200 characters, to recognise the receiving system).
4. Choose **Create webhook**. The **Secret** (`whsec_...`) appears once: choose **Copy secret**, hand it to the
   partner through a secure channel (or put it straight into your secret manager), then choose
   **I have stored the secret**. CropPath never shows it again.

The same section lists the subscriptions with their status and failures in a row, and has **Disable** / **Enable**,
**Replace secret** and **Delivery log** (the 50 newest deliveries, each with **Send again**). The console cannot edit
a subscription's URL or event types: use the API (`PATCH`, below).

### Create the subscription through the API

Get a token. With an OAuth2 API client, where your deployment offers them (`client_credentials` grant, tokens last
900 seconds):

```bash
curl -sS https://<host>/v1/oauth/token \
  -u "$CROPPATH_CLIENT_ID:$CROPPATH_CLIENT_SECRET" \
  -d grant_type=client_credentials -d scope=webhook_admin
# {"access_token": "ago_...", "token_type": "Bearer", "expires_in": 900, "scope": "webhook_admin"}
```

Or use an API token (`agt_...`) of the role `tenant_admin` that the tenant admin created for you. Then:

```bash
curl -sS https://<host>/v1/webhooks \
  -H "Authorization: Bearer $CROPPATH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://erp.partner.example/croppath/webhooks",
       "event_types": ["lot.sealed", "lot.recalled", "shipment.departed"],
       "description": "Partner ERP"}'
```

`201 Created` returns the subscription and its secret:

```json
{
  "subscription": {
    "id": 3, "url": "https://erp.partner.example/croppath/webhooks", "description": "Partner ERP",
    "event_types": ["lot.recalled", "lot.sealed", "shipment.departed"], "status": "active",
    "disabled_reason": null, "disabled_at": null, "consecutive_failures": 0,
    "created_by": "token:...", "created_at": 1790000000.5, "updated_at": 1790000000.5
  },
  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw3qdbLeXcY4o="
}
```

**The secret is shown once, in this response only** (`Cache-Control: no-store`; CropPath stores it encrypted and never
returns it again). Put it into your secret manager straight away; do not log it, commit it or send it by e-mail. If it
is lost, rotate it (section 6). `POST /v1/webhooks` refuses an `Idempotency-Key` header, because a replayed answer
could not contain the secret.

| Answer | `code` | Meaning |
| --- | --- | --- |
| `400` | `invalid_url` | the URL breaks a rule above, or its host does not resolve or resolves to a non-public address |
| `400` | `invalid_event_types` | not a non-empty list of distinct known types |
| `400` | `unknown_fields` | only `url`, `event_types` and `description` are accepted (you cannot choose the secret) |
| `409` | `subscription_limit_reached` | the tenant already has 20 subscriptions |
| `503` | `webhooks_unavailable` | the deployment has no key-encryption key configured; tell its operator |

Other operations (all with the same token):

| Operation | Request |
| --- | --- |
| list the tenant's subscriptions | `GET /v1/webhooks` |
| read one | `GET /v1/webhooks/{id}` |
| change URL, event types, description | `PATCH /v1/webhooks/{id}` with any of `url`, `event_types`, `description` |
| disable / enable | `PATCH /v1/webhooks/{id}` with `{"enabled": false}` / `{"enabled": true}` |
| replace the secret | `POST /v1/webhooks/{id}/rotate-secret` |
| delivery log, newest first | `GET /v1/webhooks/{id}/deliveries?status=failed&limit=50` (then `&cursor=<next_cursor>`) |
| redeliver one delivery | `POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` |

A changed URL is checked like a new one. New event types apply to events recorded after the change.

### Limits

- At most **20 subscriptions per tenant**, counting disabled ones. There is no delete operation (a subscription is
  disabled, so its delivery log stays): reuse a disabled subscription by changing its URL and event types and enabling
  it again.
- Another tenant's subscription or delivery answers `404`, like a missing one.

---

## 3. Verify every request

Anyone can send a `POST` to your URL. Verify every request before you trust or parse it. The algorithm:

1. **Take the raw request body bytes** exactly as received, before any JSON parsing. Do not parse and re-serialise:
   key order, spacing and escaping (`"Hữu Nghị"` versus `"H\u1eefu Ngh\u1ecb"`) change the bytes and break the
   signature.
2. **Read the three headers** `webhook-id`, `webhook-timestamp`, `webhook-signature`. If one is missing, refuse.
3. **Check the timestamp.** It must be Unix seconds (digits only). Refuse the request when
   `|now - webhook-timestamp| > 300` seconds (your clock against the timestamp, in both directions). This stops an
   attacker from replaying a captured request later.
4. **Build the signed content**: `{webhook-id}.{webhook-timestamp}.{raw body}` — the id, a dot, the timestamp exactly
   as received, a dot, then the body bytes.
5. **Build the key**: remove the `whsec_` prefix from the secret and **base64-decode** the rest. The key is the 32
   decoded bytes, not the text of the secret.
6. **Compute** HMAC-SHA256 of the signed content with that key, and base64-encode it (standard alphabet, with `=`
   padding).
7. **Compare** it with **each** space-separated entry of `webhook-signature`. Each entry is `version,signature`;
   consider only entries whose version is `v1`, and compare with a **constant-time** comparison. The request is
   genuine if any entry matches. (CropPath currently sends one entry; the header format allows several, so code for
   several.)
8. **Deduplicate** on `webhook-id`: if you have already accepted this id, answer 2xx and do not process it again.

Only then parse the JSON and act on it.

### Check your code with the test vector

[`webhook-test-vector.json`](webhook-test-vector.json) is a fixed delivery generated by the backend's own signing
function (a backend test fails if it ever drifts). Its secret is a published test value that no subscription uses.

| Field | Value |
| --- | --- |
| `secret` | `whsec_Y3JvcHBhdGgtd2ViaG9vay1kb2MtdGVzdC12ZWN0b3I=` |
| `webhook-id` | `evt_0123456789abcdef0123456789abcdef` |
| `webhook-timestamp` | `1790000003` (use it as "now", otherwise your replay check rightly refuses it) |
| body | the `body` string as UTF-8 bytes (`body_base64` holds the same 335 bytes) |
| expected `webhook-signature` | `v1,Fv2MoYYshrNynoX7zGaa1FDoMYExwnf8oKlHNObiReg=` |

Your verification must accept the vector, accept `signature_header_with_two_entries`, and refuse each `must_fail` case:
the body re-serialised with `\u` escapes, "now" one second outside the replay window, and the signature you would get
by using the secret text without base64-decoding it. Every sample in section 4 was run against these cases.

### Common mistakes

| Mistake | Effect | Do this instead |
| --- | --- | --- |
| Parsing the JSON and re-serialising it before verifying | the bytes differ, every signature fails | verify the raw bytes; parse afterwards |
| A framework body parser runs first (`express.json()`, a Pydantic model, a DTO or `Map` parameter in Spring, `[FromBody]` model binding) | you only get the parsed object, not the bytes | read the raw body: see the table below |
| Using the secret text as the key, or keeping the `whsec_` prefix | wrong key, every signature fails | strip `whsec_`, base64-decode, use the bytes |
| Comparing with `==` / `equals` / `strcmp` | leaks timing information about the expected signature | `hmac.compare_digest`, `crypto.timingSafeEqual`, `MessageDigest.isEqual`, `CryptographicOperations.FixedTimeEquals`, `hmac.Equal`, `hash_equals` |
| Skipping the timestamp check | a captured request can be replayed | refuse more than 300 seconds of difference |
| Comparing against the whole header | breaks as soon as the header carries more than one entry | split on spaces, keep `v1` entries, compare each |
| Decoding the body as text in another charset, or trimming a trailing newline | changes the bytes | keep the bytes as received (UTF-8) |
| Server clock out of sync | genuine requests refused as replays | run NTP on the receiving servers |
| Re-processing a repeated `webhook-id` | duplicate side effects (two goods-receipt postings) | deduplicate on `webhook-id` |
| Answering 2xx before verifying | forged events accepted | verify first, then answer |

How each sample reads the raw body:

| Stack | Raw body |
| --- | --- |
| Express | `express.raw({ type: "application/json" })` on the route, then `req.body` is a `Buffer` |
| Flask | `request.get_data()` |
| FastAPI | `await request.body()` (no Pydantic model parameter for the body) |
| Spring | a `@RequestBody byte[] body` parameter |
| JDK `HttpServer` | `exchange.getRequestBody().readNBytes(...)` |
| ASP.NET Core | copy `request.Body` into a `MemoryStream` (no model binding) |
| Go `net/http` | `io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))` |
| PHP | `file_get_contents('php://input')` |

---

## 4. Code samples

Each language has a verification function that uses only the standard library, then a minimal receiver. Where a
CropPath SDK has a verifier (Java, .NET, Go), its use comes first. The SDK packages are downloads of the developer
portal (`/developers/downloads`, each with a SHA-256 checksum). The TypeScript SDK has one too, `verifyWebhook`;
the Node.js sample below uses `node:crypto` only. The Python SDK (the IoT device SDK) has **no** webhook verifier: use
the standard-library code below.

Every sample receives the secret from the environment variable `CROPPATH_WEBHOOK_SECRET` (load it from your secret
manager), listens on `/croppath/webhooks`, answers `400` to a request that does not verify and `204` otherwise, and
keeps the ids it has seen in memory only to stay short: in production use a table with a unique key on `webhook-id`
and a durable queue (section 5).

How they were tested: each verification function was run against the test vector (accept it, accept the two-entry
header, refuse the three `must_fail` cases), and each receiver was started and sent a freshly signed delivery (2xx),
the same delivery again (2xx), a changed body (400), a timestamp 301 seconds old (400) and no headers (400).

### Python

Standard library only (tested with Python 3.11 and 3.12). `webhook_verify.py`:

```python
import base64
import binascii
import hashlib
import hmac
import time

REPLAY_WINDOW_S = 300  # seconds allowed between webhook-timestamp and your clock


def verify_webhook(secret, msg_id, timestamp, signature_header, body, now=None):
    """True when the delivery is authentic and fresh. `body` is the raw request body (bytes), never parsed JSON."""
    if not msg_id or not timestamp or not signature_header:
        return False
    if not (timestamp.isascii() and timestamp.isdigit()):
        return False
    now = time.time() if now is None else now
    if abs(now - int(timestamp)) > REPLAY_WINDOW_S:
        return False
    if not secret.startswith("whsec_"):
        raise ValueError("not a CropPath webhook secret (whsec_...)")
    key = base64.b64decode(secret[len("whsec_"):], validate=True)
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = hmac.new(key, signed, hashlib.sha256).digest()
    valid = False
    for entry in signature_header.split():
        version, _, signature = entry.partition(",")
        if version != "v1":
            continue
        try:
            given = base64.b64decode(signature, validate=True)
        except binascii.Error:
            continue
        if hmac.compare_digest(given, expected):  # constant time; check every entry
            valid = True
    return valid
```

A minimal receiver with Flask (`pip install flask`, run with `flask --app receiver_flask run`):

```python
import json
import os
import queue

from flask import Flask, request

from webhook_verify import verify_webhook

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
SECRET = os.environ["CROPPATH_WEBHOOK_SECRET"]  # whsec_..., loaded from your secret manager
events = queue.Queue()  # a worker takes events from here; use a durable queue in production
seen = set()  # production: a table with a unique key on webhook-id


@app.post("/croppath/webhooks")
def croppath_webhook():
    body = request.get_data()  # the raw bytes; never request.json before verifying
    h = request.headers
    if not verify_webhook(SECRET, h.get("webhook-id"), h.get("webhook-timestamp"), h.get("webhook-signature"), body):
        return "", 400
    event_id = h["webhook-id"]
    if event_id not in seen:  # a repeat is answered 2xx and not processed again
        seen.add(event_id)
        events.put(json.loads(body))
    return "", 204
```

The same with FastAPI (`pip install fastapi uvicorn`, run with `uvicorn receiver_fastapi:app`):

```python
import json
import os

from fastapi import FastAPI, Request, Response

from webhook_verify import verify_webhook

app = FastAPI()
SECRET = os.environ["CROPPATH_WEBHOOK_SECRET"]
events = []  # hand events to your queue instead
seen = set()


@app.post("/croppath/webhooks")
async def croppath_webhook(request: Request):
    body = await request.body()  # the raw bytes; do not declare a Pydantic model for this body
    h = request.headers
    if not verify_webhook(SECRET, h.get("webhook-id"), h.get("webhook-timestamp"), h.get("webhook-signature"), body):
        return Response(status_code=400)
    if h["webhook-id"] not in seen:
        seen.add(h["webhook-id"])
        events.append(json.loads(body))  # parse only after verifying
    return Response(status_code=204)
```

### Node.js

JavaScript ES modules, `node:crypto` only (tested with Node.js 22). `webhook-verify.mjs`:

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

const REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock

/** True when the delivery is authentic and fresh. `body` is the raw request body (a Buffer), never parsed JSON. */
export function verifyWebhook(secret, id, timestamp, signatureHeader, body, now = Date.now() / 1000) {
  if (!id || !timestamp || !signatureHeader) return false;
  if (!/^[0-9]+$/.test(timestamp)) return false;
  if (Math.abs(now - Number(timestamp)) > REPLAY_WINDOW_S) return false;
  if (!secret.startsWith("whsec_")) throw new Error("not a CropPath webhook secret (whsec_...)");
  const key = Buffer.from(secret.slice("whsec_".length), "base64");
  const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
  let valid = false;
  for (const entry of signatureHeader.split(" ")) {
    if (!entry.startsWith("v1,")) continue;
    const given = Buffer.from(entry.slice(3), "base64");
    // constant time; check every entry
    if (given.length === expected.length && timingSafeEqual(given, expected)) valid = true;
  }
  return valid;
}
```

A minimal receiver with Express (`npm install express`, tested with Express 5):

```javascript
import express from "express";
import { verifyWebhook } from "./webhook-verify.mjs";

const secret = process.env.CROPPATH_WEBHOOK_SECRET; // whsec_..., loaded from your secret manager
const seen = new Set(); // production: a table with a unique key on webhook-id
const app = express();

// express.raw keeps the body as bytes; never put express.json() in front of this route
app.post("/croppath/webhooks", express.raw({ type: "application/json", limit: "1mb" }), (req, res) => {
  const id = req.get("webhook-id");
  const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  if (!verifyWebhook(secret, id, req.get("webhook-timestamp"), req.get("webhook-signature"), body)) {
    res.sendStatus(400);
    return;
  }
  if (!seen.has(id)) {
    seen.add(id);
    const event = JSON.parse(body.toString("utf8")); // parse only after verifying
    setImmediate(() => handleEvent(event)); // answer first, process afterwards (use a queue in production)
  }
  res.sendStatus(204);
});

function handleEvent(event) {
  console.log(event.type, event.id);
}

app.listen(Number(process.env.PORT ?? 8080));
```

### Java

**With the CropPath Java SDK** (`vn.theio.croppath:croppath-sdk`, Java 17+): `WebhookVerifier` checks the headers, the
replay window (300 seconds by default, `.tolerance(...)` to change it) and every `v1` entry in constant time.

```java
import vn.theio.croppath.sdk.WebhookVerificationException;
import vn.theio.croppath.sdk.WebhookVerifier;

public final class SdkReceiver {
  static final WebhookVerifier VERIFIER =
      WebhookVerifier.builder(System.getenv("CROPPATH_WEBHOOK_SECRET")).build(); // default tolerance: 300 s

  /** The HTTP status to answer; {@code body} is the raw request body. */
  static int receive(String id, String timestamp, String signature, byte[] body) {
    try {
      VERIFIER.verify(id, timestamp, signature, body);
    } catch (WebhookVerificationException e) {
      return 400; // e.reason() says why; the exception never carries the secret
    }
    // deduplicate on id, queue the event, then answer
    return 204;
  }
}
```

**Without the SDK**, JDK only (tested with Java 17). `WebhookVerification.java`:

```java
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class WebhookVerification {
  static final long REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock

  /** True when the delivery is authentic and fresh; {@code body} is the raw request body, never parsed JSON. */
  public static boolean verify(String secret, String id, String timestamp, String signatureHeader, byte[] body,
      long nowSeconds) throws GeneralSecurityException {
    if (id == null || id.isEmpty() || timestamp == null || signatureHeader == null) return false;
    if (!timestamp.matches("[0-9]{1,12}")) return false;
    if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > REPLAY_WINDOW_S) return false;
    if (!secret.startsWith("whsec_")) throw new IllegalArgumentException("not a CropPath webhook secret");
    byte[] key = Base64.getDecoder().decode(secret.substring("whsec_".length()));
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
    byte[] expected = mac.doFinal(body);
    boolean valid = false;
    for (String entry : signatureHeader.trim().split(" +")) {
      if (!entry.startsWith("v1,")) continue;
      byte[] given;
      try {
        given = Base64.getDecoder().decode(entry.substring(3));
      } catch (IllegalArgumentException e) {
        continue;
      }
      if (MessageDigest.isEqual(expected, given)) valid = true; // constant time; check every entry
    }
    return valid;
  }
}
```

A minimal receiver with the JDK's built-in `HttpServer`:

```java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class Receiver {
  static final String SECRET = System.getenv("CROPPATH_WEBHOOK_SECRET"); // whsec_..., from your secret manager
  static final Set<String> SEEN = ConcurrentHashMap.newKeySet(); // production: a unique key on webhook-id
  static final ExecutorService WORKER = Executors.newSingleThreadExecutor(); // production: a durable queue

  public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/croppath/webhooks", Receiver::handle);
    server.start();
  }

  static void handle(HttpExchange exchange) throws java.io.IOException {
    try (exchange; InputStream in = exchange.getRequestBody()) {
      if (!"POST".equals(exchange.getRequestMethod())) {
        exchange.sendResponseHeaders(405, -1);
        return;
      }
      byte[] body = in.readNBytes(1 << 20); // the raw bytes, before any JSON parsing
      var h = exchange.getRequestHeaders();
      String id = h.getFirst("webhook-id");
      boolean valid;
      try {
        valid = WebhookVerification.verify(SECRET, id, h.getFirst("webhook-timestamp"),
            h.getFirst("webhook-signature"), body, System.currentTimeMillis() / 1000);
      } catch (Exception e) {
        valid = false;
      }
      if (!valid) {
        exchange.sendResponseHeaders(400, -1);
        return;
      }
      if (SEEN.add(id)) {
        WORKER.submit(() -> System.out.println("received " + id)); // parse and process the body here
      }
      exchange.sendResponseHeaders(204, -1);
    }
  }
}
```

With Spring Boot (tested with Spring Boot 3.5; put this class and `WebhookVerification` in your application's
package):

```java
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebhookController {
  private final String secret = System.getenv("CROPPATH_WEBHOOK_SECRET");
  private final Set<String> seen = ConcurrentHashMap.newKeySet(); // production: a unique key on webhook-id

  // byte[] keeps the raw body; a DTO or Map parameter would be parsed (and re-serialised) JSON
  @PostMapping("/croppath/webhooks")
  public ResponseEntity<Void> receive(
      @RequestHeader(name = "webhook-id", required = false) String id,
      @RequestHeader(name = "webhook-timestamp", required = false) String timestamp,
      @RequestHeader(name = "webhook-signature", required = false) String signature,
      @RequestBody byte[] body) throws Exception {
    if (!WebhookVerification.verify(secret, id, timestamp, signature, body, System.currentTimeMillis() / 1000)) {
      return ResponseEntity.badRequest().build();
    }
    if (seen.add(id)) {
      // queue the event; parse the body with your JSON library only now
    }
    return ResponseEntity.noContent().build();
  }
}
```

### C# / .NET

**With the CropPath .NET SDK** (`CropPath.Sdk`, .NET 8): `WebhookVerifier` checks the headers, the replay window
(300 seconds by default, the `tolerance` argument to change it) and every `v1` entry in constant time.

```csharp
using CropPath.Sdk;

public static class SdkReceiver
{
    static readonly WebhookVerifier Verifier =
        new(Environment.GetEnvironmentVariable("CROPPATH_WEBHOOK_SECRET")); // default tolerance: 300 s

    /// <summary>The HTTP status to answer; <paramref name="body"/> is the raw request body.</summary>
    public static int Receive(string? id, string? timestamp, string? signature, byte[] body)
    {
        try
        {
            Verifier.Verify(id, timestamp, signature, body);
        }
        catch (WebhookVerificationException)
        {
            return 400; // its Reason says why; it never carries the secret
        }
        // deduplicate on id, queue the event, then answer
        return 204;
    }
}
```

**Without the SDK**, base class library only (tested with .NET 8; the collection expression needs C# 12).
`WebhookVerification.cs`:

```csharp
using System.Security.Cryptography;
using System.Text;

public static class WebhookVerification
{
    const long ReplayWindowSeconds = 300; // allowed between webhook-timestamp and your clock

    /// <summary>True when the delivery is authentic and fresh; <paramref name="body"/> is the raw request body.</summary>
    public static bool Verify(string secret, string? id, string? timestamp, string? signatureHeader, byte[] body,
        long? nowSeconds = null)
    {
        if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(signatureHeader)) return false;
        if (timestamp.Length > 12 || !timestamp.All(char.IsAsciiDigit)) return false;
        long now = nowSeconds ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        if (Math.Abs(now - long.Parse(timestamp)) > ReplayWindowSeconds) return false;
        if (!secret.StartsWith("whsec_", StringComparison.Ordinal)) throw new ArgumentException("not a CropPath webhook secret");
        byte[] key = Convert.FromBase64String(secret["whsec_".Length..]);
        byte[] signed = [.. Encoding.UTF8.GetBytes(id + "." + timestamp + "."), .. body];
        byte[] expected = HMACSHA256.HashData(key, signed);
        bool valid = false;
        foreach (string entry in signatureHeader.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        {
            if (!entry.StartsWith("v1,", StringComparison.Ordinal)) continue;
            byte[] given;
            try { given = Convert.FromBase64String(entry[3..]); }
            catch (FormatException) { continue; }
            if (CryptographicOperations.FixedTimeEquals(expected, given)) valid = true; // constant time; check every entry
        }
        return valid;
    }
}
```

A minimal ASP.NET Core receiver (`Program.cs` of a `Microsoft.NET.Sdk.Web` project with implicit usings):

```csharp
using System.Collections.Concurrent;

var app = WebApplication.CreateBuilder(args).Build();
string secret = Environment.GetEnvironmentVariable("CROPPATH_WEBHOOK_SECRET")
    ?? throw new InvalidOperationException("CROPPATH_WEBHOOK_SECRET is not set"); // from your secret manager
var seen = new ConcurrentDictionary<string, bool>(); // production: a unique key on webhook-id

app.MapPost("/croppath/webhooks", async (HttpRequest request) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer); // the raw bytes; do not bind the body to a model before verifying
    byte[] body = buffer.ToArray();
    string? id = request.Headers["webhook-id"];
    if (!WebhookVerification.Verify(secret, id, request.Headers["webhook-timestamp"],
            request.Headers["webhook-signature"], body))
        return Results.BadRequest();
    if (seen.TryAdd(id!, true))
    {
        // queue the event (a Channel or a durable queue); parse the body with System.Text.Json only now
    }
    return Results.NoContent();
});

app.Run();
```

### Go

**With the CropPath Go SDK** (module `txng.theio.vn/sdk/go`, Go 1.22+, served only by the developer portal:
`go env -w GOPRIVATE=txng.theio.vn`, then `go get txng.theio.vn/sdk/go@v0.2.0`, as the SDK's README describes):

```go
package main

import (
	"io"
	"log"
	"net/http"
	"os"

	croppath "txng.theio.vn/sdk/go"
)

func main() {
	verifier, err := croppath.NewWebhookVerifier(os.Getenv("CROPPATH_WEBHOOK_SECRET")) // default tolerance: 300 s
	if err != nil {
		log.Fatal(err) // not a whsec_ secret
	}
	http.HandleFunc("POST /croppath/webhooks", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil || verifier.Verify(r.Header, body) != nil { // a *croppath.WebhookVerificationError says why
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		// deduplicate on r.Header.Get("webhook-id"), queue the event, then answer
		w.WriteHeader(http.StatusNoContent)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

**Without the SDK**, standard library only (tested with Go 1.22). `verify.go`:

```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const replayWindow = 300 // seconds allowed between webhook-timestamp and your clock

var unixSeconds = regexp.MustCompile(`^[0-9]{1,12}$`)

// verifyWebhook reports whether a delivery is authentic and fresh; body is the raw request body, never parsed JSON.
func verifyWebhook(secret, id, timestamp, signatureHeader string, body []byte, now time.Time) bool {
	if id == "" || signatureHeader == "" || !unixSeconds.MatchString(timestamp) {
		return false
	}
	ts, _ := strconv.ParseInt(timestamp, 10, 64)
	if skew := now.Unix() - ts; skew > replayWindow || skew < -replayWindow {
		return false
	}
	encoded, ok := strings.CutPrefix(secret, "whsec_")
	key, err := base64.StdEncoding.DecodeString(encoded)
	if !ok || err != nil {
		return false // not a CropPath webhook secret
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + timestamp + "."))
	mac.Write(body)
	expected := mac.Sum(nil)
	valid := false
	for _, entry := range strings.Fields(signatureHeader) {
		signature, isV1 := strings.CutPrefix(entry, "v1,")
		given, err := base64.StdEncoding.DecodeString(signature)
		if isV1 && err == nil && hmac.Equal(expected, given) { // constant time; check every entry
			valid = true
		}
	}
	return valid
}
```

A minimal receiver (`main.go` in the same package):

```go
package main

import (
	"io"
	"log"
	"net/http"
	"os"
	"sync"
	"time"
)

func main() {
	secret := os.Getenv("CROPPATH_WEBHOOK_SECRET") // whsec_..., from your secret manager
	var seen sync.Map                              // production: a unique key on webhook-id
	queue := make(chan []byte, 1000)               // production: a durable queue
	go func() {
		for body := range queue {
			log.Printf("received %d bytes", len(body)) // parse with encoding/json and process here
		}
	}()
	http.HandleFunc("POST /croppath/webhooks", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) // the raw bytes
		id := r.Header.Get("webhook-id")
		if err != nil || !verifyWebhook(secret, id, r.Header.Get("webhook-timestamp"),
			r.Header.Get("webhook-signature"), body, time.Now()) {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if _, repeat := seen.LoadOrStore(id, true); !repeat {
			queue <- body
		}
		w.WriteHeader(http.StatusNoContent)
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

### PHP

Core functions only, PHP 8 (`str_starts_with`; tested with PHP 8.3). `verify_webhook.php`:

```php
<?php
const CROPPATH_REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock

/** True when the delivery is authentic and fresh; $body is the raw request body, never decoded JSON. */
function croppath_verify_webhook(string $secret, ?string $id, ?string $timestamp, ?string $signatureHeader,
    string $body, ?int $now = null): bool
{
    if ($id === null || $id === '' || $signatureHeader === null || $timestamp === null) return false;
    if (!preg_match('/^[0-9]{1,12}$/D', $timestamp)) return false;
    if (abs(($now ?? time()) - (int) $timestamp) > CROPPATH_REPLAY_WINDOW_S) return false;
    if (!str_starts_with($secret, 'whsec_')) throw new InvalidArgumentException('not a CropPath webhook secret');
    $key = base64_decode(substr($secret, strlen('whsec_')), true);
    if ($key === false) throw new InvalidArgumentException('not a CropPath webhook secret');
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $body, $key, true));
    $valid = false;
    foreach (preg_split('/ +/', trim($signatureHeader)) as $entry) {
        if (str_starts_with($entry, 'v1,') && hash_equals($expected, substr($entry, 3))) {
            $valid = true; // hash_equals is constant time; check every entry
        }
    }
    return $valid;
}
```

A minimal receiver (`index.php`; with the built-in server: `php -S 0.0.0.0:8080 index.php`). PHP handles each
request in a fresh process, so it stores the event in an SQLite inbox table (`pdo_sqlite`) that also deduplicates:

```php
<?php
require __DIR__ . '/verify_webhook.php';

$secret = getenv('CROPPATH_WEBHOOK_SECRET'); // whsec_..., from your secret manager
$body = file_get_contents('php://input');    // the raw bytes; never json_decode before verifying
$id = $_SERVER['HTTP_WEBHOOK_ID'] ?? null;
if (!croppath_verify_webhook($secret, $id, $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? null,
        $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? null, $body)) {
    http_response_code(400);
    exit;
}
// Store first, answer, process later: the primary key on event_id makes a repeat a no-op.
$db = new PDO('sqlite:' . __DIR__ . '/inbox.sqlite');
$db->exec('CREATE TABLE IF NOT EXISTS inbox (event_id TEXT PRIMARY KEY, body TEXT NOT NULL, received_at INTEGER NOT NULL)');
$db->prepare('INSERT OR IGNORE INTO inbox (event_id, body, received_at) VALUES (?, ?, ?)')
   ->execute([$id, $body, time()]);
http_response_code(204); // a worker reads the inbox table and processes each event once
```

---

## 5. Responding and processing

- **Answer fast.** Verify, store the event (or put it on a queue), answer `2xx`, and do the real work afterwards.
  The 10-second limit covers the whole exchange; work that calls other systems belongs in a worker.
- **Be idempotent on `webhook-id`.** Store the id with a unique key in the same transaction that queues the event;
  if the insert finds the id already there, answer 2xx and stop. Then a retry, a redelivery or a duplicate never
  triggers the work twice. Do not mark an id as seen before the event is safely stored, or a crash in between loses it.
- **What to answer when verification fails:** a `4xx` (the samples use `400`). Do not answer 2xx to a request you
  refuse. Be aware of what CropPath does with it: every non-2xx answer is a **failed attempt**, so it is retried with
  the backoff above and counts towards the 50 failures in a row that disable the subscription. A genuine CropPath
  delivery that fails verification therefore means your configuration is wrong (usually the secret, see section 6):
  alert on a run of `400`s rather than letting the subscription be disabled.
- **What to answer when you cannot process now:** if you stored the event, answer 2xx and retry inside your system.
  If you could not store it, answer `5xx` (or `503`) and CropPath retries it.
- **Unknown event types:** answer 2xx and ignore them.
- **Fetch the full record when you need it.** Payloads carry ids, states and times only. Read the rest through the
  API with your token, for example `GET /v1/lots/{lot}` for a lot, or the public record of a lot by its `public_id`
  (see the API reference on the developer portal).
- **Do not trust the payload more than the signature allows.** It proves the event came from CropPath; still validate
  the fields you use (types, known enum values).

---

## 6. Rotating the secret

Rotation (`POST /v1/webhooks/{id}/rotate-secret`, or **Replace secret** in the console) **replaces the secret at
once**: the response (shown once, `no-store`) carries the new secret, and every attempt from then on, including retries
of older events, is signed with the new secret only. CropPath does not send a second signature with the old secret,
and there is no grace period on its side. The new secret is generated by CropPath, so you cannot install it before you
rotate.

Safe procedure:

1. **Before rotating**, make your receiver accept a list of secrets loaded from your secret manager at run time
   (without a redeploy). For example:

   ```python
   from webhook_verify import verify_webhook


   def verify_with_any(secrets, msg_id, timestamp, signature_header, body, now=None):
       """During a rotation: accept a delivery signed with any secret in `secrets` (the new one and the old one)."""
       return any(verify_webhook(s, msg_id, timestamp, signature_header, body, now) for s in secrets)
   ```

2. **Rotate**, and immediately add the new secret to the list, keeping the old one.
3. **Watch** the delivery log: new attempts verify with the new secret. An attempt that started just before the
   rotation can still arrive signed with the old secret, which is why the old one stays for a few minutes.
4. **After a few minutes** (one attempt lasts at most 10 seconds), remove the old secret from the list.

If your receiver can only hold one secret, the gap between the rotation and your deploy produces failed attempts
(`400` from your side). They are not lost: each is retried (after 1, 2, 4 ... minutes), so deploy the new secret
quickly, well within the 12 attempts and before 50 failures in a row disable the subscription.

Rotate when the secret may have leaked, when someone who knew it leaves, and on a regular schedule you choose.

---

## 7. Testing

### Without CropPath: send yourself a signed delivery

Point your receiver at the test secret from the vector, then send it a delivery signed the way CropPath signs (this
script reads `webhook-test-vector.json` from its own directory and uses the current time):

```python
"""Sends one signed test delivery to your receiver, the way CropPath signs it. Usage:
    CROPPATH_WEBHOOK_SECRET=whsec_... python send_test_delivery.py http://localhost:8080/croppath/webhooks"""
import base64
import hashlib
import hmac
import json
import os
import sys
import time
import urllib.error
import urllib.request

url, secret = sys.argv[1], os.environ["CROPPATH_WEBHOOK_SECRET"]
vector = json.load(open(os.path.join(os.path.dirname(__file__), "webhook-test-vector.json"), encoding="utf-8"))
body = vector["body"].encode("utf-8")
msg_id, timestamp = vector["headers"]["webhook-id"], str(int(time.time()))
key = base64.b64decode(secret[len("whsec_"):])
signature = base64.b64encode(hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest())
request = urllib.request.Request(url, data=body, method="POST", headers={
    "Content-Type": "application/json", "webhook-id": msg_id, "webhook-timestamp": timestamp,
    "webhook-signature": "v1," + signature.decode(),
})
try:
    with urllib.request.urlopen(request, timeout=10) as response:
        print(response.status)  # 2xx: your receiver accepted it
except urllib.error.HTTPError as e:
    print(e.code)  # 4xx/5xx: CropPath would count this attempt as failed and retry it
```

`204` (or another 2xx) means your receiver verified and accepted it. Send it twice to check that the repeat is
answered 2xx and not processed twice.

### Against the hosted sandbox

The hosted sandbox at `https://sandbox-txng.theio.vn` is a separate CropPath server that holds test data only. One
request gives you a test company of your own and an API token for it (role `tenant_admin`, valid 24 hours); within a
few minutes the company holds the demo data, a shipped lot among it. The developer portal's sandbox guide
(`/developers/guides/sandbox`) lists its limits. Webhooks work there as on the live service.

There is **no test or ping event**: to get a delivery, make a real change happen. The sandbox applies every URL rule of
section 2, so your receiver needs a public `https://` address with a valid certificate (for example a tunnel to your
machine); `localhost` and private addresses are refused.

1. Check your verification code against the test vector first ([section 3](#check-your-code-with-the-test-vector)).
2. Create a sandbox account and keep its `api_token` (it is shown once):

   ```bash
   curl -sS -X POST https://sandbox-txng.theio.vn/v1/sandbox/accounts
   # {"tenant_id": "sbx-...", "api_token": "agt_...", "expires_at": ..., "base_url": "https://sandbox-txng.theio.vn"}
   TOKEN=agt_...
   ```

3. Register your endpoint, then store the `secret` of the answer in your receiver:

   ```bash
   curl -sS https://sandbox-txng.theio.vn/v1/webhooks -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"url": "https://<your public receiver>/croppath/webhooks", "event_types": ["lot.recalled"]}'
   ```

4. Find the demo lot: its code ends with the first 12 characters of your `tenant_id` after `sbx-`, in capitals
   (for `sbx-6kvlw4zwnirazpgy` it is `LO-260928-014-6KVLW4ZWNIRA`). The demo data is added over a few minutes, and the
   lot is listed before that ends: wait until the list shows it with the status `shipped` before you change anything, because
   recalling it earlier stops the demo data from being added. Then recall the lot, which records a `lot.recalled` event:

   ```bash
   curl -sS "https://sandbox-txng.theio.vn/v1/lots?limit=10" -H "Authorization: Bearer $TOKEN"
   curl -sS https://sandbox-txng.theio.vn/v1/lots/<lot code>/recall -H "Authorization: Bearer $TOKEN" \
     -H "Content-Type: application/json" -d '{"kind": "recall", "reason": "quality", "scope": "consumer"}'
   ```

5. Within seconds your receiver gets the delivery. It verifies the signature with the secret of step 3 (section 3) and
   answers 2xx. The delivery log shows what CropPath recorded (`<id>` is the subscription's `id` from step 3):

   ```bash
   curl -sS "https://sandbox-txng.theio.vn/v1/webhooks/<id>/deliveries" -H "Authorization: Bearer $TOKEN"
   ```

A lot can be recalled or withdrawn once; to get the event again, redeliver it (below) or create a new sandbox account.
The sandbox deletes each test company, its subscriptions and their deliveries 7 days after the account was created.

### Redeliver and the delivery log

The delivery log (`GET /v1/webhooks/{id}/deliveries`, or **Delivery log** in the console) shows each delivery's
`status` (`pending`, `delivered`, `failed`), `attempts`, `last_status` (your last HTTP answer), `last_error` (section
8), and times in Unix seconds. Filter with `?status=failed`; page with `limit` (1 to 200, default 50) and `cursor`.

`POST /v1/webhooks/{id}/deliveries/{delivery}/redeliver` (console: **Send again**) queues a delivered or failed delivery
again, due at once, with a fresh set of 12 attempts. It answers `409` with the `code` `subscription_disabled` while the
subscription is disabled, or `delivery_is_pending` while the delivery is still pending (it will be attempted at its next
attempt time). A redelivery carries the **same `webhook-id`**: a receiver that already stored that id answers 2xx and
skips it, which is what you want for a missed event. To have it processed again, remove the id from your store first.

---

## 8. Troubleshooting

`last_error` in the delivery log says why the last attempt failed:

| `last_error` | Cause | Fix |
| --- | --- | --- |
| `http_status` | your endpoint answered something other than 2xx (`last_status` has the code): a 4xx from failed verification, a 3xx redirect, a 5xx error | `400`/`401`/`403`: check the secret and the raw-body handling (section 3); `3xx`: register the final URL (e.g. the `https://` one, with or without the trailing slash your server wants); `404`/`405`: check the path and that it accepts `POST`; `5xx`: check your server logs |
| `blocked_address` | the host resolved, at send time, to at least one address that is not public | publish only public A/AAAA records for that name; do not use a split-horizon name that answers private addresses |
| `dns_failure` | the host name did not resolve | fix the DNS record; check that it resolves from the public internet |
| `invalid_url` | the stored URL no longer passes the URL rules | `PATCH` a valid `https://` URL |
| `connect_failed` | no TCP connection (refused, unreachable, reset) | open the port (443 or the one in the URL) to the internet; check firewalls and that the server is up |
| `tls_error` | the TLS handshake failed | install a certificate from a public CA, valid, not expired, for exactly the URL's host name, with the full chain |
| `timeout` | no complete answer within 10 seconds (connect, TLS, send and read included) | answer first, process asynchronously (section 5); check slow TLS or network paths |
| `protocol_error` | the connection closed or the answer was not valid HTTP | check your server or load balancer; it must speak HTTP/1.1 over TLS |
| `secret_unavailable` | CropPath could not decrypt the subscription's secret (a deployment key problem); this does not count towards disabling | tell the deployment's operator; after they fix it, rotate the secret |
| `subscription_disabled` | the subscription was disabled (by an admin or after 50 failures in a row) while the delivery was pending | fix the cause, enable the subscription, redeliver |
| `internal_error` | an error inside CropPath | retried automatically; report it if it persists |

Errors when creating or changing a subscription: see the table in section 2.

### A disabled subscription

`GET /v1/webhooks/{id}` shows `status: disabled` with `disabled_reason` `failures` (50 failed attempts in a row) or
`manual` (an admin turned it off). To recover:

1. Fix the endpoint (check `last_error` of the latest deliveries) and test it (section 7).
2. Enable it: console **Enable**, or

   ```bash
   curl -sS -X PATCH https://<host>/v1/webhooks/3 -H "Authorization: Bearer $CROPPATH_TOKEN" \
     -H "Content-Type: application/json" -d '{"enabled": true}'
   ```

   This resets `consecutive_failures` to 0. New events are recorded again from now on.
3. Redeliver the `failed` deliveries you need (`?status=failed`), within 30 days.
4. Read through the API what changed while it was disabled: no events were recorded for it in that period.

### My signatures never match

Run your verification against the test vector (section 3). If it passes there but not on real traffic, something
changes the body before your code sees it (a body parser, a proxy that re-encodes or decompresses, a framework that
trims), or you use another subscription's secret (each subscription has its own).

---

## 9. Security checklist

- [ ] The endpoint is `https://` with a valid public certificate and answers `POST` only.
- [ ] Every request is verified before anything else: raw body bytes, `whsec_` stripped and base64-decoded key,
      HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, every `v1` entry, constant-time comparison.
- [ ] Requests with a timestamp more than 300 seconds from your clock are refused; the servers run NTP.
- [ ] A request that does not verify gets a 4xx and is not processed; a run of them raises an alert.
- [ ] Processing is idempotent on `webhook-id`, enforced by a unique key, and the event is stored before you answer 2xx.
- [ ] The 2xx answer comes within 10 seconds; the work runs in a worker.
- [ ] The secret lives in a secret manager, never in source code, logs, tickets or e-mail; each subscription has its
      own; a rotation procedure is written down (section 6).
- [ ] Logs carry `webhook-id` and the outcome, never the secret or the signature.
- [ ] The request body size is limited (the samples allow 1 MiB; events are a few hundred bytes).
- [ ] Payload fields are validated before use; unknown event types and enum values are tolerated.
- [ ] Anything beyond the payload is read through the API with a least-privilege token.
- [ ] Someone watches the subscription's `status` and the delivery log for failures.
