# Webhooks (`round.settled`, `credits.low`, `credits.exhausted`)

BetPlug delivers asynchronous operator events from a transactional PostgreSQL outbox (`api/asyncapi.yaml`) through BetPlug's DNS-pinning SSRF guard (no redirects, 64 KB cap) until your HTTPS endpoint answers with any `2xx` status.

## Quick SDK receivers (recommended)

Verify the raw HTTP body **before** `JSON.parse` using any of the four [Official SDKs](/docs/sdk):

```ts no-eval tab
import { verifyWebhook, isRoundSettledEvent, isCreditsLowEvent, isCreditsExhaustedEvent, parseUsdMicros } from "./sdk/ts/src/index.ts";

// Express / Next.js Route Handler: read raw bytes via await req.arrayBuffer()
const verified = await verifyWebhook({
  method: "POST",
  target: requestRawPathAndQuery, // exact wire path + query, e.g. "/webhooks/betrail?site=1"
  headers: req.headers,
  body: new Uint8Array(await req.arrayBuffer()),
  secrets: [process.env.BETRAIL_WEBHOOK_SECRET!, process.env.BETRAIL_WEBHOOK_PREV_SECRET].filter(Boolean) as string[],
  nonceStore: myValkeyNonceStore, // SET NX EX 630
});

if (await alreadyProcessed(verified.webhookId)) return new Response("ok", { status: 200 }); // deduplicate on Betrail-Webhook-Id
if (isRoundSettledEvent(verified.event)) await recordSettlement(verified.event.data);
else if (isCreditsLowEvent(verified.event) || isCreditsExhaustedEvent(verified.event)) {
  await alertOps(verified.event.type, parseUsdMicros(verified.event.data.balance));
}
return new Response("ok", { status: 200 });
```

```go no-eval tab
event, err := betrail.VerifyHTTPWebhook(r.Context(), r, secrets, nonceStore, time.Time{})
if err != nil {
    http.Error(w, "unauthorized", http.StatusUnauthorized)
    return
}
if round, ok, _ := event.AsRoundSettled(); ok {
    recordSettlement(round)
} else if low, ok, _ := event.AsCreditsLow(); ok {
    alertOps("credits.low", low.Balance)
} else if ex, ok, _ := event.AsCreditsExhausted(); ok {
    alertOps("credits.exhausted", ex.Balance)
}
w.WriteHeader(http.StatusOK)
```

```python no-eval tab
event = verify_webhook("POST", request.full_path, raw_body, request.headers, secrets, nonce_store)
if event.is_round_settled():
    record_settlement(event.parse_round_settled())
elif event.is_credits_low():
    alert_ops("credits.low", event.parse_credits_low().balance)
elif event.is_credits_exhausted():
    alert_ops("credits.exhausted", event.parse_credits_exhausted().balance)
```

```php no-eval tab
$event = Webhooks::verifyGlobals([$activeSecret, $prevSecret], $nonceStore);
if (($round = $event->asRoundSettled()) !== null) {
    recordSettlement($round);
} elseif ($event->isCreditsLow() || $event->isCreditsExhausted()) {
    alertOps($event->type, $event->data['balance']);
}
```

## Headers & verification order

| Header | Pattern | Purpose |
|---|---|---|
| `Betrail-Webhook-Id` | `string` (equals `body.id`) | Stable event ID across every retry. Deduplicate business side effects strictly on this ID. |
| `Betrail-Timestamp` | `^[0-9]{10}$` | Unix seconds when this delivery attempt was signed (`±300 s` window). |
| `Betrail-Nonce` | `^[A-Za-z0-9_-]{16,64}$` | Fresh per delivery attempt. Claim in Valkey (`SET NX EX 630`) after MAC verification. |
| `Betrail-Signature` | `^v1=[0-9a-f]{64}(,v1=[0-9a-f]{64})?$` | `betrail-v1` HMAC-SHA256 keyed with the brand's webhook secret (`v1=<new>,v1=<old>` during 24 h rotation). |

