Skip to content

TypeScript SDK

Use the published @billstack/sdk v2 client for typed, provider-neutral BillStack API calls.

BillStack exposes a REST API. The @billstack/sdk package provides a typed HTTP client with zero runtime dependencies. This page covers the v2 client, BillStackV2Client, which is the one to use for every new integration. For other languages, the v2 API is also described by an OpenAPI 3.1 specification.

Which client

BillStack has two API generations. Use v2 for every new integration.

ImportClientUse it for
@billstack/sdk/v2BillStackV2ClientRecommended. Provider-neutral (Stripe, Razorpay, RevenueCat), /api/billstack/v2/....
@billstack/sdk/legacyBillStackClientLegacy, Stripe-first. Existing integrations that already call /api/billstack/teams/.... Maintenance only, see Legacy TypeScript SDK.
@billstack/sdkbothThe package root exports both clients and is unchanged for compatibility.

The @billstack/sdk/v2 and @billstack/sdk/legacy subpaths are new in @billstack/sdk 0.7.0. Check the published version with npm view @billstack/sdk version --registry https://npm.w3api.dev. On an older version the subpath import fails with "Package subpath is not defined by exports", and 0.3.0 and earlier do not contain BillStackV2Client at all. If 0.7.0 is not on the registry yet, call the v2 HTTP API directly, as the quickstart does.

Install

bun add @billstack/sdk

This package is published to the public https://npm.w3api.dev registry. Add the scoped registry line to .npmrc; no auth token is needed to install:

@billstack:registry=https://npm.w3api.dev

Configure the client

import { BillStackV2Client } from "@billstack/sdk/v2";

const billing = new BillStackV2Client({
  baseUrl: process.env.BILLING_PORTAL_URL!,
  apiKey: process.env.BILLING_PORTAL_API_KEY!,
  teamId: process.env.BILLING_PORTAL_TEAM_ID!,
  projectId: process.env.BILLING_PORTAL_PROJECT_ID!,
});

Checkout, entitlements and portal

// One checkout for one customer. Country routing is off by default, so this
// goes to the team's default payment connection and needs no country. If you
// opted in to country routing, mint a country confirmation first and pass it
// as `countryConfirmation` (see "Regions and country routing").
const checkout = await billing.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  priceVariantId: variant.id,
  successUrl: "https://app.example.com/billing/success",
  cancelUrl: "https://app.example.com/billing/cancel",
  idempotencyKey: `checkout-${order.id}`,
});
// Send the customer to checkout.data.url

// What the customer may use right now, across providers
const { data } = await billing.entitlements.get(user.id);
data.effective; // the effective entitlement; data.grants lists the grants behind it

// A hosted portal session for the customer
const portal = await billing.portal.create({
  customerExternalId: user.id,
  returnUrl: "https://app.example.com/billing",
});
// Send the customer to portal.data.portalUrl

See the Entitlements guide for how to read and cache the result.

v2 resources

  • checkout, checkouts, portal: create hosted checkouts and portal sessions, read checkout intents, confirm the customer's country
  • catalog: products, price variants and their provider links
  • lifetimeDeals (in the release after 0.7.0; the HTTP routes work until then): stepped-price lifetime deals on a one-time Catalog price (create, launch, edit steps, end, sales, the refund list, revoke, and the public offers for a pricing page), see Lifetime deals
  • entitlements: effective entitlement per customer, plus entitlements.grants for complimentary grants
  • subscriptions: read and manage subscriptions across providers
  • financials: canonical payments, invoices, balances and other financial reads
  • providerConnections, providerBindings, routingRules: connect provider accounts and bind them to a project
  • referrals, credits: referral program, codes, attribution, checkout resolution, referrer view, reports and the credit ledger
  • webhookEndpoints, webhookDeliveries, webhookEventTypes: manage outbound webhook endpoints, delivery history and replay
  • regions: team-wide country routing
  • sandbox: native sandbox (bs_test_ keys only), see Native sandbox
  • entities: list, get and update the team's merchant entities, see Merchant entities
  • partnerPortal: createSession signs one of your customers in to the partner portal (live key only)

Separately from the client, every entry point exports webhooks.verify and webhooks.constructEvent (module functions, not client resources) to verify the BillStack-Signature header on incoming webhooks.

