# Receiving webhooks

Path: `/guide/receiving-webhooks`
Summary: Building a receiver that survives retries and out-of-order delivery

The [webhooks catalog](/guide/webhooks) tells you *which* events to subscribe to. This page
is about the other half — building a **receiver** that stays correct when deliveries retry,
arrive out of order, or arrive twice. Getting this wrong is the most common source of
duplicated fulfillments and missed orders.

## Subscribe

**Endpoint: Subscribe to webhook events** — `POST /webhook/` (operationId: subscribeWebhook)

Your `url` must be **HTTPS** and the `method` is `POST`. Narrow the firehose with
`warehouse_id`, `merchant_id` and `merchant_channel_id` filters, and list only the event
types you handle in `allowed_types`.

**Example (cURL):**

```bash
curl -X POST {{baseUrl}}/webhook/ \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
  "url": "https://your-domain.com/webhooks/pulpo",
  "method": "POST",
  "warehouse_id": 140,
  "merchant_id": 69,
  "merchant_channel_id": 76,
  "allowed_types": ["packing_order_finished", "sales_order_finished"]
}'
```

## The four rules

PULPO's own delivery contract asks receivers to do four things. Treat them as
non-negotiable.

> **WARNING: 1 · Return 200 quickly, process asynchronously**
>
> Acknowledge with `200` as soon as you've *durably stored* the event (e.g. enqueued it).
> Do all real work — API calls, DB writes, label generation — after responding. Slow handlers
> cause timeouts, which cause retries, which cause duplicate processing.

> **WARNING: 2 · Be idempotent — deliveries retry**
>
> The same event may arrive more than once. Compute a stable key from the event and skip
> anything you've already handled. A good key is `type` + the entity id in `data`
> (e.g. `sales_order_finished:<data.sales_order_id>`). Store handled keys and dedupe on write.

> **WARNING: 3 · Handle out-of-order delivery**
>
> Ordering is **not** guaranteed. You might see `sales_order_finished` before
> `packing_order_finished`. Don't build logic that assumes a sequence. Treat each event as a
> *hint that something changed*, then re-fetch the authoritative state from the API (e.g.
> `GET /sales/orders/{id}`) before acting on it.

> **WARNING: 4 · Verify authenticity**
>
> Only act on events you can trust. If PULPO issues a signing secret for your subscription,
> verify it on every request; confirm the exact mechanism (header name and algorithm) with
> your onboarding contact. At minimum, use an unguessable receiver path or a shared secret you
> check on arrival, and reject anything that fails.

## A receiver that follows all four

```js
import express from "express";
const app = express();
const seen = new Set(); // back this with Redis/DB in production

app.post("/webhooks/pulpo", express.json(), async (req, res) => {
  // 4 — verify authenticity (shared secret shown; use PULPO's signature if provided)
  if (req.get("x-webhook-secret") !== process.env.PULPO_WEBHOOK_SECRET) {
    return res.sendStatus(401);
  }

  const event = req.body;                       // { type, data, ... }
  const key = `${event.type}:${event.data?.sales_order_id ?? event.data?.id}`;

  // 2 — idempotency: ignore repeats
  if (seen.has(key)) return res.sendStatus(200);
  seen.add(key);

  // 1 — acknowledge fast, then process out of band
  res.sendStatus(200);
  queue.push(event); // 3 — the worker re-fetches authoritative state before acting
});
```

## Payload shape

Every delivery is a JSON object with a `type` (one of the subscribed `allowed_types`) and a
`data` object carrying the full event data. The richest payloads — the packing and
shipment-tracking events used by label providers — are documented field-by-field on the
[label-provider webhooks](/label-provider/webhooks) page.

**Webhook event:&#x20;**`sales_order_finished`

Fired when a sales order completes (PGI). Re-fetch the order to read its authoritative
final state before you mark anything shipped on your side.

Sample payload:

```json
{
  "type": "sales_order_finished",
  "data": {
    "sales_order_id": 12345,
    "order_num": "SO-2024-001",
    "state": "ended"
  }
}
```

> **TIP: Not receiving anything?**
>
> Check the subscription filters first — a `warehouse_id` / `merchant_id` that doesn't match
> the order silently excludes its events. The receiver URL must be publicly reachable over
> HTTPS. See [idempotency & retries](/guide/idempotency) for how PULPO retries failed
> deliveries.

---

Website version: https://connect.pulpo.co/guide/receiving-webhooks
Whole guide in one file: https://connect.pulpo.co/llms-full.txt
Index of all pages: https://connect.pulpo.co/llms.txt
