Skip to content

Multi-provider v2 integration

Connect provider accounts, publish canonical prices, route checkout, and read provider-neutral entitlements.

Country routing is opt-in per project

Country routing is disabled by default for every project, including existing projects. Ordinary checkout uses the configured default payment connection. An existing customer pin keeps its connection; an unavailable pinned or default connection fails instead of choosing another provider. Direct checkout requires neither country input nor a confirmation token, and does not evaluate country-based rules. Provider bindings, authenticated webhook and fulfillment readiness, verified prices, explicit pauses and checkout idempotency still apply.

Read GET /api/billstack/v2/teams/{teamId}/projects/{projectId}/routing-settings (billing:GetBilling). Explicitly opt in with PATCH on that path and { "countryRoutingEnabled": true } (billing:UpdateBilling, live credential or dashboard session). Set it to false to return to direct checkout. The setting covers both environments of that project; team-wide rollout flags or checkout request fields cannot enable it.

SDK equivalents are billing.checkout.getRoutingSettings() and billing.checkout.updateRoutingSettings({ countryRoutingEnabled: true }). Only opted-in projects need the country-confirmation flow documented below. They retain routing rollout/canary controls, signed customer-bound tokens and single-use enforcement. country-advisory.manualConfirmationRequired reports the project's current setting.

This guide uses the additive v2 API and @billstack/sdk. It assumes a server-side integration and two credentials with different jobs. Keep both and all provider credentials out of your app's code and browser bundles.

  • Project API key (bs_test_ or bs_live_): the runtime credential. Your app's server uses it for checkout, entitlements, customers, subscriptions and catalog reads. A key created since 2026-12-01 cannot write the catalog.
  • Personal access token (bsu_test_ or bsu_live_): the setup credential. You or your coding agent use it to create projects, products and prices, as in the catalog section below. It acts as you. See Personal access tokens.
import { BillStackV2Client } from "@billstack/sdk";

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!,
});

Existing Stripe accounts and first-time test setup

An existing legacy team Stripe integration does not automatically populate v2 provider connections, project bindings, canonical catalog, or routing. Empty authenticated v2 lists can coexist with an active legacy account. A new test integration can connect the same Stripe account using authorized test credentials and create the v2 configuration without backfilling history. Historical migration remains an operator-reviewed preflight/backfill/verification procedure; there is no public import endpoint.

Follow the public Configure BillStack billing skill for the complete test setup, actual webhook signing secret, non-payment readiness probe, and migration boundaries. This page's live SDK examples require separately prepared live credentials, objects, and readiness.

Connect test and live accounts

Create one logical connection for a provider, then verify each credential slot you use. Keep test and live credentials separate. The response contains an immutable accountIncarnationId for each mode and a mode-specific webhook URL. Rotating a credential adds a new incarnation and keeps the old one for history, so a mode can list several slots: only the one with active: true serves keys, and the rotated-away one reports status: "disconnected".

const stripeConnection = await billing.providerConnections.create({
  provider: "stripe",
  mode: "live",
  credentials: { secret: process.env.STRIPE_LIVE_SECRET! },
});

await billing.providerConnections.verify(stripeConnection.data.connection.id, {
  mode: "live",
});

// Add the test slot on the same logical provider connection when you need it.
await billing.providerConnections.rotate(stripeConnection.data.connection.id, {
  mode: "test",
  credentials: { secret: process.env.STRIPE_TEST_SECRET! },
});

The same flow works for Razorpay and RevenueCat with their provider-specific credential fields. Razorpay verification requires a key ID, key secret, and an expected merchant account ID in credential metadata. RevenueCat verification requires the RevenueCat project ID in credential metadata.

A team can connect one account of each payment provider: one Stripe account and one Razorpay account side by side. Connecting a second account of the same provider returns 409 CONNECTION_ALREADY_EXISTS; if two legal entities both need Stripe, use a separate team for each (see Limitations). RevenueCat is an entitlement source, not a payment provider, and can be connected next to either. Test and live credentials of a provider are two slots of the same connection. A credential rotation that resolves to a different external account creates a new immutable account incarnation so historical records stay attached to their original account.

The first payment provider you connect (or the one chosen when the team was created) becomes the team's default region. Connecting a second provider does not change what customers pay through until you create and activate a region for it; see Regions.

Bind a provider to a project

Bindings select which team connection and mode a project uses. A binding does not copy credentials into the project.