Payout requests and partner sessions (v2 client)

BillStackV2Client (0.4.1) covers the partner portal admin side. BillStack moves no money; these calls record decisions and your payment reference.

import { BillStackV2Client } from "@billstack/sdk/v2";

const client = new BillStackV2Client({ baseUrl, apiKey, teamId, projectId });

// Review payout requests (newest first, keyset paged)
const { data: page } = await client.referrals.payouts.list({ status: "requested" });
await client.referrals.payouts.approve(page.items[0].id);
await client.referrals.payouts.reject(id, "Details incomplete"); // note required
await client.referrals.payouts.markPaid(id, { externalReference: "wire-001" });

// Sign one of your customers in to the partner portal (live key only)
const { data: session } = await client.partnerPortal.createSession("user_123");
redirect(session.url);

ReferralProgram gained minPayoutAmount and partnerPortalEnabled, writable through referrals.program.update. Webhook event types payout.requested, payout.approved, payout.rejected, payout.paid, payout.cancelled and payout.credit_reversed are included in the typed events. There is no SDK wrapper for the payout CSV export; call GET .../referrals/payouts/export.csv directly. See Referral payout requests.

Regions and country routing (0.6.0)

BillStackV2Client 0.6.0 adds regions and customer-bound country confirmation. A region is one payment-provider account plus the countries it serves; the team's default region serves every country no other region claims. Concepts, limits and the full example are in Regions.

// Regions are team-wide (not project-scoped). Create, update and delete need
// a live key; a test key can read, activate, deactivate and run coverage in
// its own environment. Making a region the default is dashboard-only.
const india = await client.regions.create({
  name: "India",
  connectionId: razorpayConnectionId,
  countries: ["IN"], // ISO 3166-1 alpha-2; the UK is "GB"
});
const { data } = await client.regions.coverage(india.data.region.id, { mode: "live" });
if (data.coverage.ready) {
  await client.regions.activate(india.data.region.id, { mode: "live" });
}

The other methods are list, get, rename, setCountries, update, delete and deactivate. makeDefault is deprecated: changing the default region needs a dashboard session, so a call with an API key answers 403 UNAUTHORIZED.

client.entities (list, get, update) reads and edits the team's merchant entities: the legal merchant behind each provider account. Region.entity, Region.entityId and ProviderConnection.entityId say which entity bills a region; connection slots carry accountCountry and accountCurrency (Stripe only). See Merchant entities.

Outbound webhooks have a per-endpoint apiVersion: 2026-10-19 (the original body, kept for endpoints created before versions existed), 2026-10-22 (adds region) or 2026-10-26 (the same shape, plus the entitlement.updated, subscription.* and purchase.* events; the default for new endpoints). An endpoint only receives the event types that exist at its version, so move an existing endpoint with webhookEndpoints.update(id, { apiVersion: "2026-10-26" }) to receive the new ones; webhookEventTypes.list({ apiVersion }) lists what a version receives and BILLSTACK_WEBHOOK_EVENT_SINCE carries the same map. The payloads are typed as EntitlementUpdatedData, SubscriptionEventData and PurchaseEventData. webhookEndpoints.create and update accept it, webhookEventTypes.list returns latestApiVersion, legacyApiVersion and supportedApiVersions, and BillStackWebhookEvent is a union you narrow on event.apiVersion before reading event.region. See Outbound webhooks.

This section applies to projects that opted in to country routing (checkout.updateRoutingSettings({ countryRoutingEnabled: true }); it is off by default, and checkout then goes to the default connection without a country). A country confirmation is bound to one customer and works for one checkout. customerExternalId is required on checkout.confirmCountry() (breaking: a request without it is 400 COUNTRY_TOKEN_CUSTOMER_REQUIRED), the same value goes on checkout.create(), and every checkout attempt needs a fresh confirmation. Confirmations minted before the server upgrade are refused with COUNTRY_TOKEN_INVALID.

const confirmation = await client.checkout.confirmCountry({
  country: "IN",
  scope: "checkout",
  customerExternalId: user.id,
});

