# Customer Intelligence Feed

Pull per-customer segments, churn risk, predicted next order dates, lifetime
value and **personalized product recommendations** into your email or CRM tool:
Klaviyo, Mailchimp, Brevo, or your own automation. BasketBooster works out the
personalization and your email tool does the sending. If you would rather
have BasketBooster send the emails through your own provider account, use
[Email Flows](email-flows.md).

Requires the **Customer Intelligence** feature on your plan. All endpoints use
your secret API key (dashboard, API Keys page) in the `X-API-Key` header. Never
use the publishable `pk_` key here, and never call these endpoints from a
browser.

Data refreshes nightly from your order history and the recommendation engine.
Only identified customers participate (orders that carried a customer id);
anonymous sessions are never profiled.

## Endpoints

### `GET /customers/summary`

Segment counts and revenue totals, the same numbers as the dashboard page.

### `GET /customers/export`

The batch feed. Parameters:

| param | meaning |
|---|---|
| `segment` | filter: `champions`, `loyal`, `promising`, `new`, `at_risk`, `hibernating`, `lost` |
| `updated_since` | ISO datetime; incremental syncs pull only rows refreshed since your last run |
| `due_replenishment` | `true` returns only customers with a repeat-purchase item due (replenishment reminders) |
| `q` | the customer id contains this text. Case does not matter, and `%` and `_` are plain characters here |
| `min_churn` / `max_churn` | churn risk between 0 and 1. `min_churn=0.5` keeps customers at 50 % risk or above |
| `min_orders` / `max_orders` | order count band: `min_orders=2&max_orders=3` keeps customers with 2 or 3 orders; either bound alone is open-ended |
| `min_revenue` | at least this much lifetime revenue |
| `inactive_days` | no order in the last N days. `inactive_days=90` is the usual win-back cut |
| `sort` | `revenue` (default) · `orders` · `last_order` · `next_order` · `churn_risk` · `clv` · `prediction_accuracy` · `segment` · `customer_id` |
| `order` | `asc` / `desc`; defaults to the column's natural direction (money, scores and dates newest/richest first; labels A to Z). Rows without the value sort last either way |
| `limit` / `offset` | paging, `limit` ≤ 500 |

Filters combine, so a customer has to pass every one you set. The response echoes `sort` and `order` next to `total`, `limit` and `offset`, and `total` counts the filtered rows.

Some pulls you will probably want:

| goal | call |
|---|---|
| win-back list: repeat buyers silent for 3 months, most valuable first | `/customers/export?inactive_days=90&min_orders=2&sort=clv` |
| one-time buyers at 50 to 75 % churn risk | `/customers/export?max_orders=1&min_churn=0.5&max_churn=0.75` |
| VIPs slipping away | `/customers/export?segment=at_risk&min_revenue=500` |
| everyone past the 50 % churn mark | `/customers/export?min_churn=0.5&sort=revenue` |
| replenishment reminders due today | `/customers/export?due_replenishment=true` |
| one customer by (part of) their id | `/customers/export?q=1042` |

The Customers page in the dashboard uses the same parameters. Whatever you
narrow down there, you can pull here.

Each row:

```json
{
  "customer_id": "1042",
  "segment": "at_risk",
  "prev_segment": "loyal",
  "segment_since": "2026-10-24",
  "rfm": {"r": 2, "f": 4, "m": 5},
  "orders": 12,
  "revenue": 1840.5,
  "aov": 153.4,
  "last_order_at": "2026-06-02T10:11:12+00:00",
  "median_interval_days": 42.0,
  "predicted_next_order_at": "2026-07-14",
  "churn_risk": 0.74,
  "clv_12m": 2210.0,
  "prediction_accuracy": {
    "scored": 8, "on_time": 6, "hit_rate": 0.75, "mae_days": 6.4,
    "last_outcome": "late", "last_error_days": 19
  },
  "recommendations": [
    {"id": "SKU-9", "title": "…", "product_url": "…", "image_url": "…", "price": 25.0}
  ],
  "replenishment_due": [
    {"item_id": "SKU-3", "last_bought": "2026-06-20", "expected_every_days": 41, "due_date": "2026-07-31",
     "product": {"id": "SKU-3", "title": "…", "product_url": "…", "image_url": "…", "price": 12.0}}
  ]
}
```

`recommendations` are computed per customer by your store's recommendation
engine, so they can go straight into a "picked for you" email block.
`replenishment_due` is the "they buy this every ~6 weeks; it's week 7" trigger.

### `GET /customers/{customer_id}`

One customer's profile. Useful at checkout or account pages via your backend.

### `GET /customers/events`: the change feed

What moved since your last pull, one row per detected change, oldest first.
Poll it instead of diffing `/export` yourself.

| param | meaning |
|---|---|
| `after_id` | cursor: the `next_after_id` from your previous pull (recommended; nothing is missed when a night is skipped) |
| `since` | ISO datetime alternative to the cursor |
| `type` | comma-separated filter: `became_at_risk,replenishment_due,…` (list below) |
| `customer_id` | one customer's history |
| `include=customer` | attach the customer's current profile + product cards to each event |
| `limit` | ≤ 500 |