const stripeBinding = await billing.providerBindings.create({
  connectionId: stripeConnection.data.connection.id,
  mode: "live",
  configuration: { checkoutPrefix: "live" },
});

await billing.providerBindings.verify(stripeBinding.data.binding.id);

Create a separate binding for test mode if you use test checkouts. New checkout routing and provider operations use the binding's immutable account incarnation.

Create the product and price once in the project catalog. Provider links are part of the price response and carry their provider price ID, status, and verification evidence.

Creating, linking, publishing and archiving catalog objects is setup work. Run it with a personal access token, passed to the SDK as apiKey in a separate setup client (its environment is null, because only bs_ and pk_ prefixes name one). A project key created since 2026-12-01 gets 403 USER_TOKEN_REQUIRED on these calls, while the catalog reads (such as listPriceVariants) work with it. Your app's runtime client keeps the project key. A legacy full-access key still works for both until you restrict it.

const setup = new BillStackV2Client({
  baseUrl: process.env.BILLING_PORTAL_URL!,
  apiKey: process.env.BILLSTACK_SETUP_TOKEN!, // bsu_test_...
  teamId: process.env.BILLING_PORTAL_TEAM_ID!,
  projectId: process.env.BILLING_PORTAL_PROJECT_ID!,
});

The examples below call billing.catalog; for the write calls, use the setup client.

const product = await billing.catalog.createProduct({
  name: "Pro",
  description: "Monthly Pro plan",
});

const price = await billing.catalog.createPriceVariant({
  productId: product.data.product.id,
  amountMinor: 1200,
  currency: "USD",
  interval: "month",
});

const euroPrice = await billing.catalog.createPriceVariant({
  productId: product.data.product.id,
  amountMinor: 1100,
  currency: "EUR",
  interval: "month",
});

const catalog = await billing.catalog.listPriceVariants();
const links = catalog.data.priceVariants.find(
  (item) => item.id === price.data.priceVariant.id,
)?.providerLinks;

const verifiedStripeLink = await billing.catalog.verifyPriceLink({
  priceVariantId: price.data.priceVariant.id,
  provider: "stripe",
  connectionId: stripeConnection.data.connection.id,
  mode: "live",
  externalProductId: process.env.STRIPE_LIVE_PRODUCT_ID!,
  externalPriceId: process.env.STRIPE_LIVE_PRICE_ID!,
});

const verifiedEuroLink = await billing.catalog.verifyPriceLink({
  priceVariantId: euroPrice.data.priceVariant.id,
  provider: "stripe",
  connectionId: stripeConnection.data.connection.id,
  mode: "live",
  externalProductId: process.env.STRIPE_LIVE_PRODUCT_ID!,
  externalPriceId: process.env.STRIPE_LIVE_EUR_PRICE_ID!,
});

Publish instead of linking (Stripe). Rather than creating the Stripe price yourself, publish the variant. BillStack creates the Stripe product and price in the account of the project's active binding for that mode, verifies it and saves the link. Publishing again returns the same link:

const published = await billing.catalog.publishPriceVariant(
  price.data.priceVariant.id,
  { mode: "test" },
);
published.data.providerLink.status; // "verified"

In the dashboard, Project → Catalog does the same: in the test environment "Add price" publishes to test by default, and live always needs an explicit, confirmed Publish to live. The page shows, for every price, whether it is published in test and in live.

A Razorpay team links its plan the same way, with provider: "razorpay", its own connection ID, the Razorpay plan ID as externalPriceId, and metadata: { razorpayTotalCount: 12 }.

Checkout requires a verified provider link for the selected account incarnation. unverified and quarantined links cannot be used. The public v2 SDK exposes catalog creation, link reads, and verifyPriceLink. The server resolves credentials from the selected connection's immutable mode incarnation, then validates amount, currency, billing type, interval, and provider metadata before persisting a verified link. A link is never accepted from caller claims alone.

Establish readiness before activating routing

Credential verification and price linking do not prove signed delivery or fulfillment. Register the slot's canonical webhook URL in the actual provider account/mode and store that endpoint's signing secret with the API credentials through connection rotation. The BillStack operator must enable canonical capture on the service and verify the provider-event worker is registered and running.

For Stripe test setup, enable customer.created and create a disposable test customer in that account before the first routed checkout. Verify its signed event is accepted and processed, then read back the exact test slot's authenticated webhook and fulfillment readiness. This pipeline probe needs no payment and resolves the readiness prerequisite before routing activation. See the configuration skill for full event and operator diagnostics; a successful probe alone does not grant a purchased plan.

