# Receive updates

> Set your update address, check each update's signature, answer fast, drop repeats, keep the newest state, test with a sample, and catch up on anything missed.

Source: https://docs.b7r.app/receive-updates

B7R posts an update to your server whenever an order, a product or the wallet changes, so you never need to poll. The kinds, body and retry schedule are in [Updates](https://docs.b7r.app/updates).

Updates cover every order and product of your account, whatever its channel, for as long as the account has an active key. A change made while it has none is not recorded, not even in the catch-up list, and that includes the orders you placed through the API: when you replace a key, create the new one before you revoke the old one.

## Set the address and keep the secret

In the B7R app, open Settings, then Integrations, then the Custom API card, and enter your address: an `https` URL on port 443 with a public host name (not an IP address). Create the signing secret there: it starts with `whsec_` and is shown once. Keep it on your server, like your API key.

## Check the signature

Before you trust an update, check that B7R sent it: rebuild the signature over the raw body and compare, and refuse a timestamp more than 5 minutes old so a recorded update cannot be replayed. During a secret rotation the header holds two signatures: accept either. Check your code against the test vector below: with the clock set to the timestamp, it must return true, and false after one changed byte.

Verify:

```javascript
import crypto from "node:crypto";

// secret: the whsec_ value from the Custom API card.
// body: the raw request body as a string, before any JSON parsing.
export function verifyUpdate(secret, headers, body) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;
  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!Number.isFinite(age) || age > 300) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${timestamp}.${body}`)
    .digest();
  return signatures.split(" ").some((entry) => {
    const [version, value] = entry.split(",");
    if (version !== "v1" || !value) return false;
    const given = Buffer.from(value, "base64");
    return (
      given.length === expected.length &&
      crypto.timingSafeEqual(given, expected)
    );
  });
}
```

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


def verify_update(secret, headers, body):
    """secret: the whsec_ value; body: the raw request body as bytes."""
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False
    try:
        if abs(time.time() - int(timestamp)) > 300:
            return False
    except ValueError:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(
        hmac.new(key, signed, hashlib.sha256).digest()
    ).decode()
    for entry in signatures.split(" "):
        version, _, value = entry.partition(",")
        if version == "v1" and hmac.compare_digest(value, expected):
            return True
    return False
```

```php
<?php
// $secret: the whsec_ value; $body: the raw request body, before json_decode.
function verify_update(string $secret, array $headers, string $body): bool
{
    $id = $headers['webhook-id'] ?? '';
    $timestamp = $headers['webhook-timestamp'] ?? '';
    $signatures = $headers['webhook-signature'] ?? '';
    if ($id === '' || $signatures === '' || !ctype_digit($timestamp)) {
        return false;
    }
    if (abs(time() - (int) $timestamp) > 300) {
        return false;
    }
    $key = base64_decode(preg_replace('/^whsec_/', '', $secret), true);
    if ($key === false) {
        return false;
    }
    $expected = base64_encode(
        hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true)
    );
    foreach (explode(' ', $signatures) as $entry) {
        [$version, $value] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $value)) {
            return true;
        }
    }
    return false;
}
```

Test vector:

```text
secret            whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw
webhook-id        evt_0f8d2a4c6b1e4f3a9d7c5b3a1e2f4d6c
webhook-timestamp 1795341605
body              {"id":"evt_0f8d2a4c6b1e4f3a9d7c5b3a1e2f4d6c","type":"order.status_changed","created_at":"2026-11-22T10:00:00.000Z","sequence":3,"subject":{"type":"order","id":"B26112200042"},"data":{"id":"B26112200042","external_id":"partner-order-1001","status":"in_production","payment_status":"paid","delivery_method":"home","seller":{"id":"seller-77","name":"Store Seventy Seven"},"carrier_id":"6f1c2b3a-4d5e-4f60-8a71-92b3c4d5e6f7","tracking_number":null,"tracking_url":null,"cancellation":null,"created_at":"2026-11-22T08:15:30.250Z","previous_status":"created","direction":"forward","reason":null},"sample":false}
webhook-signature v1,szNHdTiZFbAqfUIxewRBzw4F3n6qT8m/55JzqMI7KJ4=
```

## Answer fast, then work

- Answer `2xx` within 10 seconds: store the update, answer, then process it.
- Answer `2xx` to every update you accept, kinds you ignore included. Answer `400` to one whose signature fails: a real B7R update never fails it.
- Only `410 Gone` stops B7R retrying an update. Any other `4xx`, a `5xx`, a redirect (never followed) or a timeout is retried on the schedule in [Updates](https://docs.b7r.app/updates#delivery-and-retries).

A handler:

```javascript
import express from "express";
import { verifyUpdate } from "./verify.js";

const app = express();

// Raw body: the signature covers the exact bytes B7R sent.
app.post("/b7r/updates", express.raw({ type: "application/json" }), async (req, res) => {
  const body = req.body.toString("utf8");
  if (!verifyUpdate(process.env.B7R_UPDATES_SECRET, req.headers, body)) {
    return res.status(400).end();
  }
  const update = JSON.parse(body);
  // Store it, then answer at once and do the work later: B7R waits
  // 10 seconds at most. A crash before the 200 means B7R retries.
  if (!(await db.updates.seen(update.id))) {
    await queue.add(update); // apply it only if its sequence is the highest
  }
  res.status(200).end();
});
```

## Drop repeats and keep the newest

- The same update can arrive more than once: store each `id` you handled and skip it the next time.
- One subject's updates go out in `sequence` order, but across subjects and on retries they can arrive out of order. Each carries the whole state of its subject: keep the highest `sequence` per subject and ignore a lower one.
- Ignore a `type` you do not know.

## Send yourself a sample

`POST /v1/events/test` posts a signed sample of any `type` to your address and says how your server answered. A sample has `sample: true`, is never stored, and never counts as a failure.

Request:

```bash
curl -X POST https://api.b7r.app/v1/events/test \
  -H "Authorization: Bearer $B7R_API_KEY" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || node -e 'console.log(crypto.randomUUID())')" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "order.status_changed"
  }'
```

```javascript
const res = await fetch("https://api.b7r.app/v1/events/test", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.B7R_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "type": "order.status_changed"
  }),
});
const data = await res.json();
```

```python
import os, requests, uuid

res = requests.post(
    "https://api.b7r.app/v1/events/test",
    headers={
        "Authorization": f"Bearer {os.environ['B7R_API_KEY']}",
        "Idempotency-Key": str(uuid.uuid4()),
    },
    json={
        "type": "order.status_changed"
    },
    timeout=30,
)
data = res.json()
```

## Catch up after downtime

Every update of the last 30 days is in [`GET /v1/events`](https://docs.b7r.app/updates#catch-up-on-updates), oldest first, exactly as sent. Store `next_cursor` after each page and start from it next time; run it after an outage, or on a timer as a safety net. Retries stop after about 3 days, and after 72 hours of failures B7R turns updates off and emails you: turn them on again on the Custom API card.

Request:

```bash
curl "https://api.b7r.app/v1/events?limit=100" \
  -H "Authorization: Bearer $B7R_API_KEY"
```

```javascript
const res = await fetch("https://api.b7r.app/v1/events?limit=100", {
  headers: {
    Authorization: `Bearer ${process.env.B7R_API_KEY}`,
  },
});
const data = await res.json();
```

```python
import os, requests

res = requests.get(
    "https://api.b7r.app/v1/events?limit=100",
    headers={
        "Authorization": f"Bearer {os.environ['B7R_API_KEY']}",
    },
    timeout=30,
)
data = res.json()
```