await client.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  priceVariantId,
  countryConfirmation: confirmation.data.confirmation,
  successUrl,
  cancelUrl,
  idempotencyKey: `checkout-${order.id}`,
});
  • A customer is pinned to a region at their first successful payment; after that the confirmed country is ignored.
  • Test API keys may send an unsigned country instead of countryConfirmation; a live key gets 400 COUNTRY_TOKEN_REQUIRED.
  • CheckoutInput.campaignTier sells a tier's lifetime campaign instead of a priceVariantId (pass exactly one). New errors: PRICE_UNAVAILABLE_IN_REGION (422), CAMPAIGN_UNAVAILABLE (409), LIFETIME_ALREADY_OWNED (409).
  • The webhook event type customer.region_conflict (payload type CustomerRegionConflictData) is raised when a customer pays in a region other than their pinned one. The payment is accepted and the pin kept; BillStack never refunds automatically. See Outbound webhooks.

Subscriptions (v2 client)

client.subscriptions manages an existing subscription from your server: read it, preview and apply a switch to another price variant, cancel it, and undo a scheduled cancel. The first argument is the provider subscription id (sub_123) or the grant's sourceExternalId; every call also names the customerExternalId that must own it. Behaviour, errors and provider support are in Subscription management.

const ref = "sub_123";
const customerExternalId = user.id;

const { data: subscription } = await client.subscriptions.get(ref, { customerExternalId });
if (subscription.actions.find((a) => a.key === "change_price")?.enabled) {
  const { data } = await client.subscriptions.previewChange(ref, {
    customerExternalId,
    priceVariantId: proVariantId,
    prorationBehavior: "always_invoice",
  });
  // Show data.quote.immediateAmountMinor to the customer, then apply the same quote.
  await client.subscriptions.change(ref, {
    customerExternalId,
    priceVariantId: proVariantId,
    idempotencyKey: `upgrade-${user.id}-${data.quote.expiresAt}`,
    quoteToken: data.quote.quoteToken,
  });
}

await client.subscriptions.cancel(ref, { customerExternalId, when: "period_end" });
await client.subscriptions.resume(ref, { customerExternalId });

Entitlement grants follow the provider's event, so read entitlements.get() again after a change instead of assuming the plan already moved. Stripe supports every method; for Razorpay only get and cancel with when: "period_end" work, and the others reject with 409 PROVIDER_ACTION_UNSUPPORTED. The types are ManagedSubscription, SubscriptionChangeQuote, SubscriptionChangeInput, SubscriptionChangeResult, SubscriptionCancelInput and SubscriptionMutationResult.

Error handling

import { BillStackV2Error } from "@billstack/sdk/v2";

try {
  await billing.entitlements.get("missing");
} catch (err) {
  if (err instanceof BillStackV2Error && err.status === 404) {
    // handle not-found
  }
}

Environment variables

BILLING_PORTAL_URL=https://billing.w3dev.app
BILLING_PORTAL_TEAM_ID=team_...
BILLING_PORTAL_PROJECT_ID=proj_...
BILLING_PORTAL_API_KEY=bs_test_...   # bs_live_... in production

The environment is decided by the key alone: bs_test_ keys see test data and bs_live_ keys see live data. apiKeyEnvironment(key) (exported from @billstack/sdk/v2) reports "test", "live" or null for a legacy bs_ key, which is live. A live key for a team with no live environment is rejected with LIVE_ENVIRONMENT_NOT_ENABLED.

Runtime key and setup token

BILLING_PORTAL_API_KEY is the project's runtime key. It covers what your app does at runtime: checkout, portal, entitlements, subscriptions, customers, payment methods, referrals, webhook endpoints and catalog reads. A key created since 2026-12-01 cannot create, update, archive, link or publish products and prices (createProduct, updateProduct, archiveProduct, createPriceVariant, archivePriceVariant, verifyPriceLink, publishPriceVariant); those calls fail with 403 USER_TOKEN_REQUIRED.

Run catalog setup with a personal access token instead. Pass it as apiKey in a second client, and keep it out of your app's environment:

BILLSTACK_SETUP_TOKEN=bsu_test_...   # your shell or agent only, not the deployed app

Keys created before 2026-12-01 are legacy full-access keys and still make these calls until a team admin restricts them.

See also API Keys and Authentication.