Regions: sell through more than one provider

A team can take payments through Stripe and Razorpay at the same time and decide per country which one collects. The unit is a region: one payment-provider account plus the countries it serves.

  • One account per provider. A team connects at most one Stripe and one Razorpay account, so a team has at most two regions. Two Stripe accounts in one team is not supported (see Limitations).
  • Each country belongs to one region. The default region owns no country list: it serves every country that no other region claims, so every country is always covered. The first payment provider a team connects becomes the default.
  • One team, one integration. Same API key, SDK client, customer list and entitlement view. Entitlements are derived the same way whichever provider took the payment.
  • Per-environment status. A region is draft or active separately in test and live. A draft region claims no countries; its countries are served by the default region. A region that was activated but whose connection can no longer serve (keys removed, connection disabled or disconnected) is unavailable.
  • No silent fallback. An unavailable region does not hand its customers to another provider. Checkout for its countries fails with 409 PROVIDER_UNAVAILABLE until the connection is back or you deactivate the region on purpose (which sends its countries to the default region).

Customers are pinned at their first payment

A customer is pinned to a region when their first payment succeeds, not when a checkout is created.

  • Before the first payment, every checkout is routed again by the confirmed country, so a customer who tries from two countries can have open checkouts in two regions.
  • At the first confirmed payment the customer is pinned to the region that was paid in, and their other open checkouts in other regions are closed on a best effort basis.
  • After that, every new checkout uses the pinned region and the confirmed country is ignored (a mismatch is only logged). Moving country never re-routes a customer. You still send a valid country confirmation; it is checked and spent as usual.
  • If the pinned region is unavailable, checkout fails with PROVIDER_UNAVAILABLE; it never falls back to the rules or to another region.
  • If a second payment still completes in another region (for example an old checkout link), BillStack accepts it, keeps the first pin, records the payment against the region actually paid in and raises customer.region_conflict so you can decide on a refund. It never refunds silently.

Example: Stripe for the world, Razorpay for India

Stripe is the default region and serves the US, the UK (GB), Australia (AU) and everyone else. Razorpay serves IN in INR. Country codes are ISO 3166-1 alpha-2, so the United Kingdom is GB, not UK.

// 1. Stripe is already connected, so it is the default region.
// 2. Connect Razorpay next to it.
const razorpay = await billing.providerConnections.create({
  provider: "razorpay",
  mode: "live",
  credentials: {
    publishableKey: process.env.RAZORPAY_LIVE_KEY_ID!,
    secret: process.env.RAZORPAY_LIVE_KEY_SECRET!,
    metadata: { razorpayAccountId: process.env.RAZORPAY_ACCOUNT_ID! },
  },
});

// 3. Create the region. It starts as a draft in both environments.
const india = await billing.regions.create({
  name: "India",
  connectionId: razorpay.data.connection.id,
  countries: ["IN"],
});

// 4. Give every variant India can buy a verified Razorpay link. Razorpay sells
//    INR only; Stripe keeps serving USD, GBP and AUD variants.
await billing.catalog.verifyPriceLink({
  priceVariantId: inrPrice.data.priceVariant.id,
  provider: "razorpay",
  connectionId: razorpay.data.connection.id,
  mode: "live",
  externalPriceId: process.env.RAZORPAY_LIVE_PLAN_ID!,
  metadata: { razorpayTotalCount: 12 },
});

// 5. Check what activation needs, then activate per environment.
const coverage = await billing.regions.coverage(india.data.region.id, {
  mode: "live",
});
if (coverage.data.coverage.ready) {
  await billing.regions.activate(india.data.region.id, { mode: "live" });
}

At checkout the customer confirms a country and you choose the price variant for that country; BillStack chooses the region.

const country = selectedCountryFromCheckoutForm; // "IN", "GB", "AU", "US", ...
const confirmation = await billing.checkout.confirmCountry({
  country,
  scope: "checkout",
  customerExternalId: user.id,
});

const variantByCountry = { IN: inrPrice, GB: gbpPrice, AU: audPrice };
const variant = variantByCountry[country] ?? usdPrice;

const checkout = await billing.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  priceVariantId: variant.data.priceVariant.id,
  countryConfirmation: confirmation.data.confirmation,
  successUrl: "https://app.example.com/billing/success",
  cancelUrl: "https://app.example.com/billing/cancel",
  idempotencyKey: `checkout-${order.id}`,
});

