---
name: integrate-billstack
description: "v2 (provider-neutral). Integrate a SaaS application with BillStack at billing.w3dev.app using server-side HTTP APIs for checkout, entitlements, and customer portal sessions. Choose provider-neutral v2, connect existing Stripe accounts through explicit configuration, reconcile workspace plans from canonical entitlements, and test end to end with the keyless native sandbox, its simulate API and test clocks."
---

# Integrate BillStack

**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 to add billing to an application. For provider, catalog, and routing setup, load [configure-billstack-billing](https://billing.w3dev.app/.well-known/agent-skills/configure-billstack-billing/SKILL.md). These instructions describe supported source contracts; a deployment still needs configured providers, migrations, and working signed webhook delivery.

## Prerequisites and credentials

1. Open [BillStack](https://billing.w3dev.app), sign in or complete the site's available account setup, then create/select a team and project. If you do not have access, obtain membership from the team operator. Account creation is not a public billing API operation.
2. Copy team and project IDs. Create the project's app key from the project's Settings > Keys page. The raw key is shown once. The key-creation API requires a session; do not use another private key as a bootstrap credential. Two credentials do two jobs. The app key (`bs_`) is the runtime credential for your app's server: checkout, portal, entitlements, subscriptions, customers and catalog reads. A personal access token (`bsu_`, created under Account > Access tokens, or handed to you as `BILLSTACK_SETUP_TOKEN` by the setup wizard) is the setup credential: use it only from your own shell to create projects, products and prices. A new app key cannot write the catalog; such a call returns `403 USER_TOKEN_REQUIRED`, so retry it with the token.
3. Start in test. Every team has a test environment, so create a `bs_test_` key first and build against it. A `bs_live_` key works only after the team is promoted to live; before that, a live key gets `403 LIVE_ENVIRONMENT_NOT_ENABLED`. A legacy key (`bs_` followed directly by hex) has no environment in its prefix and runs in the environment stored for the key: live for keys issued before environments, test for keys of teams that were moved to test-only. Keep the key in a trusted backend. Publishable `pk_test_`/`pk_live_` keys are only for explicitly public legacy endpoints, never private v2 checkout or entitlement reads.
4. Know your key's access. A key created since 2026-12-01 is limited to the app-runtime policy, whatever IAM policies are attached. An older key (shown as "Full access (legacy)") without IAM attachments receives an admin-equivalent fallback until a team admin restricts it. Scope strings on a key are ignored. V2 uses permission-aware helpers and project restrictions; legacy routes can use broader access helpers.
5. For v2, configure an active connection with a test-mode account, a test-mode project binding, an active canonical price variant, a verified provider price link, a routing rule (single-provider teams) or an active region, and webhook/fulfillment readiness. A key sees only its own environment's provider links and bindings, so set these up for test before using a test key. Do not substitute legacy tier or Stripe price IDs for a canonical priceVariantId.

Set these in your app's server environment:

```text
BILLING_PORTAL_URL=https://billing.w3dev.app
BILLING_PORTAL_TEAM_ID=<team-id>
BILLING_PORTAL_PROJECT_ID=<project-id>
BILLING_PORTAL_API_KEY=<private-key-from-secret-store>
```

## Server helper

This example requires Node 18+ or Bun. `userId`, `confirmedCountry`, `priceVariantId`, `intentId`, and redirect URLs below come from your application's authenticated, validated server workflow. The key decides the environment: the example omits `mode`, so a `bs_test_` key runs in test and a `bs_live_` key in live. Never put the secret in a public environment variable or browser bundle.

```ts
const base = process.env.BILLING_PORTAL_URL;
const team = process.env.BILLING_PORTAL_TEAM_ID;
const project = process.env.BILLING_PORTAL_PROJECT_ID;
const key = process.env.BILLING_PORTAL_API_KEY;
if (!base || !team || !project || !key) throw new Error("Missing BillStack configuration");
const projectPath = `/api/billstack/v2/teams/${encodeURIComponent(team)}/projects/${encodeURIComponent(project)}`;
async function billing(path: string, body?: unknown) {
  const response = await fetch(`${base.replace(/\/$/, "")}${path}`, {
    method: body === undefined ? "GET" : "POST",
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: body === undefined ? undefined : JSON.stringify(body),
    cache: "no-store",
  });
  const result = await response.json();
  if (!response.ok) {
    throw new Error(`BillStack ${response.status}: ${result.error?.code ?? "REQUEST_FAILED"} (request ${result.meta?.requestId ?? "unknown"})`);
  }
  return result.data;
}
```

Keep authorization tied to the authenticated app user/tenant. Do not proxy arbitrary customer IDs, endpoints, or redirect URLs supplied by an untrusted browser. Log sanitized request IDs, not keys, confirmation tokens, portal URLs, or customer response bodies.

## V2 checkout and access

1. Only if the project enabled country routing (off by default): ask the customer to confirm their billing country. `GET .../country-advisory` is only a suggestion; never silently turn IP geography into confirmation. Request a signed confirmation with that country and the same customer identity used at checkout, and send it as `countryConfirmation`. Otherwise skip this step.
2. Persist a unique checkout intent ID in your application. Reuse it for retries of the same checkout request.
3. Create checkout and redirect to `data.url` from the full response (the helper below already unwraps data).

```ts
// Only when the project enabled country routing; otherwise leave it out.
const countryConfirmation = countryRoutingEnabled
  ? (await billing(`${projectPath}/country-confirmations`, {
      country: confirmedCountry, // ISO alpha-2, explicitly confirmed by the customer
      scope: "checkout",
      customerExternalId: userId,
    })).confirmation
  : undefined;
const checkout = await billing(`${projectPath}/checkout`, {
  externalId: userId,
  customerExternalId: userId,
  priceVariantId,
  countryConfirmation,
  idempotencyKey: intentId,
  successUrl: "https://your-app.example/account/billing?checkout=success",
  cancelUrl: "https://your-app.example/pricing?checkout=cancelled",
});
// Return checkout.url to the authenticated browser for navigation.
const entitlement = await billing(
  `${projectPath}/entitlements/${encodeURIComponent(userId)}`,
);
const canUsePaidFeatures = entitlement.effective.isEntitled;
```

The confirmation contains country, scope, token, confirmedAt, expiresAt, and customerExternalId; pass the returned object, not a fabricated token. A token is bound to one customer, expires after an hour and pays for one checkout, so request a fresh confirmation for every checkout attempt (a retry of the same checkout with the same `idempotencyKey` may reuse it). Error codes are `COUNTRY_TOKEN_REQUIRED`, `_CUSTOMER_REQUIRED`, `_CUSTOMER_MISMATCH`, `_INVALID`, `_EXPIRED` and `_ALREADY_USED`. Only a test API key may send an unsigned top-level `country` instead of a token. V2 checkout does not silently switch providers when routing fails.

Regions: a team may take Stripe and Razorpay at once, each region serving a list of countries (the default region serves every other country). The confirmed country decides the region until the customer's first successful payment pins them to the region they paid in; after that the pin decides and the country is ignored (still send a valid confirmation). You choose the price variant for the customer's country and BillStack chooses the region: a region without a verified link for that variant answers `422 PRICE_UNAVAILABLE_IN_REGION` (the token is not spent), and a region that cannot take payments answers `409 PROVIDER_UNAVAILABLE` and is never replaced by another provider. A Razorpay region sells INR only. To sell a tier's lifetime campaign send `campaignTier` instead of `priceVariantId` (errors `CAMPAIGN_UNAVAILABLE`, `LIFETIME_ALREADY_OWNED`). If a customer pays in a second region the payment is kept, the pin stays and a `customer.region_conflict` webhook event is raised for you to decide on a refund. Region setup belongs to configure-billstack-billing. Provider customer creation/mapping is handled by checkout where supported; do not use the legacy Stripe customer endpoint to provision a v2 account.

Checkout options (price-variant checkouts only): `trialDays` (integer 1-730, recurring prices), `allowPromotionCodes` (show the provider's code box), `promotionCode` (a merchant code the customer typed) and `referral: { code? }` (apply a BillStack referral discount; `code` omitted uses the customer's attribution, the customer needs an email on record, and the key needs `referral:ApplyCode` as well as `checkout:CreateCheckout`). `allowPromotionCodes: true`, `promotionCode` and `referral` are mutually exclusive (`400 CHECKOUT_OPTIONS_CONFLICT`), and a campaign checkout takes none of them. Only Stripe regions apply them: any other region answers `422 CHECKOUT_OPTION_UNSUPPORTED` rather than selling without the option, before the token is spent. Other 422 codes: `TRIAL_REQUIRES_RECURRING_PRICE`, `PROMOTION_CODE_NOT_FOUND`, `PROMOTION_CODE_INVALID`, `PROMOTION_CODE_IS_REFERRAL` (send referral codes as `referral.code`), `REFERRAL_REJECTED` (the reason is in `fieldErrors`), `REFERRAL_EMAIL_REQUIRED`, `REFERRAL_NOT_APPLICABLE`, `REFERRAL_TRIAL_DISCOUNT_WASTED` (a one-invoice referral discount would be spent on the free trial). Options are saved with the checkout and reused when the same `idempotencyKey` is retried; a different option set with the same key is `IDEMPOTENCY_CONFLICT`. A default trial on the price variant is not available.

Lifetime deals: to sell the current step of a plan's active lifetime deal, send `campaignTier: "<tierAlias>"` instead of `priceVariantId` (exactly one of the two; both or neither is `400 INVALID_REQUEST`). It sells one unit at the step price, then the price the deal discounts once every step is sold; a deal that is not on sale is `409 CAMPAIGN_UNAVAILABLE` and an owner gets `409 LIFETIME_ALREADY_OWNED`. Creating, launching and operating the deal is in [run-billstack-lifetime-deals](https://billing.w3dev.app/.well-known/agent-skills/run-billstack-lifetime-deals/SKILL.md).

Reading purchases: `GET ${projectPath}/checkouts/{checkoutId}` (the `checkoutId` the checkout call returned) and `GET ${projectPath}/checkouts` (filters `customerExternalId`, `idempotencyKey`, `priceVariantId`, `status`, plus `cursor`, `limit` 1-200 and `mode`; newest first). A checkout reports `status` (`open`, `completed`, `expired`, `failed`, `unknown`), `paymentStatus` (`unpaid`, `paid`, `refunded`), `quantity` (saved from the request, 1 if none), `amountMinor` and `currency` (what was paid; `null` until the payment event is processed), `unitAmountMinor`, `priceVariantId`, `paymentId`, `customerExternalId`, the `metadata` and `externalId` you sent, and `completedAt`. `completed` is set only by a signed provider payment event, never by a redirect, so poll with bounded backoff after the customer returns. A checkout of another project or environment is `404 CHECKOUT_NOT_FOUND`; an unknown `status` is `400 INVALID_FILTER`; a cursor the API did not issue is `400 INVALID_CURSOR`. For a consumable price variant (`billingScheme: "consumable"`, one-time only) the payment never grants access: fulfill when `status` is `completed` and `paymentStatus` is `paid`, credit your own ledger once per `checkoutId`, and reverse it on `refunded`. Do not read `effective` to detect a consumable purchase.

Success URLs are not proof of payment. Signed provider webhooks drive billing state; if fulfillment is pending, show a pending state and recheck entitlements with bounded backoff. Do not grant paid access because a redirect says success. Read `effective.status`, `endsAt`, and `unresolvedGrantCount` when explaining state.

Required IAM actions on the project: `checkout:CreateCheckout` (checkout, `country-advisory`, and `country-confirmations` with scope `checkout`), `checkout:GetCheckout` and `checkout:ListCheckouts` for reading purchases, `entitlement:GetEntitlement` for one subject, `entitlement:ListEntitlements` for the list, and `portal:CreateSession` (also for `country-confirmations` with scope `portal`). API calls still enforce team and project ownership.

Environment and `mode`: on v2 routes `mode` is optional and defaults to the key's environment. A key that names the other environment (for example `mode=live` with a `bs_test_` key, or `mode=test` with a `bs_live_` key) gets `403 ENVIRONMENT_MISMATCH`, and a checkout never writes into an environment other than the caller's. Omit `mode` unless you want that assertion. A price variant that has been archived in the catalog cannot be sold: a new checkout for it fails with `409 CANONICAL_PRICE_UNAVAILABLE`. Create a new variant for a new amount instead of reusing the archived ID.

## Workspace plans and entitlement synchronization

For workspace billing, persist a stable subject such as `workspace:<immutable-workspace-id>` and use it consistently as `externalId`, `customerExternalId`, country-confirmation customerExternalId, entitlement path identity, and portal customerExternalId. In the example above, replace userId with this trusted workspace subject. Verify the caller's workspace membership and billing role on your backend. Do not change existing billing subjects without an identity migration.

Load [sync-billstack-entitlements](https://billing.w3dev.app/.well-known/agent-skills/sync-billstack-entitlements/SKILL.md) for the authoritative cache, lifecycle, and reconciliation workflow. BillStack's outbound webhook endpoints (payload version `2026-10-26` and later) send `entitlement.updated`, `subscription.*` and `purchase.*` events; use them to refresh your cache sooner, but still implement periodic server-side reconciliation plus refresh after checkout/portal return and on billing/account loads, because events are at-least-once, unordered and not sent when a period merely runs out. Provider ingress and BillStack's five-minute worker are internal fulfillment, not callbacks to the app.

Canonical price tierAlias determines entitlement plan/tier, falling back to priceVariantId. Map approved plan aliases to your application's workspace features and limits. The v2 effective response exposes access, status, period boundaries, contributors, and unresolvedGrantCount; it does not expose legacy limits, enabledFeatures, version, or updatedAt. Keep test and live caches isolated (a test key and a live key read different environments) and grant access only from effective.isEntitled and the approved plan mapping. A single invoice or canceled subscription is insufficient to replace the combined effective result.

## Customer portal

```ts
const portal = await billing(`${projectPath}/portal`, {
  customerExternalId: userId,
  provider: "stripe",
  returnUrl: "https://your-app.example/account/billing",
});
// Return portal.portalUrl to this customer only.
```

Requires `portal:CreateSession`. BillStack resolves the stored provider/customer/account affinity; providerCustomerId is rejected, and `returnUrl` defaults to the BillStack origin when omitted, so always send your own. There is no `mode` parameter here: the portal runs in the key's environment and sees only that environment's customers, so a customer created with a test key has no portal under a live key (`404 CUSTOMER_PROVIDER_ACCOUNT_NOT_FOUND`). Multiple matching accounts may return CUSTOMER_PROVIDER_ACCOUNT_AMBIGUOUS; do not guess. This v2 route opens the provider's own portal: Stripe supports it; Razorpay and RevenueCat do not (`PROVIDER_ACTION_UNSUPPORTED`). A BillStack-hosted portal that also serves Razorpay customers exists only as a legacy route; see legacy-billstack-integration. With `@billstack/sdk` 0.7.0 or later `portal.create()` returns `{ sessionId, token, portalUrl, expiresAt }`; `url` is a deprecated alias, so read `portalUrl`. Treat session URLs as temporary sensitive links.

## Errors and retries

V2 returns `{ data, meta }` on success or `{ error: { code, message, fieldErrors? }, meta }` on failure. Relevant private routes return 403 UNAUTHORIZED for missing/disallowed credentials. Two other 403 codes are specific to environments: `ENVIRONMENT_MISMATCH` (the `mode` you sent differs from the key's environment; omit `mode` or use a key of the right environment) and `LIVE_ENVIRONMENT_NOT_ENABLED` (a live key for a team not yet promoted to live; use a `bs_test_` key or promote the team). `USER_TOKEN_REQUIRED` (403) means a project key tried a setup call; use the personal access token. Fix authorization instead of retrying. Invalid inputs return 400; inspect error.code and meta.requestId.

A created checkout replay returns its stored result. Reusing the key for a different request returns IDEMPOTENCY_CONFLICT. CHECKOUT_IN_PROGRESS means wait before checking again with the same intent; CHECKOUT_RECONCILIATION_REQUIRED means the provider outcome is unknown and an operator must reconcile it. Do not generate a new key to bypass that state. Preserve the original amount/price/customer/mode/URLs on retries; refresh expired confirmation only with valid customer confirmation. Do not assume other POST routes are idempotent.

## Fast end-to-end tests with the native sandbox

A team's test environment runs on either the payment provider's own test mode (the default) or the BillStack native sandbox, a simulated provider that needs no Stripe or Razorpay keys. The normal v2 calls work on both; the sandbox routes below answer `409 NOT_NATIVE_SANDBOX` on a team that uses the provider's test mode, which tells you which one applies. Switching sandbox resets the team's test billing data and needs a signed-in dashboard session (Integrations > Sandbox, typed confirmation `reset test data`), so ask the user to do it; do not try it with an API key, and never switch without the user's consent.

On a native-sandbox team the v2 checkout from the section above returns `data.url` pointing at a BillStack test checkout, and `data.sessionId` (`cs_sbx_...`) finishes it without a browser. All routes need a `bs_test_` key (a `bs_live_` key gets `403 SANDBOX_TEST_ONLY`) and sit under `/api/billstack/v2/teams/{teamId}/sandbox`:

```ts
const sandbox = `/api/billstack/v2/teams/${encodeURIComponent(team)}/sandbox`;
// Pay the checkout. outcome: pay | decline | insufficient_funds | require_authentication |
// cancel | complete_authentication | fail_authentication. `card` is optional and only with pay.
const paid = await billing(`${sandbox}/checkout-sessions/${checkout.sessionId}/simulate`, { outcome: "pay" });
// paid.status is complete | canceled | requires_action | card_error; paid.paymentId, paid.subscriptionId.
const entitlement = await billing(`${projectPath}/entitlements/${encodeURIComponent(userId)}`);
```

Test cards (Stripe's numbers): `4242 4242 4242 4242` succeeds; `4000 0000 0000 0002` declines; `4000 0000 0000 9995` insufficient funds; `4000 0000 0000 0341` attaches and then fails every charge, so use it only with `setPaymentMethod` to make a renewal fail (as the card of a checkout simulation it returns `card_error`); `4000 0025 0000 3155` needs authentication once; `4000 0027 6000 3184` needs authentication every time; `4000 0000 0000 0069` expired; `4000 0000 0000 0119` processing error. A declined card (`card_error`) leaves the session open, so try another card. Change the card a customer is charged with using `POST {sandbox}/customers/{customerId}/payment-method` with `{ card }`, and refund with `POST {sandbox}/payments/{paymentId}/refund` with an optional `{ amount }` in minor units.

Test clocks move time instead of waiting: `POST {sandbox}/clocks` with an optional `{ name, frozenTime }`, then `POST {sandbox}/clocks/{clockId}/advance` with `{ to }` (ISO 8601, later than the clock's `frozenTime`). Advance answers `202` with the clock `advancing`; poll `GET {sandbox}/clocks/{clockId}` with a short delay until `status` is `ready` (`internal_failure` is terminal: delete the clock and start over) and `frozenTime` equals `to`, then read the entitlement. Renewals, trial ends, failed-payment retries (1, 3, 5 and 7 days after the first failure, then the subscription is canceled) and cancellations at period end all run in order. A clock holds at most 10 customers, attached when the customer is created; no API route attaches a customer to a clock, so customers made by your own checkout renew on real time only, and a clock-driven renewal test needs sample data created in the dashboard (the sample-data card with "Attach to a new test clock", which a human or session does, not an API key). Do not assume the sandbox covers everything: proration, quantities above one, coupons, tax, metered billing, disputes and the provider customer portal are not simulated, and routes that call the payment provider directly answer `409 NATIVE_SANDBOX_UNSUPPORTED`. A native-sandbox run shows how your integration behaves, not how Stripe or Razorpay behave: run a final pass on the provider's test mode before going live.

With `@billstack/sdk` 0.7.0 or later the same calls are `client.sandbox.simulateCheckout`, `setPaymentMethod`, `refund` and `sandbox.clocks.create/get/advance/advanceAndWait/delete`. Full guide: https://docs.billing.w3dev.app/integration/native-sandbox; API reference: https://docs.billing.w3dev.app/api-reference/sandbox.

## SDK and verification

HTTP works without SDK installation. `@billstack/sdk` is published to the public `https://npm.w3api.dev` registry; installing needs only the scoped registry line `@billstack:registry=https://npm.w3api.dev` in `.npmrc` and no auth token. It is not on the default public npm registry, so that line is required. Use `BillStackV2Client` from `@billstack/sdk/v2` (needs `@billstack/sdk` 0.7.0 or later; versions 0.3.0 and earlier do not contain it, so use HTTP if 0.7.0 is not on the registry); the legacy `BillStackClient` (`@billstack/sdk/legacy`) belongs to the legacy skill. Some HTTP options are newer than the SDK types; use documented HTTP instead of casting unsupported fields.

The v2 API also has a machine-readable OpenAPI 3.1 description at https://billing.w3dev.app/api/billstack/v2/openapi.json (public, no key needed). Read it to look up the path, parameters, request body, response and error shapes, and the required permission of any v2 route, or to generate a client for another language. It describes the same behaviour as this skill; if it and a live response disagree, trust the live response.

Verify an authorized test journey with a `bs_test_` key end to end: configured price and routing -> checkout -> test payment (on a native-sandbox team, the simulate route above) -> signed webhook -> effective entitlement -> supported portal. Record provider/mode and sanitized request IDs. Going live is a separate intentional step: promote the team in the dashboard (**Promote to live**; there is no public v2 API for it), then use a `bs_live_` key with live credentials, bindings, price links (publish or link the variant for live), and routing. Customers and subscriptions are not carried over from test to live.
