Outbound webhooks
Receive signed, retried HTTP callbacks when referral, credit, payout, region, entitlement, subscription and purchase events happen in BillStack.
BillStack can call your server when something happens in a project, such as a customer's entitlement changing, a subscription renewing, a referral converting or a reward being approved. Each event is stored first, then delivered as a signed POST to every endpoint you registered for that project and environment. Failed deliveries are retried for about three days.
Outbound webhooks are scoped by project and environment. A test key manages test endpoints that receive test events; a live key manages live ones. Billing-provider webhooks that arrive at BillStack (Stripe, Razorpay) are a different feature; see Providers and Webhooks.
Entitlement, subscription and purchase events (entitlement.updated, subscription.*, purchase.*) are sent on payload version 2026-10-26 and later. Endpoints created before that version stay on theirs and do not receive them, not even with *. To start receiving them, move the endpoint to 2026-10-26. Reading an entitlement through the API stays the source of truth; see Entitlements.
Event envelope
Every delivery body is one JSON object:
{
"id": "evt_0123456789abcdef0123456789abcdef",
"type": "credit.created",
"created": 1700000000,
"projectId": "proj_123",
"environment": "live",
"apiVersion": "2026-10-26",
"region": { "id": "reg_india", "provider": "razorpay", "entityId": "entity_123" },
"data": {}
}| Field | Meaning |
|---|---|
id | Stable event id. The same id is sent on every attempt and every replay. |
type | One of the event types below. |
created | Unix seconds when the event was recorded. |
projectId, environment | The project and test or live environment it belongs to. |
apiVersion | Payload version of the endpoint receiving the delivery (see below). |
region | Version 2026-10-22 and later (the customer's region for entitlement, subscription and purchase events, once they have one). The region the event relates to: id, provider and entityId (the merchant entity, null when it has none). The whole field is null for events that relate to no region. |
data | Event specific payload. |
Payload versions
Every endpoint has an apiVersion:
| Version | Shape |
|---|---|
2026-10-19 | The original envelope, without region. Endpoints created before versions existed stay on it, and their bodies are unchanged. |
2026-10-22 | Adds region. |
2026-10-26 | The same shape as 2026-10-22. Adds the entitlement, subscription and purchase events. The default for new endpoints. |
Choose the version with apiVersion when you create an endpoint, and change it later with PATCH. The change applies to deliveries sent from then on, including retries and replays of earlier events (an event is stored once and rendered for the endpoint's version when it is sent). Every delivery reports the version of the endpoint that receives it in apiVersion. GET /webhook-event-types lists supportedApiVersions. Receivers should ignore fields they do not know.
Each event type exists from a version on (since in the catalogue). An endpoint only ever receives the types that exist at its version: * means "every type at my version", and listing a newer type by name on an older endpoint is rejected with a validation error. The same check applies to PATCH, so you cannot move an endpoint back to a version that lacks a type it subscribes to. Upgrading an existing endpoint is the opt-in: events from before the upgrade are not sent retroactively.
Event types
Read the live list from GET .../webhook-event-types. An endpoint subscribes to a list of types, or to * for all of them.
| Type | Sent when |
|---|---|
referral.code_created | A referral code was created. |
referral.code_updated | A referral code was changed or deactivated. |
referral.attributed | A customer was attributed to a referral code. |
referral.converted | A referred customer made a qualifying payment. |
referral.expired | A referral attribution expired before converting. |
referral.reward_pending | A reward was created and is waiting for approval. |
referral.reward_approved | A reward was approved for payout. |
referral.reward_applied | A reward was paid out to the referrer. |
referral.reward_rejected | A reward was rejected. |
referral.reward_expired | A reward expired before approval. |
referral.reward_reversed | A reward was reduced or reversed after a refund, credit note or dispute. |
referral.reward_failed | Paying out a reward failed. |
credit.created | A credit ledger entry was created. |
credit.approved | A credit ledger entry was approved for payout. |
credit.rejected | A credit ledger entry was rejected. |
credit.expired | A credit ledger entry expired before approval. |
credit.applied | A credit ledger entry was applied. |
credit.reversed | An applied credit ledger entry was reversed. |
credit.failed | Applying a credit ledger entry failed. |
payout.requested | A referrer asked to be paid out their earned rewards. |
payout.approved | A payout request was approved. BillStack moves no money. |
payout.rejected | A payout request was rejected and its credits released. |
payout.paid | A payout request was marked paid with your external reference. |
payout.cancelled | A referrer cancelled their payout request. |
payout.credit_reversed | A credit behind a paid payout request was reversed afterwards. |
customer.region_conflict | A customer paid in a region other than the one they are pinned to. The payment was accepted and the pin kept. |
entitlement.updated | A customer's effective entitlement changed. Version 2026-10-26. |
subscription.created | A subscription was seen for the first time, including a trial. Version 2026-10-26. |
subscription.renewed | A subscription moved into a new billing period. Version 2026-10-26. |
subscription.canceled | A subscription ended (canceled, expired or revoked). Version 2026-10-26. |
subscription.updated | A subscription changed in another way, such as a cancellation scheduled for the period end. Version 2026-10-26. |
purchase.completed | A one-time payment was confirmed. One event per checkout. Version 2026-10-26. |
purchase.refunded | A one-time payment was refunded. Version 2026-10-26. |
webhook.test | You sent a test event to one endpoint. Never sent by subscription. |
Entitlement, subscription and purchase events
These events describe what happened to a customer's access and payments, whichever provider (Stripe, Razorpay or RevenueCat) the change came from. They are sent to the endpoints of the project and environment the customer belongs to: a test-environment change reaches test endpoints only.
entitlement.updated is the event to build access control on. It is sent when a customer's effective entitlement (the plan, tier, status, access, period end or the set of grants behind it) changes, and carries the state before and after:
{
"id": "evt_0123456789abcdef0123456789abcdef",
"type": "entitlement.updated",
"created": 1700000000,
"projectId": "proj_123",
"environment": "live",
"apiVersion": "2026-10-26",
"region": null,
"data": {
"customer": { "id": "cus_123", "externalId": "user_42" },
"version": 7,
"transition": "granted",
"changes": ["plan", "tier", "status", "isEntitled", "currentPeriodEnd", "contributors"],
"before": null,
"after": {
"plan": "pro",
"tier": "pro",
"status": "active",
"isEntitled": true,
"currentPeriodEnd": "2026-11-23T00:00:00.000Z",
"contributors": ["stripe:pconn_1:live:stripe_subscription:sub_123:user_42"]
},
"occurredAt": "2026-10-23T10:00:00.000Z",
"cause": {
"type": "provider_event",
"provider": "stripe",
"providerEventId": "evt_stripe_456",
"providerEventType": "customer.subscription.created"
}
}
}data field | Meaning |
|---|---|
customer | The BillStack customer id and your own id for them (externalId, null when none). |
version | The entitlement's version after the change. It increases for every change to that customer in that environment, with gaps. Apply an update only if its version is higher than the last one you applied. null when the change was made with the manual grant API (see below); order those by occurredAt. A lifetime deal revoke has a version. |
transition | granted (the customer had no access and now has), revoked (had access, now has none) or changed. |
changes | Which of plan, tier, status, isEntitled, currentPeriodEnd and contributors differ between before and after. |
before, after | The effective entitlement before and after. before is null when the customer had no entitlement. contributors are the source keys of the grants behind it (the same ids as sourceExternalId in the entitlement API). |
occurredAt | When BillStack applied the change. |
cause | provider_event with the provider event that caused it, manual_grant (granted or revoked, with the grantId) or lifetime_deal_revoked (an operator ended the access one lifetime deal purchase gave, with the dealId, saleId and the grantId of the payment grant). |
Comping a customer with a manual grant and revoking it also send entitlement.updated when they change what the customer can do.
Revoking a lifetime deal purchase sends entitlement.updated too, with cause.type lifetime_deal_revoked, transition revoked and a version, when the buyer had access and now has none. It is not a refund: the payment still reads as paid, and no purchase.refunded follows from the revoke. If you later refund the payment at the provider, that refund is the first purchase.refunded. Retrying the same revoke sends the event again if the first attempt lost it (same event id), and never twice.
subscription.* and purchase.* events describe the underlying subscription or payment:
| Type | Sent when |
|---|---|
subscription.created | A subscription is seen for the first time (a trial included). |
subscription.renewed | The billing period moved forward. |
subscription.canceled | A live subscription ended: canceled, expired or revoked. A cancellation scheduled for the period end is subscription.updated (cancelAtPeriodEnd: true) until the subscription actually ends. |
subscription.updated | Anything else that changed: a cancellation scheduled or undone, a plan, price or quantity change, a billing problem, a trial converting, or an ended subscription coming back. |
purchase.completed | A one-time payment was confirmed. A single checkout produces one event even though the provider confirms it with several events of its own. |
purchase.refunded | A one-time payment that had been confirmed was refunded. |
{
"customer": { "id": "cus_123", "externalId": "user_42" },
"grant": {
"sourceKind": "stripe_subscription",
"sourceKey": "stripe:pconn_1:live:stripe_subscription:sub_123:user_42",
"provider": "stripe",
"plan": "pro",
"tier": "pro",
"priceVariantId": "var_pro",
"status": "canceling",
"currentPeriodEnd": "2026-11-23T00:00:00.000Z",
"quantity": 1,
"cancelAtPeriodEnd": true,
"trialing": false
},
"previous": { "status": "active", "plan": "pro", "tier": "pro", "currentPeriodEnd": "2026-11-23T00:00:00.000Z" },
"occurredAt": "2026-10-23T10:00:00.000Z",
"cause": { "type": "provider_event", "provider": "stripe", "providerEventId": "evt_stripe_789", "providerEventType": "customer.subscription.updated" }
}That is the data of a subscription.updated. previous is null on subscription.created. A purchase.* event has the same shape, with checkoutId (the checkout the payment settled, null for a payment made outside a BillStack checkout), paymentId and consumable in place of cancelAtPeriodEnd and trialing. Purchase events carry no amounts; read financial detail from the API.
Good to know:
- At least once, any order. Deduplicate on the envelope
id, as for every event. Forentitlement.updated, compareversion(oroccurredAtforversion: null) with the last update you applied and ignore an older one, or re-read the entitlement.GET .../entitlements/{externalId}is always authoritative. - Treat updates as state, not as commands. The same resulting state can be announced more than once (for example a comp grant is announced when it is made, and a later provider event can re-evaluate the entitlement). Setting your stored plan to
after.planis safe to repeat. - Only changes are announced. A provider event that changes nothing, or a stale one that BillStack ignores, sends nothing. One change sends one
subscription.*orpurchase.*event, and at most oneentitlement.updated. - Delay. Events are sent right after BillStack records the change, and a sweep every 5 minutes covers anything missed, so an event can arrive up to about five minutes late in the worst case.
- Time-based endings are not announced. A subscription or comp whose period simply runs out, with no event from the provider, changes the entitlement that the API reports but does not send an event; providers normally send a final event when a subscription ends, and that one is announced. Until time-based expiry events exist, keep reading the entitlement (or its
currentPeriodEnd) for that case. The same goes for a comp grant that starts in the future. - Comps with a priority.
beforeandafterof a change made by a provider event are computed without the priority a manual grant can carry. If you use comp grants with a priority above 0, read the entitlement for the exact effective plan.
Reversal events
referral.reward_reversed (and credit.reversed for a credit that is not a referral reward) carries data.credit (the reward) and data.reversal:
| Field | Meaning |
|---|---|
originalId | The reward that was reversed. |
reversalId | The reversal ledger entry, or null when the reward had not been paid yet and its amount was only reduced. |
amount, currency | Minor units taken back by this action (positive). |
reason | refund, credit_note or dispute. |
objectId | The Stripe refund/charge, credit note or dispute that caused it. |
mode | reversal_entry (paid reward) or reduced (unpaid reward, partial). |
full | true when the reward is now fully reversed. |
A full refund of a reward that was not paid yet rejects it instead (referral.reward_rejected, reason refunded, credit_note or disputed). A won dispute does not restore the reward; create a manual credit to give it back.
customer.region_conflict
A customer is pinned to the region of their first successful payment. If a payment is later confirmed in a different region (for example the customer opened checkouts in two regions and paid both), BillStack still accepts the payment, keeps the original pin and raises this event. It never refunds or cancels anything automatically, so the decision is yours. The same event is raised when a second payment for an already-owned lifetime campaign tier lands in another region (see Lifetime Deal Campaigns).
An endpoint subscribed to * receives it without any change; an endpoint with
an explicit list must add customer.region_conflict. The event id is derived
from the customer, the provider and the provider event, so a replayed provider
event never produces a second one. It can take up to about five minutes to be
delivered.
{
"id": "evt_0123456789abcdef0123456789abcdef",
"type": "customer.region_conflict",
"created": 1700000000,
"projectId": "proj_123",
"environment": "live",
"apiVersion": "2026-10-26",
"region": { "id": "reg_india", "provider": "razorpay", "entityId": "entity_123" },
"data": {
"customer": { "id": "cus_123", "externalId": "user_42" },
"pinnedRegionId": "reg_global",
"paidRegionId": "reg_india",
"provider": "razorpay",
"connectionId": "pconn_123",
"checkoutIntentId": "chk_123",
"providerEventId": "evt_provider_456",
"providerEventType": "payment_link.paid"
}
}data field | Meaning |
|---|---|
customer.id, customer.externalId | The BillStack customer id and your own id for them (null when none). |
pinnedRegionId | The region the customer stays pinned to. |
paidRegionId | The region this payment was made in. |
provider | The provider that confirmed the payment (stripe or razorpay). |
connectionId | The provider connection that received the payment, or null when unknown. |
checkoutIntentId | The BillStack checkout the payment belongs to, or null. |
providerEventId, providerEventType | The provider event that confirmed the payment. |
What to do: look up the payment in the provider dashboard (the provider and
event ids are in the payload), decide whether to keep it or refund it there,
and tell the customer. BillStack grants access for the payment as usual. The
envelope has no region fields of its own; the region ids are only in data.
Request headers
| Header | Value |
|---|---|
Content-Type | application/json |
User-Agent | BillStack-Webhooks/1 |
BillStack-Signature | t=<unix seconds>,v1=<hex signature> |
BillStack-Event-Id | The envelope id. |
BillStack-Event-Type | The envelope type. |
The signature is HMAC-SHA256(secret, "<t>.<raw body>") as lowercase hex, using the endpoint's signing secret (whsec_...). t is the time of that attempt, so a retry carries a fresh timestamp.
Verify the signature
Always verify against the raw request body, exactly as received. Re-serialised JSON will not match.
With the SDK
@billstack/sdk verifies with Web Crypto, so the same code runs on Node 18+, edge runtimes, Deno and Bun. Verification is asynchronous.
import { webhooks } from "@billstack/sdk";
export async function POST(request: Request) {
const payload = await request.text();
const signature = request.headers.get("BillStack-Signature") ?? "";
try {
const event = await webhooks.constructEvent(
payload,
signature,
process.env.BILLSTACK_WEBHOOK_SECRET!,
);
// handle event.type, dedupe on event.id
} catch {
return new Response("invalid signature", { status: 400 });
}
return new Response("ok");
}webhooks.verify(payload, signatureHeader, secret, { toleranceSec? })resolves totrueorfalseand never throws on a bad signature.webhooks.constructEvent(...)verifies, parses and returns the typed event, or throwsBillStackWebhookSignatureErrorwhosereasonismalformed,expiredormismatch.toleranceSecdefaults to 300. A timestamp further than that from now is rejected, which blocks replayed captures.
With Node only
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyBillStack(
rawBody: string,
header: string,
secret: string,
toleranceSec = 300,
): boolean {
let t: number | null = null;
const signatures: string[] = [];
for (const part of header.split(",")) {
const index = part.indexOf("=");
if (index < 0) continue;
const key = part.slice(0, index).trim();
const value = part.slice(index + 1).trim();
if (key === "t" && /^\d+$/.test(value)) t = Number(value);
if (key === "v1") signatures.push(value);
}
if (t === null || signatures.length === 0) return false;
if (Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
return signatures.some((candidate) => {
const actual = Buffer.from(candidate, "hex");
return actual.length === expected.length && timingSafeEqual(actual, expected);
});
}Responding, retries and idempotency
Return any 2xx status to acknowledge. Anything else, a timeout (10 seconds), a network error or a redirect, counts as a failed attempt. BillStack does not follow redirects, so register the final URL.
A failed delivery is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 24 hours and 24 hours, for nine attempts over roughly 68 hours. After the last attempt it is marked failed. Retries are picked up by a sweep that runs every 5 minutes, so a retry can start up to five minutes after its scheduled time.
Delivery is at least once. Deduplicate on the event id: a retry, a replay, or a rare double send carries the same id. Process the event, record the id, and acknowledge repeats without reprocessing. Events are not guaranteed to arrive in the order they happened.
Endpoint URLs must use https (test endpoints may use http). URLs that point to private, link-local, loopback or internal addresses are rejected, and so is an empty event list.
Manage endpoints with the API
Routes live under /api/billstack/v2/teams/{teamId}/projects/{projectId}. They need a secret API key or a signed-in project admin; publishable keys are refused. The environment is the key's own environment. A dashboard session may pass ?mode=test or ?mode=live. An id from another project or environment returns 404.
| Method and path | Purpose |
|---|---|
GET /webhook-endpoints | List endpoints. |
POST /webhook-endpoints | Create an endpoint. Body: url, optional description, optional enabledEvents (defaults to ["*"]), optional apiVersion (defaults to the latest). The response contains the signing secret once. |
GET /webhook-endpoints/{endpointId} | Read one endpoint. The secret is never returned, only secretPrefix. |
PATCH /webhook-endpoints/{endpointId} | Change url, description, enabledEvents, apiVersion or status (active or disabled). |
DELETE /webhook-endpoints/{endpointId} | Disable the endpoint. History is kept; it is not a hard delete. |
POST /webhook-endpoints/{endpointId}/rotate-secret | Issue a new secret, shown once. The old secret stops working immediately, so deploy the new one first or accept failures until you do. |
POST /webhook-endpoints/{endpointId}/test | Send a webhook.test event to this endpoint only. Returns 202 with eventId and deliveryId; 409 if the endpoint is disabled. |
GET /webhook-deliveries | List deliveries, newest first. Filters: endpointId, status (pending, succeeded, failed), limit (1 to 200, default 50), cursor. Returns items and nextCursor. |
GET /webhook-deliveries/{deliveryId} | One delivery with eventType, attemptCount, lastStatusCode, lastError, nextAttemptAt, deliveredAt, timestamps and the sent payload. |
POST /webhook-deliveries/{deliveryId}/replay | Requeue a failed or succeeded delivery with a fresh attempt budget. Returns 202; 409 while it is still pending. |
GET /webhook-event-types | The event catalogue. Each type has since, the first payload version it is sent on. ?apiVersion= lists only the types an endpoint on that version receives. |
Responses use the standard v2 envelope: { "data": ..., "meta": { "apiVersion": "2", "requestId": "..." } }, and errors are { "error": { "code", "message" }, "meta": ... }.
curl -X POST \
"https://billing.w3dev.app/api/billstack/v2/teams/{teamId}/projects/{projectId}/webhook-endpoints" \
-H "Authorization: Bearer <private-api-key>" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/billstack","enabledEvents":["referral.converted","credit.applied"]}'With the SDK
import { BillStackV2Client } from "@billstack/sdk";
const client = new BillStackV2Client({
baseUrl: "https://billing.w3dev.app",
apiKey: process.env.BILLSTACK_API_KEY!,
teamId,
projectId,
});
const { data } = await client.webhookEndpoints.create({
url: "https://example.com/billstack",
enabledEvents: ["referral.converted"],
});
// Store data.secret now; it is not shown again.
await client.webhookEndpoints.sendTest(data.endpoint.id);
const failed = await client.webhookDeliveries.list({ status: "failed" });
await client.webhookDeliveries.replay(failed.data.items[0].id);The SDK covers webhookEndpoints.{list,create,get,update,disable,rotateSecret,sendTest}, webhookDeliveries.{list,get,replay} and webhookEventTypes.list (optionally { apiVersion }). To start receiving the entitlement, subscription and purchase events on an existing endpoint, call webhookEndpoints.update(id, { apiVersion: "2026-10-26" }).