An Indian customer who is sent a USD variant, or a customer in another country who is sent the INR variant, gets 422 PRICE_UNAVAILABLE_IN_REGION: the region they were routed to has no verified link for that price. BillStack never swaps in another region's price. The same applies to a Razorpay region and a non-INR variant. For a team with a single region, a missing link keeps failing as a provider checkout error (400 PROVIDER_CHECKOUT_FAILED) as before.

In the dashboard, Team → Integrations has the same controls: connect the second provider, add the region, pick countries from the list of all ISO codes, and activate it. The activate dialog shows the coverage report first.

Manage regions with the API and SDK

Regions are team-wide (they apply to every project and to both environments), so the routes sit under /teams/{teamId}/regions and the SDK methods under billing.regions. See the API reference.

SDK methodWhat it does
regions.list() / get(id)Regions with countries, per-environment status and availability.
regions.create({ name, connectionId, countries? })New draft region on a connection that has none.
regions.rename(id, name) / setCountries(id, countries) / update(id, { name?, countries? })countries replaces the whole list.
regions.coverage(id, { mode? })Variants without a verified link (these block activation), currencies the provider cannot charge, hand-written rules that stop applying, lifetime campaigns that would be paused.
regions.activate(id, { mode }) / deactivate(id, { mode })Start or stop selling through the region in one environment.
regions.makeDefault(id)Deprecated: an API key is refused (403 UNAUTHORIZED). Make a region the default in the dashboard; pinned customers do not move.
regions.delete(id)Non-default region that nothing references.

Rules to know:

  • A live API key or a dashboard session is needed to create, change or delete a region. Making a region the default is dashboard-only, because it changes the team's default payment provider. A test key can read regions, and can run activate, deactivate and coverage for its own environment; other calls get 403 ENVIRONMENT_MISMATCH.
  • Activating a non-default region needs the default region to be active in that environment (DEFAULT_REGION_UNAVAILABLE), a usable key slot for the environment (MODE_NOT_CONNECTED) and no coverage gaps (REGION_COVERAGE_GAPS, with the first gaps in fieldErrors).
  • Deactivating a region sends its countries to the default region and warns with COUNTRIES_REROUTE_TO_DEFAULT; pinned customers of the region then fail with PROVIDER_UNAVAILABLE.
  • The default region cannot be deactivated or deleted (DEFAULT_REGION_PROTECTED). Make another region the default first.
  • A region cannot be deleted while pinned customers, subscriptions, checkouts or provider accounts reference it (REGION_IN_USE); deactivate it instead.
  • Country lists must be valid ISO codes (INVALID_COUNTRY) and a country already owned by another region is 409 COUNTRY_CONFLICT.
  • A team that still holds Stripe or Razorpay credentials outside a provider connection (set up through the legacy project settings) must connect them as provider connections first: 409 LEGACY_PROVIDER_CONNECTION_REQUIRED.
  • Webhooks: register each connection's canonicalWebhookUrl with its provider, as for any routed checkout. A Razorpay region does not need the legacy per-team Razorpay URL.

In a team with more than one active region a lifetime campaign can only be active if it has a price for every active region: a Stripe region sells the step's own Stripe price, a Razorpay region needs a regional alternate (see Lifetime deal campaigns). A campaign without one cannot be activated (CAMPAIGN_REGION_ALTERNATE_MISSING), and an active one is paused when a region is activated.

Features that exist only on Stripe return 409 FEATURE_UNAVAILABLE_IN_REGION for a customer in a Razorpay region: public payment links, referral credit payouts (the credit fails at apply time and needs manual handling) and v1 Stripe subscription changes. A Razorpay subscription can be cancelled at the end of the period, but not resumed or cancelled immediately; the v2 subscription management routes answer 409 PROVIDER_ACTION_UNSUPPORTED for those.

Limitations

  • One account per provider per team. Two Stripe accounts (or two Razorpay accounts) in one team are not supported. If two legal entities both need Stripe, create a separate team for each; each team has its own API key, customers and entitlement view.
  • Regions are a v2 feature. The legacy v1 checkout (/checkout/start) serves the default region only and never takes a country. A customer pinned to a non-default region gets 409 REGION_REQUIRES_V2 on v1 and is never billed in the default region instead; use the v2 checkout for them. An unpinned customer on v1 pays through the default region.
  • Hand-written routing rules are frozen in a multi-region team (see routing rules).
  • No automatic re-homing. A pinned customer stays in their region; moving them is a manual operator task.
  • Reporting is per currency. BillStack does not convert currencies across regions.
  • A trial or zero-amount start pins nobody; only a confirmed payment does.

