# Webhooks

Get a signed HTTP POST the moment BasketBooster detects something about your
customers: a loyal buyer slipping to at-risk, a repeat-bought product coming
due, or a predicted order that never arrived. Point a webhook at Zapier, Make,
n8n, your own backend or the WooCommerce plugin, and let *your* tools send
the win-back email or create the coupon. A webhook tells you who to talk to
and why. It carries no email address: you match `customer_id` to the address
in your own system. To have BasketBooster send the emails for you instead,
see [Email Flows](email-flows.md).

Webhooks are managed in the dashboard (**Webhooks** in the settings menu) or
through `/account/webhooks` with your secret API key (`X-API-Key`). Up to 5
endpoints per account.

## Event types

Customer events need the **Customer Intelligence** feature on your plan. They
are produced by the nightly refresh (see the [Customer Intelligence Feed](customer-feed.md)),
so expect a burst once a day, not a trickle.

| type | fires when |
|---|---|
| `customer.became_at_risk` | a customer entered the at-risk segment from a non-drifting one (win-back trigger) |
| `customer.predicted_order_missed` | the predicted next order date passed 7 days ago with no order (once per predicted date) |
| `customer.replenishment_due` | a product the customer buys regularly entered the due list (once per product) |
| `customer.segment_changed` | any move between RFM segments; `data.value_drop` marks a move from champion/loyal to at_risk/hibernating/lost |
| `customer.churn_threshold_crossed` | churn risk rose through 0.5 or 0.8 |
| `customer.reactivated` | a drifting customer placed a new order |
| `customer.new_champion` | a customer reached the champions segment |
| `ping` | the "Send test" button in the dashboard |

Subscribe to specific types or to `*` (everything).

## Payload

One POST carries one event type. In `batch` mode (default) up to 100 events
share a POST; in `single` mode every event is its own POST (handy for Zapier
"Catch Hook" steps that expect one record per call).

```json
{
  "id": "6a1c0f3e-…",
  "type": "customer.became_at_risk",
  "api_version": "2026-10",
  "created_at": "2026-10-26T03:12:40+00:00",
  "account_id": "…",
  "data": {
    "events": [
      {
        "id": 8812,
        "type": "became_at_risk",
        "customer_id": "1042",
        "run_date": "2026-10-26",
        "occurred_at": "2026-10-26T03:12:40+00:00",
        "revenue": 1840.5,
        "data": {"from": "loyal", "churn_risk": 0.61, "clv_12m": 2210.0, "last_order_at": "2026-08-30T10:11:12+00:00"},
        "customer": {
          "customer_id": "1042",
          "segment": "at_risk",
          "prev_segment": "loyal",
          "churn_risk": 0.61,
          "revenue": 1840.5,
          "predicted_next_order_at": "2026-10-11",
          "recommendations": [{"id": "SKU-9", "title": "…", "product_url": "…", "image_url": "…", "price": 25.0}],
          "replenishment_due": [{"item_id": "SKU-3", "due_date": "2026-10-31", "expected_every_days": 41, "product": {"id": "SKU-3", "title": "…", "product_url": "…"}}]
        }
      }
    ]
  }
}
```

`customer` is the customer's current profile, the same row the
[feed](customer-feed.md) returns, so a reminder email needs no second call.
`customer_id` is the id your store gave the customer (the WooCommerce user id
for the Woo plugin); match it to the email in your own system.

## Headers and signature

| header | value |
|---|---|
| `X-BasketBooster-Event` | the event type |
| `X-BasketBooster-Delivery` | delivery id; use it as an idempotency key, since retries reuse it |
| `X-BasketBooster-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |
| `User-Agent` | `BasketBooster-Webhooks/1` |

The signature is `HMAC-SHA256(secret, "<t>." + raw_body)` with the endpoint's
secret (shown once when you create or rotate it). Verify against the **raw**
request body, compare in constant time, and reject timestamps older than
5 minutes:

```python
import hmac, hashlib, time

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

```php
function bbr_verify(string $secret, string $body, string $header, int $tolerance = 300): bool {
    $parts = [];
    foreach (explode(',', $header) as $p) { [$k, $v] = explode('=', $p, 2); $parts[$k] = $v; }
    if (abs(time() - (int) $parts['t']) > $tolerance) return false;
    $expected = hash_hmac('sha256', $parts['t'] . '.' . $body, $secret);
    return hash_equals($expected, $parts['v1'] ?? '');
}
```

Answer with any 2xx within 10 seconds. Anything else, including a timeout,
counts as a failure.

## Retries

Failed deliveries are retried after 1 min, 5 min, 30 min, 2 h, 6 h and 24 h,
then marked **dead**. The dashboard shows every delivery with its status, HTTP
code and last error, and lets you redeliver one by hand. After 20 consecutive
failures an endpoint is switched off (`disabled_reason: "failing"`); fix the
receiver and re-enable it from the dashboard.

## Receiver requirements

- `https://` only, no credentials in the URL, and the host must resolve to a
  public address (private networks, localhost and `.internal` hosts are
  rejected).
- Redirects are not followed.
- Responses are read up to 64 KB; the body is ignored.

## Managing endpoints with the API

| call | purpose |
|---|---|
| `GET /account/webhooks` | list endpoints (secrets masked) |
| `POST /account/webhooks` `{url, event_types, description?, delivery_mode?}` | create; the response carries `secret` once |
| `PUT /account/webhooks/{id}` | change URL / types / mode / `enabled` |
| `DELETE /account/webhooks/{id}` | remove |
| `POST /account/webhooks/{id}/rotate-secret` | new secret (returned once) |
| `POST /account/webhooks/{id}/test` | queue a `ping` |
| `GET /account/webhooks/{id}/deliveries?status=` | delivery log |
| `POST /account/webhooks/{id}/deliveries/{did}/redeliver` | retry one delivery |
| `GET /account/webhooks/event-types` | the registry with `entitled` per type |

All with `X-API-Key: <secret key>` (the dashboard uses the same endpoints).

## Prefer polling?

The same events are available as a pull feed: `GET /customers/events?after_id=…`
(see the [Customer Intelligence Feed](customer-feed.md)). Stores without a
public URL (staging, local dev, basic-auth) poll instead.
