---
name: sync-billstack-entitlements
description: "v2 (provider-neutral). Synchronize application workspace plans from BillStack v2 entitlements after purchase, renewal, cancellation, and failed payment using stable billing subjects, mode-isolated caches, and periodic reconciliation; explains current outbound notification limits."
---

# Synchronize BillStack entitlements

**Generation: v2** (provider-neutral, `/api/billstack/v2/...`, `BillStackV2Client`). This skill covers v2 only. If the app calls `/api/billstack/teams/...` (legacy v1), load [legacy-billstack-integration](https://billing.w3dev.app/.well-known/agent-skills/legacy-billstack-integration/SKILL.md) instead.

Use this skill when an application needs to keep workspace plans and access consistent with BillStack. Use [configure-billstack-billing](https://billing.w3dev.app/.well-known/agent-skills/configure-billstack-billing/SKILL.md) for provider/catalog/routing readiness and [integrate-billstack](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack/SKILL.md) for checkout and portal. The current v2 contract is read-based synchronization; these instructions do not advertise a future event API.

Origin: `https://billing.w3dev.app`. Prefix `P = /api/billstack/v2/teams/{teamId}/projects/{projectId}`. Keep the private BillStack API key in the application backend and send `Authorization: Bearer <private-bs-key>`. A single read requires `entitlement:GetEntitlement` and the bulk list requires `entitlement:ListEntitlements`, both with authorized project access. The manual grant calls (see "Complimentary access") need `entitlement:CreateGrant`, `entitlement:ListGrants` and `entitlement:RevokeGrant`. Encode each path identifier. Success uses `{ data, meta }`; errors use `{ error: { code, message, fieldErrors? }, meta }`.

## Keys and environments

Use a `bs_test_` key while building and in staging, and a `bs_live_` key in production (a legacy `bs_<hex>` key has no environment in its prefix and runs in the environment stored for it: live for keys issued before environments, test for teams moved to test-only). A key reads only its own environment, and `mode` defaults to it. Naming the other mode returns `403 ENVIRONMENT_MISMATCH`; a live key for a team that is not yet promoted to live returns `403 LIVE_ENVIRONMENT_NOT_ENABLED`. Treat both as configuration errors, not as "no entitlement".

## Notifications and reconciliation support

BillStack's outbound webhook endpoints (`/webhook-endpoints`, payload version `2026-10-26` and later) send `entitlement.updated` when a customer's effective entitlement changes, plus `subscription.created`, `subscription.renewed`, `subscription.canceled`, `subscription.updated`, `purchase.completed` and `purchase.refunded`. Endpoints on an older `apiVersion` receive none of them, not even with `*`: create the endpoint without an `apiVersion` (it defaults to the latest) or `PATCH` it to `2026-10-26`. See [Outbound webhooks](https://docs.billing.w3dev.app/integration/outbound-webhooks) for the signed payloads. Provider webhooks are **inbound** to BillStack and its Inngest worker projects them internally; they are not forwarded to your application's webhook URL. Do not invent an outbound endpoint, signing secret, event name, callback parameter, or SDK subscription method beyond those documented.

Treat the events as a trigger, not as the source of truth. They are delivered at least once and can arrive out of order: dedupe on the envelope `id`, ignore an `entitlement.updated` whose `version` is not higher than the last one you applied for that customer (`version` is `null` for a change made through the manual grant API; order those by `occurredAt`), and prefer re-reading `GET .../entitlements/{externalId}` and overwriting your cache over trusting `after`. Events are not sent when a period simply runs out with no provider event, nor when a comp starts in the future, so the periodic reconciliation below stays mandatory.

Implement server-side periodic reconciliation (with or without the events above), refresh on authenticated billing/account loads, and refresh after checkout or portal return. Application-owned provider notifications, if independently configured, may trigger a fresh BillStack read but are not BillStack outbound notifications and must not directly grant/revoke workspace access. Canonical signed webhook capture and the BillStack worker must be operating for reads to reflect provider changes.

The current worker runs on a five-minute sweep on the BillStack service; canonical capture is always on. Provider delivery, retries, and worker timing add lag. No synchronous fulfillment latency guarantee is implied by checkout success or a webhook's HTTP 200.

## Define the billing subject and plan mapping first

For workspace billing, choose one stable external subject per application workspace, for example `workspace:<immutable-workspace-id>`. The customer identity is `customerExternalId` (checkout falls back to `externalId` only when it is omitted), so always send `customerExternalId` with your stable customer ID and use that **same** value for country confirmation `customerExternalId`, entitlement reads, and portal `customerExternalId`. Checkout `externalId` may be a per-order ID. A user ID represents per-user billing; do not accidentally charge a user while expecting a workspace entitlement. The payer's email, Stripe customer ID, and current workspace slug are not durable application billing identity.

Persist the mapping between the authenticated application workspace and that BillStack external ID before starting checkout. Authorize the user's membership and billing role before checkout/portal operations or exposing entitlement data. Never accept an arbitrary external ID, team, project, or mode from an untrusted browser. Existing integrations must retain their current subjects or use a separately reviewed identity migration; changing an external ID does not transfer old purchases.

Create each canonical price variant with an intentional `tierAlias`, such as `pro`. Canonical entitlement plan/tier use that alias; without it they use the canonical variant ID. Maintain a server-owned allowlist mapping those labels to application plans, feature flags, seat limits, and quotas. Do not infer a plan from the product display name, Stripe metadata, checkout redirect, or customer input.

V2's public effective entitlement does **not** currently contain feature limits, enabledFeatures, version, or updatedAt. Those legacy snapshot fields are not part of this v2 response. Store your application's approved feature/limit mapping and cache fetch time separately; do not pretend the API supplied an entitlement version.

## Read the canonical entitlement

`GET P/entitlements/{externalId}` returns this shape (the example is a test-key response); IDs and dates are illustrative:

```json
{
  "data": {
    "effective": {
      "projectId": "<project-id>",
      "externalId": "workspace:example",
      "mode": "test",
      "plan": "pro",
      "tier": "pro",
      "isEntitled": true,
      "status": "active",
      "startsAt": "2026-10-01T00:00:00.000Z",
      "endsAt": "2026-11-01T00:00:00.000Z",
      "contributors": ["<source-identity>"],
      "unresolvedGrantCount": 0
    },
    "grants": []
  },
  "meta": { "requestId": "<request-id>" }
}
```

The grants array contains the persisted source grant details when available, including id, projectId, externalId, mode, sourceKind, sourceExternalId, commercialKey, status, startsAt, endsAt, lifetime, provenance, quantity, isEntitled, consumable, checkoutId, trialing, trialEndsAt, priority, reason, and grantedBy. `quantity` is the units bought (`null` when BillStack did not record it, never assume 1) and is kept on a refunded grant; `effective` ignores it. A grant with `consumable: true` and `isEntitled: false` is the record of a consumable purchase (a credit pack): it never counts toward `effective`, so do not map it to a plan or treat it as access; `checkoutId` is the checkout to read with `GET P/checkouts/{checkoutId}` for the amount paid and refund state, and credits belong in the application's own ledger keyed on that checkout. `trialing: true` means the grant is entitled (`status` stays `active`) on a free trial that ends at `trialEndsAt`, with nothing paid yet; both clear when the subscription converts. The example omits grants for brevity. `commercialKey` identifies what was bought: the canonical price variant ID for v2 checkouts (otherwise the provider product or source key). Active grants are reduced to one per `commercialKey` (latest endsAt kept), then the winner is the grant with the highest priority (always 0 except on manual grants), then the latest endsAt (null endsAt, open-ended, ranks first), ties broken by `sourceExternalId`; its plan and tier become `effective.plan` and `effective.tier`. Features and limits are not merged, so an add-on grant that outlasts the base plan can become `effective.plan`; derive add-on access from `grants` by `commercialKey` (status active, provenance verified). Effective entitlement combines grants; it is the access decision, not a raw Stripe subscription status. Inspect provenance and unresolvedGrantCount when diagnosing discrepancies.

`mode` is optional (`test` or `live`) and defaults to the key's environment, so a test key can never upgrade a production workspace. Read `effective.mode` and store it with the cache entry. Cache identity is `(BillStack team, BillStack project, mode, externalId, application workspace)` under verified application authorization. Reads use canonical grants/aggregates, not the team Stripe mirror or legacy `/entitlements/by-external-id` snapshot.

## Complimentary access (manual grants)

To give a customer a plan without a payment, call `POST P/entitlements/{externalId}/grants` from the backend with exactly one of `priceVariantId` or `tierAlias`, a `reason`, and an `idempotencyKey` (reuse the key when retrying). Optional: `startsAt`, `endsAt` (omit for an open-ended grant, which lasts until revoked) and `priority` (0 to 100, default 0). The response carries the new `grant` and the customer's `effective` access; `201` means created, `200` means the key had already created this grant, and the same key with a different request is `409 IDEMPOTENCY_CONFLICT`. The customer must already exist (`404 CUSTOMER_NOT_FOUND`); an unknown variant or tier alias is `404 PRICE_VARIANT_NOT_FOUND` or `404 TIER_NOT_FOUND`.

`GET P/entitlements/{externalId}/grants` (filters `status`, `sourceKind`) and `GET P/entitlements/{externalId}/grants/{grantId}` read every grant of the customer, whatever its source. `DELETE P/entitlements/{externalId}/grants/{grantId}` (optional body `{ "reason": "..." }`) soft-revokes a manual grant: it stays in `grants` with `status: "revoked"` and `isEntitled: false`. A subscription, payment, lifetime or referral grant answers `409 GRANT_NOT_MANUAL` and is never changed; cancel those at the payment provider. The SDK equivalents are `client.entitlements.grants.create`, `list`, `get` and `revoke`.

A manual grant is an ordinary entry in `grants` (`sourceKind: "manual"`, with `reason`, `grantedBy` and `priority`), so reconciliation needs no special case: re-read `effective` after creating or revoking one. What wins when the customer also pays is decided by priority, then the latest `endsAt`: an open-ended comp at priority 0 outlasts any finite paid period, so give a comp that should yield to a paid plan a finite `endsAt`, and give one that must win a `priority` above 0. A comp of an add-on competes for `effective.plan` like a paid add-on, so keep deriving add-on access from `grants` by `commercialKey`. Manual grants are separate for test and live, are not copied between environments, and do not appear in the legacy `/entitlements/by-external-id` snapshot. There is no MCP tool for them.

## Apply an application cache safely

Maintain, for each known subject, the effective fields, derived application plan, `fetchedAt`, last successful reconciliation time, and a fingerprint of the effective fields. These cache fields are application-owned. Store checkout/payment intent progress separately from effective access.

One shared backend reconciliation function should serve scheduled jobs, billing-page loads, and return flows:

1. Resolve the workspace's trusted team/project/mode/externalId mapping and serialize reconciliation for that subject across the network read and cache write. V2 exposes no version/updatedAt comparison for rejecting late concurrent responses.
2. Read `GET P/entitlements/{externalId}` with caching disabled, using the environment's own key (add `mode` only to assert it). Validate that the returned projectId, externalId, and mode match the expected mapping.
3. Inspect effective.isEntitled, status, startsAt, endsAt, and unresolvedGrantCount. Map an entitled, recognized plan through the application's allowlist. For a resolved non-entitled effective result, apply the application's configured free/no-paid-access plan. A retained paid plan label with isEntitled false does not authorize access.
4. Update the derived plan and cache atomically in your application database. Repeated identical snapshots are harmless; refresh fetchedAt and make any downstream application side effects idempotent by the snapshot fingerprint.
5. Recheck at endsAt as well as on the normal schedule. Do not retain access indefinitely because an old snapshot said isEntitled true. A null endsAt can represent non-expiring access; do not invent an expiry. BillStack recomputes effective access against the current time on reads.

Unknown plan aliases or unresolved grants require investigation; do not assign an arbitrary paid tier. The effective aggregate can preserve previous access while provenance is unresolved. Preserve that distinction in billing UI and operational alerts instead of treating an unresolved row as a new payment or as confirmed cancellation.

On HTTP 404 with error.code `ENTITLEMENT_NOT_FOUND`, a new subject has no canonical grant yet: show free or purchase-pending according to the application's tracked checkout state and retry pending fulfillment. This response does not prove that a payment failed. For a previously paid workspace, investigate missing/mismatched identity, mode, or migration rather than silently deleting its access record. A 403 is an authorization or environment failure (`UNAUTHORIZED`, `ENVIRONMENT_MISMATCH`, `LIVE_ENVIRONMENT_NOT_ENABLED`); a timeout, 429, 5xx, or invalid response is a reconciliation failure, not a free-plan snapshot. Record sanitized meta.requestId and schedule retries without overwriting the last confirmed entitlement with an invented result. Enforce the app's documented bounded stale-cache policy and known entitlement expiry while recovering.

## Lifecycle behavior

| Trigger | Source behavior and application action |
| --- | --- |
| Purchase | The redirect creates no entitlement proof. Keep purchase pending until signed provider events are processed and the effective read for the key's environment authorizes the intended plan. Use bounded backoff after return; keep scheduled reconciliation running if the browser never returns. |
| Renewal | Signed subscription events update grants and their period. Refresh effective access and endsAt; a paid invoice alone is not a new plan or an entitlement-status transition. Verify recurring subscription events are delivered and projected. |
| Trial start and conversion | A subscription started with `trialDays` yields an active, entitled grant with `trialing: true` and `trialEndsAt`; `endsAt` equals the trial end while trialing. Treat it as access without payment (for example, do not show a paid-since date). The conversion event clears `trialing`; a trial cancelled before it ends follows the cancel rows below. |
| Cancel at period end | Stripe active/trialing with cancel_at_period_end, or a cancel_at date within the current period, maps to a `canceling` grant. It can remain entitled until endsAt; refresh and show the end date rather than immediately assigning free because cancellation was requested in the portal or through the v2 subscription cancel route. |
| Immediate cancellation or expiry | Canceled/deleted subscription grants no longer grant access; expired period boundaries are respected on reads. Assign free/no-paid-access only when the effective aggregate is resolved and non-entitled. Another valid lifetime or provider grant can preserve access. |
| Plan change | A plan switched through the v2 subscription routes (`POST P/subscriptions/{subscriptionId}/change`) or the provider portal moves the grant to the new price variant only when the provider's subscription event is processed. After the call, refresh the entitlement and map the new `commercialKey` / plan; do not write the new plan from the change response alone. Pass the same `idempotencyKey` on a retry. |
| Failed payment | invoice.payment_failed is a financial event and does not directly revoke a subscription grant. A delivered subscription update with Stripe past_due maps to `billing_issue`, which can remain entitled before its endsAt. unpaid/incomplete/incomplete_expired/paused map to revoked grants. Read the effective result; do not invent a fixed grace period or immediately revoke on an invoice status. |
| Payment recovery | Read again after signed subscription updates restore the applicable grant/period; clear app billing-issue UI based on the refreshed effective result. A successful retry screen alone does not clear canonical billing state. |

Use source grants and effective contributors for explanations, not a rule that one subscription cancellation always removes all access. Verify each lifecycle on an authorized test subscription: purchase, renewal, scheduled cancellation, effective expiry or immediate cancellation, failed payment, and recovery. Record the provider event and processed inbox evidence plus the resulting effective read and application plan. If subscription/financial state contradicts effective access beyond the expected processing window, escalate canonical grant/provenance reconciliation to the operator; do not fabricate a grant or claim the lifecycle passed.

## Schedule and pagination

Choose a reconciliation cadence that matches the application's access-lag tolerance; every 5–15 minutes with jitter is a starting recommendation, not a BillStack guarantee or prescribed rate limit. Add refreshes on account/billing loads and after checkout/portal return. For pending purchase, use bounded exponential backoff, for example from 15 seconds up to 60 seconds for a maximum of 10 minutes; afterward show pending with support/retry and leave the scheduled job active. Read frequently enough to enforce known endsAt boundaries.

For bulk reads, use `GET P/entitlements?limit=50` (optional filters `externalId`, `status`, `mode`) and paginate `data.items` using the opaque, URL-encoded `data.nextCursor` until null. Maximum limit is 200; an invalid cursor returns 400 `INVALID_CURSOR`. The `status` filter is applied to each fetched page, so a page can hold fewer items than `limit`; keep following `nextCursor` until it is null. Keep team/project/mode and filters constant during pagination. No updated-since feed or snapshot transaction is advertised; re-run full passes and reconcile the application's known subjects, including targeted reads for previously paid workspaces missing from a pass. An absent list item is not a confirmed cancellation. Do not use an active-only filter for a downgrade reconciliation job.

Alert on repeated fetch failures, stale last-success times, unresolvedGrantCount, unknown plan labels, or purchase-pending beyond the processing window. Successful reconciliation must update only the mapped workspace and mode. BillStack remains billing source of truth; the application's database is a derived authorization cache, not a second subscription authority.