Add optional routing rules

Hand-written routing rules are for teams with one region (one payment provider). Once a team has more than one region, regions decide where each customer pays and country is the only routing input: existing hand-written rules are kept but no longer evaluated, and creating or editing one returns 409 ROUTING_RULES_FROZEN_MULTI_REGION. If the team drops back to one region they apply again.

In a single-region team, routing is opt-in and chooses among the prices of the team's only provider (for example by currency or country); it never chooses a provider. A project can create a generic default or a conditional rule and then validate and activate it. Activation requires all of the following:

  • an active, verified provider connection slot and project binding;
  • a verified provider price link for the referenced canonical price, or at least one usable verified link when the rule does not name a price;
  • provider capability, currency, billing type, and interval compatibility; and
  • webhook delivery and fulfillment readiness for the selected account.
const stripeDefaultRule = await billing.routingRules.create({
  name: "Stripe USD default",
  priority: 10,
  isDefault: true,
  conditions: {
    currency: ["USD"],
    priceVariantId: price.data.priceVariant.id,
  },
  connectionId: stripeConnection.data.connection.id,
  mode: "live",
});

await billing.routingRules.validate(stripeDefaultRule.data.rule.id);
await billing.routingRules.activate(stripeDefaultRule.data.rule.id);

const euroRule = await billing.routingRules.create({
  name: "Germany EUR",
  priority: 100,
  isDefault: false,
  conditions: {
    country: ["DE"],
    currency: ["EUR"],
    priceVariantId: euroPrice.data.priceVariant.id,
  },
  connectionId: stripeConnection.data.connection.id,
  mode: "live",
});

await billing.routingRules.validate(euroRule.data.rule.id);
await billing.routingRules.activate(euroRule.data.rule.id);

The two rules above are explicit user-created rules. BillStack does not seed or enable either rule, and it does not infer a provider from an IP address. Your application may show an advisory country, but the customer must confirm the country before routing. The default rule is constrained to the USD Stripe price, so it cannot route the EUR price without its own verified link.

For a generic fallback, create an explicit isDefault: true rule with empty conditions. A default rule is still subject to provider and canonical-link validation. No matching rule returns NO_ELIGIBLE_PROVIDER; BillStack does not silently switch to another provider.

Suggest and confirm a country

Country suggestions are advisory. checkout.suggestCountry() can use a platform-attached server geo value, or an explicit country supplied by your server after its own trusted geo lookup. The SDK cannot see the end-user IP. Proxy headers such as x-forwarded-for, x-vercel-ip-country, and cf-ipcountry are ignored by the API.

const suggestion = await billing.checkout.suggestCountry({
  // Pass this only from your trusted server-side geo integration.
  advisoryCountry: "DE",
});

// Render the suggestion in your checkout UI and let the customer choose.
// This value comes from the customer's explicit selection, not from the
// advisory response or a default country.
const customerConfirmedCountry = selectedCountryFromCheckoutForm;

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

The suggestion never issues a token. The confirmation response is a signed token bound to the team, project, environment, scope, country, and customer. It expires after one hour and works for one checkout: request a new confirmation for every checkout attempt. customerExternalId is required when requesting a confirmation and must be sent again on checkout. Minting a confirmation does not create a customer. The confirmed country decides the region for a customer who has not paid yet; a customer who has paid is routed to their pinned region.

CodeStatusMeaning
COUNTRY_TOKEN_REQUIRED400Checkout carried no signed token (live keys always need one).
COUNTRY_TOKEN_CUSTOMER_REQUIRED400The confirmation or the checkout request named no customer.
COUNTRY_TOKEN_CUSTOMER_MISMATCH400The token was issued for another customer.
COUNTRY_TOKEN_INVALID400Bad signature, other team, project, environment, scope or country, or a token issued before single-use tokens existed.
COUNTRY_TOKEN_EXPIRED400The token is older than one hour.
COUNTRY_TOKEN_ALREADY_USED409The token already paid for another checkout. Repeating the same checkout with the same idempotencyKey still works.

The token is spent just before the checkout is created. A checkout that fails for another reason can be retried with the same idempotencyKey and token; a checkout with a new key needs a new confirmation.

Test keys

A test API key may skip the token and send an unsigned country on checkout, so you can exercise every region from a script:

await billing.checkout.create({
  externalId: "checkout-1",
  customerExternalId: user.id,
  priceVariantId: price.id,
  country: "IN", // test API keys only
  successUrl,
  cancelUrl,
  idempotencyKey: "checkout-1",
});

Live keys never accept this: they get COUNTRY_TOKEN_REQUIRED whatever else the request contains. The key decides the environment, not a request parameter. A test key that sends a signed token works as usual.

Create an idempotent checkout

Use one stable idempotency key for one checkout intent and retry the same request when the response is lost. Reusing the key with a different customer, price, mode, URL, or metadata returns an idempotency conflict. An ambiguous provider outcome is kept unresolved for reconciliation; do not create a second checkout with a new key automatically.

const selectedPriceVariant =
  customerConfirmedCountry === "DE"
    ? euroPrice.data.priceVariant
    : price.data.priceVariant;

const checkout = await billing.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  priceVariantId: selectedPriceVariant.id,
  countryConfirmation: confirmation.data.confirmation,
  successUrl: "https://app.example.com/billing/success",
  cancelUrl: "https://app.example.com/billing/cancel",
  idempotencyKey: `checkout-${order.id}`,
});

return checkout.data.url;

Trials, promotion codes and referrals

Add trialDays, allowPromotionCodes, promotionCode or referral to a price-variant checkout to start a free trial or apply a discount. They are available in Stripe regions; any other region answers 422 CHECKOUT_OPTION_UNSUPPORTED instead of selling the checkout without the option.

const checkout = await billing.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  priceVariantId: monthlyPrice.id,
  countryConfirmation: confirmation.data.confirmation,
  trialDays: 14,
  referral: { code: referralCodeFromLink },
  successUrl: "https://app.example.com/billing/success",
  cancelUrl: "https://app.example.com/billing/cancel",
  idempotencyKey: `checkout-${order.id}`,
});
  • trialDays (1 to 730) is for recurring prices; on a one-time price it is 422 TRIAL_REQUIRES_RECURRING_PRICE. The card is still collected at checkout.
  • promotionCode applies a code you created in your payment account and the customer typed in your own form. allowPromotionCodes: true instead shows the provider's promotion-code box on the hosted page.
  • referral applies a BillStack referral discount. Send code when the customer arrived with one, or {} to use the code they were already attributed to. It runs the same check as the checkout-resolution endpoint on the price being sold and records the attribution, so the referrer is credited when the customer pays. The customer must have an email on record. A rejected referral answers 422 REFERRAL_REJECTED with the reason in fieldErrors; to fall back softly, call checkout without referral when you get it.
  • A checkout takes one discount at most: allowPromotionCodes: true, promotionCode and referral cannot be combined (400 CHECKOUT_OPTIONS_CONFLICT). A referral whose discount lasts one invoice cannot be combined with a trial (422 REFERRAL_TRIAL_DISCOUNT_WASTED): the trial invoice would use it up. Give the program a repeating discount, or drop the trial.

The options are resolved before the country token is spent and are saved with the checkout, so retrying with the same idempotencyKey is safe and reusing the key with different options is an idempotency conflict. While the customer is trialing, their grant shows trialing: true (see Entitlements). A default trial on the price variant is not available; send trialDays with each checkout.

Sell a lifetime campaign

Pass campaignTier instead of priceVariantId to sell the lifetime campaign of a tier. The customer is routed to a region like any checkout and is sold that region's price for the current step: the step's Stripe price in a Stripe region, or, in a Razorpay region, a payment link at the step's regional alternate.

const checkout = await billing.checkout.create({
  externalId: `checkout-${user.id}-${order.id}`,
  customerExternalId: user.id,
  campaignTier: "growth",
  countryConfirmation: confirmation.data.confirmation,
  successUrl: "https://app.example.com/billing/success",
  cancelUrl: "https://app.example.com/billing/cancel",
  idempotencyKey: `checkout-${order.id}`,
});

A region without a price for the campaign answers 422 PRICE_UNAVAILABLE_IN_REGION and a tier with no lifetime offer on sale answers 409 CAMPAIGN_UNAVAILABLE; the token is not spent in either case. A Razorpay payment for a campaign is settled when the connection's webhook delivers it, so the connection's canonicalWebhookUrl (see below) must be registered with Razorpay, as for any routed checkout; nothing else needs to be enabled.