```json
{
  "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},
      "customer": { "…the /export row…" }
    }
  ],
  "next_after_id": 8812,
  "has_more": false
}
```

Event types (all computed by the nightly refresh by comparing with the
previous night, so a first run never produces events):

| type | meaning | `data` |
|---|---|---|
| `became_at_risk` | entered at_risk from a non-drifting segment (the win-back trigger) | `from`, `churn_risk`, `clv_12m`, `last_order_at` |
| `predicted_order_missed` | predicted next order + 7 days passed with no order (once per predicted date) | `predicted_next_order_at`, `days_late`, `median_interval_days` |
| `replenishment_due` | a repeat-bought item entered the due list (once per item) | the replenishment entry (`item_id`, `due_date`, `expected_every_days`, `last_bought`) |
| `segment_changed` | any segment move | `from`, `to`, `value_drop` |
| `churn_threshold_crossed` | churn risk rose through 0.5 / 0.8 | `threshold`, `from`, `to` |
| `reactivated` | a drifting customer ordered again | `from`, `to`, `days_silent` |
| `new_champion` | reached champions | `from`, `orders`, `revenue` |

Events are kept for 90 days. The same events can be **pushed** to you; see
[Webhooks](webhooks.md).

### `GET /customers/prediction-accuracy`

How often the predicted next order date turned out right over the last year.
Every prediction is kept and checked against the order that came after it.
Not metered.

```json
{
  "window_days": 365,
  "scored": 1240, "live_scored": 310,
  "on_time": 702, "early": 180, "late": 214, "overdue": 144,
  "hit_rate": 0.566, "resolved_hit_rate": 0.639,
  "mae_days": 11.2, "median_error_days": 2.0,
  "baseline_hit_rate": 0.41, "baseline_mae_days": 19.8
}
```

- `hit_rate` counts customers who never came back (`overdue`) as misses.
  `resolved_hit_rate` only looks at predictions where the customer did order again.
- `mae_days` is the average miss in days. `median_error_days` above 0 means
  orders tend to come later than predicted.
- `baseline_*` scores a simple guess on the same predictions: the last order
  plus your store's typical gap. If the per-customer numbers are not better
  than this, the prediction is not adding much for your store yet.
- `live_scored` is how many predictions were made live. The rest were
  rebuilt from order history the first time a customer was seen, so you get
  numbers from day one.

### `GET /customers/alerts?days=7`

The dashboard's "what changed" strip: per event type, how many customers,
how much lifetime revenue they represent and a few sample ids. Not metered.

## Field meanings (honest definitions)

- **rfm** holds quintiles (1 to 5, 5 best) of recency, frequency and monetary
  value within *your* store's customer distribution.
- **churn_risk** compares days since the last order with twice the customer's
  usual inter-order gap, clamped to 0 to 1. A heuristic, not a model.
- **predicted_next_order_at** is the last order plus the customer's median gap.
- **prediction_accuracy** is how this customer's past predicted dates held up.
  A prediction counts as on time when the next order came within 7 days of
  the predicted date, or within a quarter of the customer's usual gap when
  that is longer. `scored` counts the predictions that can be judged, and a
  customer who is past the window without ordering counts as a miss.
  `last_outcome` is `on_time`, `early`, `late` or `overdue` (no order yet).
  `last_error_days` above 0 means later than predicted; for `overdue` it is
  the days since the predicted date.
- **clv_12m** is the 12-month revenue run-rate damped by churn risk. It is
  directional, meant for ranking, and not an accounting number.

## Klaviyo / Mailchimp walkthrough

1. Create an API key in the dashboard (API Keys, then create).
2. On a schedule (nightly works, since data refreshes nightly), call
   `/customers/export?updated_since=<last run>` and page through the rows.
3. Upsert each row onto the matching profile as custom properties
   (`bb_segment`, `bb_churn_risk`, `bb_next_order`, `bb_rec_1_url`, …). Match
   profiles by your store's customer id, the same id your platform gives the
   customer (the WooCommerce user id for the Woo plugin, the numeric Shopify
   customer id for the Shopify app).
4. Build flows on the properties: win-back when `bb_segment` becomes
   `at_risk`, replenishment reminders from `due_replenishment=true` pulls,
   "picked for you" blocks from the recommendation URLs. For a one-off list,
   say a win-back campaign, pull a filtered slice instead of everything:
   `inactive_days=90&min_orders=2` or `min_churn=0.5&min_revenue=200`.
5. For **triggers** rather than properties, poll
   `/customers/events?after_id=<stored>&type=became_at_risk,replenishment_due&include=customer`
   and fire one flow per event. Or skip polling and let a
   [webhook](webhooks.md) call Zapier / Make / n8n for you.

One metered request is counted per API **call** (not per customer row).

## Klaviyo direct sync (no polling needed)