> **Security:** Always verify in this exact order: (1) reject non-`identity` `Content-Encoding` (`415`) and bodies `> 65,536` bytes (`413`), (2) verify `Betrail-Timestamp` (`±300 s`) and constant-time `Betrail-Signature` over the **original raw request-target** and exact raw body bytes **before** `JSON.parse`, (3) claim `Betrail-Nonce` (`SET NX EX 630`), and (4) deduplicate by `Betrail-Webhook-Id` (returning `200` on duplicates).

## Outbox retry schedule, dead-letter replay & credit-alert emails

BetPlug's transactional worker (`betrail-worker`) guarantees at-least-once delivery without dropping events:

- **Retry backoff schedule:** Full-jitter exponential backoff drawn from CSPRNG starting at **`1 s` base**, doubling per attempt up to a **`15 m` cap**, across a **`24 h` delivery window** (per-operator concurrency cap: `8` live leases, `30 s` lease duration).
- **Stuck-money alerting:** Any unacknowledged settlement/money outbox event older than **`1 h`** raises a stuck-money alert automatically.
- **Dead-letter queue & Console replay:** After `24 h` without a `2xx` answer, an event transitions to status **`dead`**, raising an operator alert. Inspect full delivery attempts and endpoint health (`GET /console/webhooks/deliveries/{id}` and `GET /console/brands/{brand}/webhooks/{environment}/health`) and **replay `dead` events** directly from BetPlug Console `/webhooks` (which starts a fresh 24-hour retry window).
- **Credit-alert emails alongside webhooks:** Whenever `credits.low` or `credits.exhausted` fires on `live`, `betrail-worker` delivers **both** the signed webhook AND an operator alert email over the shared SMTP relay (`BETRAIL_SMTP_*`, mandatory STARTTLS off loopback or when credentials are set). Inspect unified webhook + email delivery status in Console (`/console/billing/alerts/history`).

> **Warning:** Return `2xx` within `3 s` — acknowledge receipt immediately after durable persistence (or enqueueing locally) and process heavy downstream analytics asynchronously.

## Event payloads (`api/asyncapi.yaml`)

Every event shares the `WebhookEvent` envelope `{ id, type, created_at, environment, data }` (`environment` is `"sandbox"` | `"live"`; both credit events are always `"live"` because prepaid USD credits pay for live play only). Remember that in `round.settled`, `payout` already includes `refund` (`GGR = stake - payout`).

### `round.settled` (`RoundSettledEvent`)

```json
{
  "id": "evt_01JBX7Q2W3E4R5T6",
  "type": "round.settled",
  "created_at": "2026-10-28T17:00:00Z",
  "environment": "sandbox",
  "data": {
    "id": "rnd_01JBX7Q2W3E4R5T6Y7U8I9O0PA",
    "game": "dice",
    "version": 1,
    "brand": "br_casino_main",
    "player_ref": "p_8f3a2c",
    "currency": "BTC",
    "status": "settled",
    "step": 1,
    "stake": "0.00100000",
    "payout": "0.00197999",
    "refund": "0.00000000",
    "max_profit": "1.00000000",
    "cap_rule": "truncate",
    "cap_source": "brand",
    "view": { "roll": 3317, "win": true },
    "seed": {
      "server_seed_hash": "3b1f0c6f9d2a4e8b7c5d1e0f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d",
      "client_seed": "seed-1",
      "nonce": 42
    },
    "created_at": "2026-10-28T17:00:00Z",
    "settled_at": "2026-10-28T17:00:00Z"
  }
}
```

### `credits.low` (`CreditsLowEvent`) & `credits.exhausted` (`CreditsExhaustedEvent`)

`credits.low` fires once when prepaid USD credits cross below your configured threshold; `credits.exhausted` fires once when a posting takes credits from `> 0` to `<= 0` (new live rounds answer `402 credits_exhausted` until topped up; open rounds still finish and sandbox keeps working; one posting can emit both events in no guaranteed order):