A customer who opens campaign checkouts in two regions can pay both. The first payment pins the customer and closes the other region's open checkout; if the other one is paid anyway, BillStack keeps the money, does not sell a second campaign unit or entitlement, records the payment as needing a refund review, and raises customer.region_conflict for endpoints subscribed to it.

Configure webhooks

Register the canonicalWebhookUrl from the verified connection slot with the provider. It is returned as a relative URL, so prepend your BillStack base URL. Configure one endpoint for each mode and immutable account incarnation.

const connection = await billing.providerConnections.get(
  stripeConnection.data.connection.id,
);
const liveSlot = connection.data.connection.slots.find(
  (slot) => slot.mode === "live",
);
const webhookUrl = new URL(
  liveSlot!.canonicalWebhookUrl,
  process.env.BILLING_PORTAL_URL!,
).toString();

The provider must sign deliveries with the webhook secret stored in the connection slot. BillStack authenticates the exact team, connection, mode, and incarnation before capturing the event. Keep the legacy provider webhook endpoint during a migration when your rollout plan requires it; do not replace it with a client-side webhook.

Read entitlements

The v2 read is project-scoped and defaults to live mode. Test mode is an explicit independent read.

const entitlement = await billing.entitlements.get(user.id);

if (
  entitlement.data.effective.isEntitled &&
  entitlement.data.effective.unresolvedGrantCount === 0
) {
  // Grant access according to your product policy.
}

The response includes the derived effective decision and source grants. Each grant also reports quantity (units bought, null when not recorded) and, for a subscription on a free trial, trialing: true with trialEndsAt. A grant with provenance: "unknown" or "quarantined" is visible but is not verified evidence. An absent endsAt does not mean lifetime; the grant's explicit source kind determines that flag. Do not authorize from provider API objects or a successful redirect.

To list many subjects, pass the returned opaque nextCursor back to the next request. The cursor is scoped to this project and mode, and malformed cursors are rejected.

const firstPage = await billing.entitlements.list({ limit: 50 });
const nextPage = firstPage.data.nextCursor
  ? await billing.entitlements.list({
      limit: 50,
      cursor: firstPage.data.nextCursor,
    })
  : null;

Synchronize application workspace plans

Follow Synchronize BillStack entitlements for stable workspace subjects, canonical plan aliases, cache boundaries, and purchase/renewal/cancellation/payment-failure behavior. Outbound webhook endpoints on payload version 2026-10-26 or later send entitlement.updated events (see Outbound webhooks); applications still reconcile periodically and refresh after checkout/portal return. Keep test and live caches isolated. V2 effective reads do not expose legacy feature/limit or version/updatedAt snapshot fields.

Create a pinned customer portal session

Pass your project customer externalId. BillStack resolves the persisted provider customer account and immutable account incarnation, so a provider customer ID cannot be supplied by the caller.

const portal = await billing.portal.create({
  customerExternalId: user.id,
  returnUrl: "https://app.example.com/settings/billing",
});

return portal.data.portalUrl;

The response lists supportedActions. A portal request fails clearly when the pinned provider account is unavailable or the provider does not support a portal. It does not fall back to another provider.

In a team with several regions the portal opens the account of the customer's pinned region. A customer who has accounts with more than one provider but no pin yet (nobody has paid) gets 409 CUSTOMER_PROVIDER_ACCOUNT_AMBIGUOUS; pass provider or regionId to choose. A regionId that is not one of the team's regions is 404 REGION_NOT_FOUND.

Roll out canonical reads and routing

Rollout is an operator CLI operation, not an SDK call. Audit first with a bounded scope:

bun scripts/rollout-billing-providers.ts \
  --mode=audit \
  --team-id=team_123 \
  --project-id=project_123

The default audit is read-only. shadow, canary, pause, and resume require --apply and --confirm=BILLING_PROVIDER_MIGRATION_APPLY. Set independent --canonical-reads-enabled=true and --new-routing-enabled=true flags only after the report's quarantine, unresolved-entitlement, freshness, and reconciliation gates pass. A pause stops new checkout activation for the selected scope while webhook ingestion and reconciliation continue.

Provider capabilities and unsupported actions

Inspect the verified capabilities returned on a connection or binding and show only actions that are supported for that account.

The table lists what each provider supports. In a team with more than one region the capabilities of the customer's region apply: a Razorpay-region customer cannot use Stripe-only actions (409 FEATURE_UNAVAILABLE_IN_REGION).

