> For the complete documentation index, see [llms.txt](https://docs.terminal.africa/tship/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.terminal.africa/tship/miscallaneous/webhook-events/handling-webhook-events.md).

# Handling Webhook Events

Verify webhook signatures and process pickup event versions safely.

### Receive Pickup Events in Node.js

Terminal signs the exact request body with HMAC-SHA512 using your `SECRET_KEY`. Verify `X-Terminal-Signature` before accepting the event. Preserve the raw body before any JSON middleware changes it.

```javascript
const express = require("express");
const crypto = require("crypto");
const app = express();
const SECRET_KEY = process.env.TERMINAL_SECRET_KEY;

function verifySignature(rawBody, signature) {
    if (!Buffer.isBuffer(rawBody) || typeof signature !== "string" ||
        !/^[a-f0-9]{128}$/i.test(signature)) return false;
    const expected = crypto.createHmac("sha512", SECRET_KEY)
        .update(rawBody).digest();
    return crypto.timingSafeEqual(expected, Buffer.from(signature, "hex"));
}

// Register this route before app-wide express.json() middleware.
app.post("/webhooks/terminal", express.raw({ type: "application/json" }),
    async (req, res) => {
        if (!verifySignature(req.body, req.get("X-Terminal-Signature"))) {
            return res.sendStatus(401);
        }
        let payload;
        try { payload = JSON.parse(req.body.toString("utf8")); }
        catch (_) { return res.sendStatus(400); }

        if (!payload.event?.startsWith("pickup.")) {
            // Route other subscribed resource events to their own handler.
            return res.sendStatus(200);
        }
        if (!payload.event_id || !payload.data?.pickup_id ||
            !Number.isSafeInteger(payload.data.version)) {
            return res.sendStatus(400);
        }
        try {
            // Your durable inbox: a unique event_id makes duplicate acceptance safe.
            // Process this inbox asynchronously after it is committed.
            await inbox.storeUnique(payload.event_id, payload);
            return res.sendStatus(200);
        } catch (_) {
            return res.sendStatus(503);
        }
    });
```

`inbox.storeUnique` represents your application's persistent storage; implement it in your database. Duplicate event IDs should count as accepted rather than causing an error. A webhook receiver should acknowledge only after durable acceptance; customer notifications are processed asynchronously.

### Pickup Identity, Ordering and Recovery

Pickup webhooks include `event_id`, `occurred_at`, `event` and `data`. Deduplicate deliveries and replays on `event_id`. Store the highest `data.version` applied for each `data.pickup_id`, and ignore equal or smaller versions. Perform the version check, state update and notification scheduling atomically, including when multiple workers process your inbox.

Use `data.next_action` to choose the customer's next step. `pickup.failed` with `next_action: "wait"` is being recovered by Terminal; a later `pickup.booked` confirms the replacement. Terminal cancellation with `next_action: "dropoff"` requires hub handover. Refund outcome is separate from collection outcome.

Replays retain the original event ID, version and snapshot. Reconcile uncertain or missing notifications with `GET /v1/pickups/:pickup_id`; it returns the latest version and recovery instructions. See [Pickup Workflow](/tship/guides/pickup-workflow.md) for the retry and drop-off flow.

Other resource events retain the envelope documented in [Sample Webhook Event Payloads](/tship/miscallaneous/sample-webhook-event-payloads.md). The same raw-body signature check applies to every event.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.terminal.africa/tship/miscallaneous/webhook-events/handling-webhook-events.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