```json tab=credits.low
{
  "id": "evt_low_01JBX7Q2W3",
  "type": "credits.low",
  "created_at": "2026-10-28T17:05:00Z",
  "environment": "live",
  "data": {
    "balance": "25.000000",
    "threshold": "50.000000"
  }
}
```

```json tab=credits.exhausted
{
  "id": "evt_ex_01JBX7Q2W4",
  "type": "credits.exhausted",
  "created_at": "2026-10-28T17:12:00Z",
  "environment": "live",
  "data": {
    "balance": "0.000000",
    "threshold": "0.000000"
  }
}
```

> **Tip:** Parse `balance` and `threshold` (6-decimal micro-USD strings, potentially negative after a GGR fee or reversed top-up) using `parseUsdMicros` / `ParseUsdMicros` — never `parseFloat`.

## Verifying raw-byte webhooks & rotation overlap (runnable sample)

```ts
import assert from "node:assert/strict";
import path from "node:path";
import { pathToFileURL } from "node:url";

const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd();
const sdk = await import(pathToFileURL(path.join(repoRoot, "sdk", "ts", "src", "index.ts")).href);

const activeSecret = "whsec-rotated-new-32bytes-secret!";
const prevSecret = "whsec-rotated-old-32bytes-secret!";
const nonces = new sdk.InMemoryNonceStore();
const processed = new Set<string>();

const rawBody = Buffer.from(
  JSON.stringify({
    id: "evt_01JBX7Q2W3E4R5T6",
    type: "credits.exhausted",
    created_at: "2026-10-28T17:12:00Z",
    environment: "live",
    data: { balance: "0.000000", threshold: "0.000000" },
  }),
  "utf8",
);

// 1. First delivery during 24 h rotation overlap (signed with previous secret) succeeds
const attempt1 = sdk.signRequest({ method: "POST", target: "/hooks/betrail?site=1", body: rawBody, secrets: [prevSecret] });
const verified1 = await sdk.verifyWebhook({
  method: "POST",
  target: "/hooks/betrail?site=1",
  headers: {
    "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6",
    "betrail-timestamp": attempt1.timestamp,
    "betrail-nonce": attempt1.nonce,
    "betrail-signature": attempt1.signature,
  },
  body: rawBody,
  secrets: [activeSecret, prevSecret],
  nonceStore: nonces,
});
assert.equal(sdk.isCreditsExhaustedEvent(verified1.event), true);
assert.equal(sdk.isCreditsLowEvent(verified1.event), false);
assert.equal(sdk.isRoundSettledEvent(verified1.event), false);
processed.add(verified1.webhookId);

// 2. Replayed identical nonce is rejected; outbox retry with fresh nonce is accepted & deduplicated by Betrail-Webhook-Id
await assert.rejects(() =>
  sdk.verifyWebhook({
    method: "POST",
    target: "/hooks/betrail?site=1",
    headers: {
      "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6",
      "betrail-timestamp": attempt1.timestamp,
      "betrail-nonce": attempt1.nonce,
      "betrail-signature": attempt1.signature,
    },
    body: rawBody,
    secrets: [activeSecret, prevSecret],
    nonceStore: nonces,
  }),
);

const attempt2 = sdk.signRequest({ method: "POST", target: "/hooks/betrail?site=1", body: rawBody, secrets: [activeSecret] });
const verified2 = await sdk.verifyWebhook({
  method: "POST",
  target: "/hooks/betrail?site=1",
  headers: {
    "betrail-webhook-id": "evt_01JBX7Q2W3E4R5T6",
    "betrail-timestamp": attempt2.timestamp,
    "betrail-nonce": attempt2.nonce,
    "betrail-signature": attempt2.signature,
  },
  body: rawBody,
  secrets: [activeSecret, prevSecret],
  nonceStore: nonces,
});
assert.equal(processed.has(verified2.webhookId), true);
```