If your store's Klaviyo integration sets each profile's `external_id` to the
store customer id (the WooCommerce integration does for logged-in customers),
BasketBooster can push straight into Klaviyo. In the dashboard open
**Customers > Klaviyo sync** (Shopify stores use the app's Customers page,
Klaviyo sync tab): paste a private API key with the `accounts:read`,
`profiles:write` and `events:write` scopes (verified on save, stored
encrypted, shown only as the last four characters), choose what to sync,
switch it on.

**Shopify stores: check your profile ids first.** Klaviyo's own Shopify
integration leaves `external_id` empty. It identifies profiles by email and
does not copy the Shopify customer id into that field (Klaviyo sets
`external_id` only from some integrations, BigCommerce for one, or through its
API). BasketBooster matches on `external_id` = the numeric Shopify customer id,
so until your profiles carry it, the sync creates email-less duplicate
profiles that never receive a flow. Populate it once, for example with a
Shopify Flow or Klaviyo API step that writes the customer id as `external_id`
when a customer is created, then switch the sync on. Set it on existing
profiles the same way (a profile import with `external_id` and email merges
onto the matching profile).

After every nightly refresh (and on "Sync now"):

- **Profile properties** via a bulk import job, matched by `external_id`:
  `bb_segment`, `bb_prev_segment`, `bb_segment_since`, `bb_churn_risk`,
  `bb_churn_band`, `bb_next_order_date`, `bb_last_order_at`, `bb_orders`,
  `bb_revenue`, `bb_clv_12m`, `bb_median_interval_days`,
  `bb_replenishment_due` (product titles), `bb_replenishment_due_date`,
  `bb_rec_1_title` / `bb_rec_1_url` / `bb_rec_1_image` … up to 3, `bb_updated_at`.
- **Events** (Klaviyo metrics, one per change, idempotent by our event id):
  `BasketBooster Became At Risk`, `BasketBooster Predicted Order Missed`,
  `BasketBooster Replenishment Due` (with `product_title`, `product_url`,
  `product_image`), `BasketBooster Reactivated`, `BasketBooster New Champion`.
  Segment moves and churn thresholds are reflected on the properties instead.

Build flows on the metrics (win-back on *Became At Risk*, a reminder on
*Replenishment Due*) and segments on the properties (`bb_churn_band` is
`high`). Profiles Klaviyo cannot match are created without an email and never
receive a flow, so nothing is sent to anyone you do not already email.

The dashboard shows the last sync, how many profiles and events were sent,
and the import job's outcome; a key Klaviyo rejects switches the sync off and
shows the reason.

### Managing the connection by API

The same endpoints the dashboard uses accept your secret `X-API-Key` (the
Shopify app and server integrations use them this way). All are gated on the
Customer Intelligence feature.

| call | does |
|---|---|
| `GET /account/esp/klaviyo` | current state: `configured` (server can store keys), `key_set`, `key_hint`, `enabled`, `sync_profiles`, `sync_events`, `matching`, `account_label`, `last_sync_at`, `last_job_status`, `last_error`, `profiles_synced`, `events_synced` |
| `PUT /account/esp/klaviyo` | body (all optional): `api_key` (verified against Klaviyo and stored encrypted; `""` removes it and disables), `enabled`, `sync_profiles`, `sync_events`. `400` when Klaviyo rejects the key or you enable without one, `502` when Klaviyo is unreachable, `503` when this server has no `SECRETS_ENCRYPTION_KEY` |
| `POST /account/esp/klaviyo/test` | re-checks the stored key; returns `{ok, account, timezone}` |
| `POST /account/esp/klaviyo/sync` | queues a sync now (`202 {"queued": true}`); `400` until the connection is enabled with a key |
| `DELETE /account/esp/klaviyo` | removes the connection and the stored key (`204`) |

```bash
curl -X PUT https://api.basketbooster.eu/account/esp/klaviyo \
  -H "X-API-Key: sk_..." -H "Content-Type: application/json" \
  -d '{"api_key": "pk_...", "enabled": true}'
```

## Acting on-site (no email needed)

With the **customer nudges** switched on in the widget designer, the
recommendations widget shows logged-in shoppers a "Time to restock" block
(their due items) or a win-back line (their picks) above the grid. The block
is driven by `GET /v1/customer-context` with your publishable key. See the
[Widget Embed Guide](widget-embed.md#restock--win-back-nudges-logged-in-shoppers).

## WooCommerce plugin

The feed carries customer ids, not addresses. The plugin sits in the store,
next to the shopper's email and marketing consent, so it is a natural place
to act on it. The contract is the same feed:

- poll `GET /customers/events?after_id={stored}&type=became_at_risk,replenishment_due,reactivated&include=customer&limit=200`
  with the store's secret key (hourly via WP-Cron, `after_id` kept in
  `wp_options`), map `customer_id` to the `WP_User` and then to the email,
  and only email users who opted into marketing; each event carries product
  cards for the message;
- or, when the store has a public URL, register a [webhook](webhooks.md)
  pointing at a plugin REST route and verify `X-BasketBooster-Signature`.