ProviderSupported v2 operationsUnsupported operations
StripeCheckout (including trials, promotion codes and referral discounts), subscriptions, refunds, payouts, disputes, portal sessionsDirect provider entitlements; entitlements are derived from authenticated events
RazorpayCheckout and subscriptionsCheckout trials, promotion codes and referral discounts, refunds, payouts, disputes, portal sessions, direct provider entitlements
RevenueCatEntitlement synchronizationCheckout, subscriptions, refunds, payouts, disputes, portal sessions

An unsupported operation returns a provider capability error. BillStack does not advertise a disabled action, issue a provider mutation through a different provider, or treat an entitlement source as checkout capability.

Region and routing errors

CodeStatusMeaningWhat to do
PROVIDER_UNAVAILABLE409The region that serves this customer cannot take payments right now (disconnected or disabled connection, no keys for the environment, the default region is down, or the webhook/fulfillment readiness check is open).Fix the connection. BillStack never routes the customer to another provider.
NO_ELIGIBLE_PROVIDER409No routing rule or region applies (a single-region team without rules, or a default region that does not serve the environment).Create or activate the default region or a default rule.
PRICE_UNAVAILABLE_IN_REGION422The customer's region has no verified price link for this variant, or no regional alternate for the campaign step.Send a variant the region can sell (INR for Razorpay) or add the missing link. The country token is not spent.
REGION_PIN_MISMATCH409Retrying a failed checkout whose customer has since been pinned to another region.Start a new checkout.
CHECKOUT_EXPIRED409The checkout was closed because the customer paid in another region.Start a new checkout.
REGION_REQUIRES_V2409v1 checkout for a customer pinned to a non-default region.Use the v2 checkout.
ROUTING_RULES_FROZEN_MULTI_REGION409Creating or changing a hand-written routing rule in a team with more than one region.Use regions; delete the rule if you no longer need it.
FEATURE_UNAVAILABLE_IN_REGION409A Stripe-only feature for a customer in a Razorpay region.Not available for that customer.
COUNTRY_CONFLICT409A country already belongs to another region (the message names it).Remove it from the other region first.
REGION_COVERAGE_GAPS409Activating the region (or making it default) while price variants have no verified link.Link the variants, or read the report with regions.coverage().
LEGACY_PROVIDER_CONNECTION_REQUIRED409A payment provider of the team is still configured only through legacy project settings.Connect it as a provider connection first.
CONNECTION_ALREADY_EXISTS409The team already has a connection for this provider.Use a separate team for a second account of the same provider.
CAMPAIGN_REGION_ALTERNATE_MISSING409Activating a lifetime campaign that lacks a price for an active region.Add the regional prices.
CAMPAIGN_UNAVAILABLE409No lifetime offer is on sale for the tier.See Sell a lifetime campaign.
LIFETIME_ALREADY_OWNED409The customer already owns the lifetime offer.Nothing to buy.

Region management errors (REGION_NOT_FOUND, REGION_ALREADY_EXISTS, REGION_IN_USE, DEFAULT_REGION_UNAVAILABLE, DEFAULT_REGION_PROTECTED, DEFAULT_REGION_MODE_GAP, MODE_NOT_CONNECTED, INVALID_COUNTRY, and others) are listed in the API reference.

Upgrade notes

Country confirmations changed (SDK 0.6.0, breaking). A confirmation is now bound to the customer it was issued for and works for one checkout.

  • Pass customerExternalId to checkout.confirmCountry(). It is required, and a request without it is 400 COUNTRY_TOKEN_CUSTOMER_REQUIRED.
  • Send the same customerExternalId on checkout.create().
  • Request a new confirmation for every checkout attempt. A retry of the same checkout with the same idempotencyKey may reuse it; any other reuse is 409 COUNTRY_TOKEN_ALREADY_USED.
  • Confirmations minted before the server upgrade are refused with COUNTRY_TOKEN_INVALID; mint a new one. They live for at most an hour, so the cutover costs at most an hour of re-minting.
  • Test API keys can send an unsigned country instead (CheckoutInput.country); live keys cannot.
  • CheckoutInput.countryConfirmation is optional in the types (it is only omitted together with country on a test key).

New in 0.6.0. billing.regions (region management), campaignTier on checkout.create() and the customer.region_conflict webhook event. Existing single-provider teams need no change: they have one default region and behave as before. A team that never creates a second region is unaffected. Once a team has a second region, GET routing-rules also returns the read-only rules compiled from the regions (source: "region") and a missing price link answers 422 PRICE_UNAVAILABLE_IN_REGION.