---
name: configure-billstack-billing
description: "v2 (provider-neutral). Connect an existing Stripe account to BillStack v2, choose the right test or live key, distinguish legacy migration from new test setup, configure canonical plans and prices with verified provider links, archive retired products and prices, establish signed webhook fulfillment readiness, activate explicit project routing, and optionally add a second payment provider as a country region."
---

# Configure BillStack billing

**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 for authorized billing setup or configuration changes. Start with [integrate-billstack](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack/SKILL.md) for account/team/project/private-key setup and app integration. Load [sync-billstack-entitlements](https://billing.w3dev.app/.well-known/agent-skills/sync-billstack-entitlements/SKILL.md) for application workspace plan synchronization.

Base origin: `https://billing.w3dev.app`. Team prefix `T = /api/billstack/v2/teams/{teamId}`; project prefix `P = T/projects/{projectId}`. Replace placeholders and encode each path identifier. Setup requests (creating projects, products and prices, linking and publishing prices, archiving) use `Authorization: Bearer <setup-token>` with a personal access token (`bsu_test_` or `bsu_live_`, `BILLSTACK_SETUP_TOKEN`); runtime and read requests may use the project's `bs_` key. Requests use JSON; responses use `{ data, meta }`, or `{ error: { code, message }, meta }`. All paths below are suffixes of T or P, not literal URL aliases.

Keys and tokens stay in secrets. Catalog writes and project creation need a personal access token: a project key created since 2026-12-01 gets `403 USER_TOKEN_REQUIRED` on them (it can still read the catalog). A legacy full-access key (created earlier, not yet restricted) can still make them. Provider connection and binding writes need `billing:ManageProviders`, which the runtime policy denies, so they also need a token or a dashboard session. Use a test token or `bs_test_` key for test setup and a live one for live work (see Test and live keys below). V2 checks IAM actions and project ownership; scope strings on a key are ignored. Team connection operations need a team-wide token or key; one restricted to a project cannot manage team connections.

## Pricing setup at a glance

1. **Project:** `POST T/projects` with `{ "name": "My app", "slug": "my-app", "description": "..." }` (`project:CreateProject`, whole-team token or session; only `name` is required). Read `data.project.id`. Errors: `400 PROJECT_SLUG_RESERVED`, `409 PROJECT_SLUG_TAKEN`. The project's runtime key is created in the dashboard (project Settings > Keys), not by API.
2. **Provider:** connect and bind it (steps 1 and 2 below).
3. **Product and prices:** create one product per plan and one price variant per amount, currency and interval (step 3).
4. **Provider prices:** publish (Stripe) or link (Razorpay, or a price made elsewhere) each variant (step 3).
5. **Webhook readiness and routing** (steps 4 and 5), then a test purchase (step 6).
6. **Live:** promote the team in the dashboard (**Promote to live** in the environment switcher; there is no public v2 API for it), connect live keys, then bind, publish or link every variant again with `mode: "live"` and activate live routing. Catalog prices are published to each environment on their own: the dashboard's **Sync catalog to live** does not publish them for you.

There is no separate plan object. A variant's `tierAlias` is the plan its purchase grants, so the monthly and yearly variants of one plan carry the same alias.

**Trials** are not stored on a price. Send `trialDays` on the checkout (recurring prices, Stripe regions; see integrate-billstack).

**BillStack sandbox teams** (test environment without provider keys): BillStack provisions the connection, one binding per project and readiness itself, and checkout always goes to the sandbox. Skip steps 1, 2, 4 and 5 for test; create products and prices and publish them with `{ "mode": "test" }`. Live still needs a real provider and every step.

## Existing team Stripe integration and empty v2 lists

An existing team Stripe integration does **not** automatically provision v2. Legacy team credentials are in `team_stripe_config`, team dashboard data is in the Stripe mirror, and legacy project prices are in `project_prices`. V2 connections, bindings, products, price variants, routing, and entitlements use separate canonical `billing_*` tables. A legacy connected account and successful private-key authentication can coexist with empty v2 lists.

Read `GET T/provider-connections`, `GET P/provider-bindings`, `GET P/catalog/products`, `GET P/catalog/price-variants`, and `GET P/routing-rules`. Empty successful responses indicate missing configuration for that scope; they do not establish that Stripe is disconnected or that database migrations are missing. Missing canonical relations instead require an operator to inspect migration errors. Checkout/portal input validation and country-confirmation issuance do not test provider configuration or payment fulfillment.

Choose the supported path:

- **New test setup:** connect the same existing Stripe account using its authorized test API secret, create a test project binding, canonical catalog, verified test price links, signed readiness, and routing as below. A historical-data backfill is not required just to start new test checkouts. Obtain the intended prices, currency, billing cadence, and workspace plan names from the operator; the examples are illustrative.
- **Preserve existing billing history:** the BillStack operator runs scoped migration preflight, backfill, and verification from the repository. There is no public v2 endpoint that imports legacy credentials or migrates history. Do not change URL prefixes or label legacy live data as test data. Keep existing legacy ingress servicing its obligations during a reviewed migration.

One team has one logical connection per provider with separate test/live slots. If a Stripe connection already exists, use its ID and add the missing test slot through `/rotate`; a second `/provider-connections` creation fails with `CONNECTION_ALREADY_EXISTS`. Reusing the account does not make legacy webhook secrets, provider price IDs, or test/live objects interchangeable.

## Permissions and changes

Connection reads use `billing:GetProviders`; connection/binding writes use `billing:ManageProviders`; binding reads use `product:ListProducts`. Catalog product reads use `product:ListProducts` and price-variant reads use `price:ListPrices`. Creating a product needs `product:CreateProduct`, creating a price variant or publishing one to a provider needs `price:CreatePrice`, and adding a provider price link needs `price:UpdatePrice`. Updating a product's name, description or metadata needs `product:UpdateProduct`. Archiving a price variant needs `price:UpdatePrice`; archiving a product needs `product:UpdateProduct` and `price:UpdatePrice`. Routing reads use `product:ListProducts` and routing writes (create, validate, activate, deactivate, update, delete) use `billing:UpdateBilling`. These are IAM actions. The setup token carries your own permissions; a runtime key is denied every write in this paragraph except routing writes (`billing:UpdateBilling`).

## Test and live keys

Every team has a test environment; the live environment opens only after the team is promoted to live in the dashboard. A private key belongs to one environment: `bs_test_` keys act on test data and `bs_live_` keys on live data. Legacy `bs_` keys (hex directly after the prefix) are live keys. Publishable `pk_test_` / `pk_live_` keys are for public endpoints; use private keys for every call in this skill.

- On v2 routes that take a `mode`, omitting it means the key's environment. A `mode` naming the other environment fails with `403 ENVIRONMENT_MISMATCH`: a `bs_test_` key cannot name `live`, and a live key cannot name `test`. Send test traffic with a test key and live traffic with a live key. `POST T/provider-connections` and the connection `/verify` and `/rotate` calls require `mode` in the body, and the same rule applies to it.
- A live key for a team that has not been promoted is refused with `LIVE_ENVIRONMENT_NOT_ENABLED` (403). Use a `bs_test_` key until the operator promotes the team.
- An API key sees only its own environment: connection slots, bindings, routing rules and catalog `providerLinks` of the other environment are not returned to it (see `mode` in providerLinks below). A dashboard session sees both and may name either mode.
- Provider connections are shared by both environments (separate test and live slots). A test key cannot `disable` or `disconnect` a connection; use a live key or a dashboard session.
- Setup and test publishing: use a test token (`bsu_test_`; a legacy `bs_test_` key also works) for the connection test slot, test binding, canonical catalog, test publish or link, readiness and test routing. Live publishing: only when the operator asks, with a `bsu_live_` token (or a dashboard session or legacy `bs_live_` key) and `"mode": "live"`, after live credentials, a live binding and live readiness exist.

Before writes, identify team, project, provider, mode, and affected projects. Honor the user's existing authorization; do not infer permission for credential rotation or production routing changes from a request to inspect configuration. Start new setups in test mode. Read back changed resources. Do not log provider credentials or full request bodies containing secrets.

## 1. Connect the existing account in test mode

`POST T/provider-connections` creates and credential-verifies a new logical connection. Populate this body from the server secret store:

```json
{
  "provider": "stripe",
  "mode": "test",
  "displayName": "Stripe",
  "credentials": { "secret": "<stripe-test-api-secret>" }
}
```

Keep `data.connection.id`. Inspect `data.connection.slots` and select the active test slot; record `accountIdentity`, `accountIncarnationId`, and `canonicalWebhookUrl`. Compare the returned Stripe account identity with the intended existing account. Creation verifies credentials but does not register a Stripe webhook endpoint or establish delivery/fulfillment readiness.

`POST T/provider-connections/{connectionId}/verify` with `{ "mode": "test" }` rechecks an active slot. A pending imported incarnation without credentials must first receive credentials through `/rotate`; `/verify` cannot bootstrap it. Never rotate to an unconfirmed different account.

Stripe uses credentials.secret; Razorpay also needs credentials.publishableKey (or keyId) and secret plus credentials.metadata.razorpayAccountId (or expectedAccountId). RevenueCat needs secret and credentials.metadata.projectId. Provider validation/readiness is authoritative: a provider enum value is not a promise of checkout/portal support. RevenueCat is an entitlement source; its BillStack checkout and portal are unsupported. Razorpay portal is unsupported.

## 2. Bind the project to the verified test incarnation

`POST P/provider-bindings`:

```json
{ "connectionId": "<connection-id>", "mode": "test", "configuration": {} }
```

Read `data.binding.id`; verify via `POST P/provider-bindings/{bindingId}/verify` with `{ "mode": "test" }`, then inspect `GET P/provider-bindings`. The active binding's account incarnation must match the active test slot. Send `mode` explicitly: when omitted, a binding takes the calling key's environment (`test` for a `bs_test_` key, `live` for a live or legacy key; a dashboard session uses the environment it is viewing). A key naming the other mode gets `403 ENVIRONMENT_MISMATCH`, and a key cannot see or verify a binding of the other environment (`404 BINDING_NOT_FOUND`). Bindings reference team credentials; they do not import legacy catalog or copy provider credentials into the application.

## 3. Create canonical plans and publish them to the provider

`POST P/catalog/products` with `{ "name": "Pro", "description": "Pro plan" }` returns `data.product.id`. Then `POST P/catalog/price-variants`:

```json
{
  "productId": "<canonical-product-id>",
  "tierAlias": "pro",
  "amountMinor": 2000,
  "currency": "USD",
  "minorUnit": 2,
  "interval": "month",
  "intervalCount": 1
}
```

Read `data.priceVariant.id`. `tierAlias` is the server-owned plan label used for canonical entitlement `plan` and `tier`; without it, those fields use the immutable canonical price variant ID. A product name or Stripe metadata does not establish the application plan. Set an intentional alias for each variant and maintain the application's approved alias-to-feature/limit mapping.

Amount is a non-negative integer in currency minor units; USD 2000 means USD 20. Do not assume every currency has two decimal places; choose minorUnit correctly. Intervals: one_time, day, week, month, year. Recurring intervalCount is a positive integer. Canonical price variants are immutable; create a new variant for a new price rather than inventing a PATCH endpoint. Creating a variant does not create a provider price; publishing does.

**Consumable prices** (credit packs, top-ups, anything bought and used up): add `"billingScheme": "consumable"` to the `POST P/catalog/price-variants` body together with `"interval": "one_time"`. The default is `standard`; `lifetime` is described below. A consumable or lifetime variant with any other interval, or an unknown `billingScheme`, is `400 INVALID_REQUEST`. The scheme is fixed at creation and variants are immutable, so create a new variant instead of trying to convert one. Responses show `billingScheme` and `tierAlias`. Publishing and linking work as for any one-time price. A paid consumable records the purchase (`isEntitled: false`, `consumable: true` on its grant) but never changes `effective`; the application reads it with `GET P/checkouts/{checkoutId}` and credits its own ledger once per `checkoutId` (see integrate-billstack). Use a consumable only for units your application tracks itself; a plain one_time price is for access that should stay on.

**Lifetime prices** (pay once, keep the plan for good): add `"billingScheme": "lifetime"` together with `"interval": "one_time"` and a `tierAlias`. A paid purchase grants that plan as a lifetime grant. This is an ordinary Catalog price sold with `priceVariantId`. For a deal whose price steps up as units sell, build a lifetime deal on a one-time Catalog price (`standard` or `lifetime`, not consumable) with a `tierAlias`, through the v2 `lifetime-deals` routes: see [run-billstack-lifetime-deals](https://billing.w3dev.app/.well-known/agent-skills/run-billstack-lifetime-deals/SKILL.md).

**Publish (Stripe):** `POST P/catalog/price-variants/{priceVariantId}/publish` with `{ "mode": "test" }` creates the Stripe product (once per account) and price in the account of the project's active **test** binding, validates it and saves a verified link. It returns `201` with `data.providerLink` and `data.created: true`; publishing again returns the same link with `200` and `created: false`, so a retry is safe. `409 PROVIDER_BINDING_MISSING` means step 2 is not done for that mode; `409 CAPABILITY_UNSUPPORTED` means the provider (Razorpay, RevenueCat) needs an existing price linked instead; `503 PROVIDER_WRITE_UNKNOWN` means Stripe may have created the price, so publish again. Omitting `mode` publishes to the caller's environment; a key can only publish to its own, so a test key naming `live` gets `403 ENVIRONMENT_MISMATCH`. `provider` is needed only when the project binds more than one provider in that mode. `502 *_FAILED` means the provider refused the request. `409 PRICE_VARIANT_INACTIVE` or `PRODUCT_UNAVAILABLE` means the variant or product is archived. Publish to live only when the operator asks, with `{ "mode": "live" }` from a session or a live key. Publishing needs `price:CreatePrice`.

**Link an existing price instead** (Razorpay plans, or a Stripe Price made outside BillStack): create/select an active, matching price in the intended account's **test** environment. Then call `POST P/catalog/price-variants/{priceVariantId}/links`:

```json
{
  "provider": "stripe",
  "connectionId": "<connection-id>",
  "mode": "test",
  "externalProductId": "<stripe-test-product-id>",
  "externalPriceId": "<stripe-test-price-id>"
}
```

For Stripe manual linking, `externalProductId` is required and must identify the independently selected expected Product in the intended account/mode. Missing or blank IDs return `400 EXPECTED_PRODUCT_REQUIRED`; do not infer the expectation from the Price itself. Razorpay and other providers keep the parent optional. The server retrieves the provider object with that incarnation's credentials and validates amount, currency, billing type, interval/count, and product identity before saving the link. Inspect `data.providerLink.status === "verified"`. A key can only link prices of its own environment (`mode` must match). `GET P/catalog/price-variants` includes providerLinks; confirm the link's accountIncarnationId matches the test slot. Each providerLinks entry carries `mode` (`test` or `live`), the environment of the provider account it belongs to. An API key sees only links of its own environment (a `bs_test_` key never sees live links); a dashboard session sees both. Unverified/quarantined links cannot route checkout. Catalog objects are project-scoped; their provider links carry account and mode identity. Copying a Stripe Price ID into checkout as priceVariantId is invalid.

## 4. Establish signed webhook readiness before routing activation

Resolve the test slot's returned canonicalWebhookUrl against `https://billing.w3dev.app`. Its shape is `T/provider-connections/{connectionId}/webhooks/test/{incarnationId}`. Register that exact destination in the intended Stripe account's test environment. Stripe signs this ingress; it does not use the BillStack Bearer key. The legacy team's webhook URL and its signing secret do not establish readiness for this canonical endpoint.

For a new endpoint, create the connection without webhookSecret first, register the returned URL with Stripe, then store the actual endpoint signing secret through `POST T/provider-connections/{connectionId}/rotate`:

```json
{
  "mode": "test",
  "credentials": {
    "secret": "<same-stripe-test-api-secret>",
    "webhookSecret": "<actual-endpoint-signing-secret>"
  }
}
```

Rotation replaces the credential payload, so supply the API secret as well as the webhook secret. Read back the slot and URL; same-account rotation preserves the immutable incarnation, while a different account creates a new one. Do this credential setup before the readiness probe. Subsequent rotation or verification may require readiness to be demonstrated again; always read back current readiness.

Subscribe the endpoint to the billing events your app uses: checkout.session.completed, payment_intent.succeeded, charge.succeeded, customer.subscription.created/updated/deleted, invoice.paid/payment_failed, and refund.created/updated or charge.refunded for refunds. Also enable customer.created for the non-payment bootstrap probe below. BillStack's canonical normalizer handles these event families; an invoice event alone does not update subscription entitlement status.

The BillStack deployment operator must verify canonical migrations and a registered, running Inngest function `billstack-process-provider-events`. This worker sweeps the durable inbox every five minutes; canonical capture is always on and needs no configuration. Do not bypass readiness with direct database writes or caller metadata.

Before the first routed checkout, create a disposable **test** Customer in the actual Stripe account so Stripe delivers a real signed customer.created event to this endpoint. This establishes account delivery/worker readiness without a payment. Do not fabricate checkout metadata, forward unsigned JSON, or use a local CLI signing secret for a remotely registered endpoint. Provider fixture delivery can test signatures, but a real account event is needed for account delivery evidence.

Verify the ingress response is 200 with `status: "accepted"` or `"duplicate"`, then verify that inbox event is `processed` through the operator's canonical event/worker diagnostics. A 202 quarantined response, 503 capture unavailable, or retrying inbox row is not fulfillment evidence. Refetch `GET T/provider-connections`; the test slot's readiness must show `webhookDeliveryReady: true`, `fulfillmentReady: true`, and `source: "authenticated_webhook"`. Delivery is recorded at authenticated capture; fulfillment is recorded by the worker after projection. The public readiness view can stay null until both steps complete. This probe proves the pipeline, not a purchased plan grant.

## 5. Validate and activate explicit test routing

`POST P/routing-rules`:

```json
{
  "name": "USD Pro test",
  "priority": 10,
  "isDefault": true,
  "connectionId": "<connection-id>",
  "mode": "test",
  "conditions": { "currency": ["USD"], "priceVariantId": "<canonical-price-variant-id>" },
  "activate": false
}
```

Keep `data.rule.id`. Call `POST P/routing-rules/{ruleId}/validate`, inspect health/validationErrors, then `POST P/routing-rules/{ruleId}/activate` only for an intended valid rule. The action routes take no required JSON body. Inspect `GET P/routing-rules` afterward for the active test rule. Conditions may include country, currency, productId, priceVariantId, capability. Use a customer-confirmed country condition only if intentionally restricting this rule. A default still respects its conditions and requested mode; it is not a catch-all for unrelated prices.

Activation requires the active matching binding, verified price link, provider capabilities, and the exact account incarnation's signed delivery/fulfillment readiness. v2 does not seed routing or silently fall back to another provider. Persisted legacy/canonical financial-read rollout controls are separate from explicit public v2 rule activation; do not blanket-enable financial resources to clear a routing error.

### Optional: a second payment provider with regions

Skip this unless the team must sell through Stripe and Razorpay at once (for example Stripe for the world, Razorpay for India). Hand-written routing rules above apply only while the team has one region; with more than one, country is the only routing input and hand-written rules are frozen (`409 ROUTING_RULES_FROZEN_MULTI_REGION` on create, update and activate).

A team has one account per payment provider (`409 CONNECTION_ALREADY_EXISTS` for a second account of a provider; use a separate team). The first payment provider connected is the **default region**, which serves every country no other region claims. Regions are team-wide, so their routes are `T/regions` (T is `/api/billstack/v2/teams/{teamId}`), not project routes. Reads use `billing:GetProviders`, writes `billing:ManageProviders`, and a test API key can only read, `activate`, `deactivate` and read `coverage` for its own environment (`403 ENVIRONMENT_MISMATCH` on create, update, delete and make-default; use a live key or a dashboard session).

1. Connect the second provider like the first (step 1; Razorpay needs `credentials.publishableKey`, `secret` and `credentials.metadata.razorpayAccountId`). Connecting it does not change where customers pay.
2. `POST T/regions` with `{ "name": "India", "connectionId": "<razorpay-connection-id>", "countries": ["IN"] }` creates a draft region (201 `{ region, warnings }`). Countries are ISO 3166-1 alpha-2 (`GB`, not `UK`); a country can belong to one region (`409 COUNTRY_CONFLICT`). The default region owns no list.
3. Bind the project to the connection and give every variant the region should sell a verified price link on that connection (step 3). A Razorpay region sells INR only; other currencies stay with the default region.
4. `GET T/regions/{regionId}/coverage?mode=test` returns `variants.gaps` (variants without a verified link; they block activation), `notOffered`, `handWrittenRules` that will stop applying and `lifetimeCampaigns` that would be paused. Fix gaps, then `POST T/regions/{regionId}/activate` with `{ "mode": "test" }`. Activation can fail with `MODE_NOT_CONNECTED`, `DEFAULT_REGION_UNAVAILABLE` or `REGION_COVERAGE_GAPS`. A region is `draft`, `active` or `unavailable` per environment (`availability` in the region object); an unavailable region fails checkout with `PROVIDER_UNAVAILABLE` and never falls back to the default region.
5. Register each connection's own `canonicalWebhookUrl` with its provider and establish signed readiness for both (step 4).
6. Test a customer in each region with the integration skill's checkout flow: with a `bs_test_` key send an unsigned `country`, with a live key a customer-bound single-use confirmation. The first confirmed payment pins the customer to the region paid in; moving country afterwards never re-routes them. Do the same for live only on the operator's explicit instruction.

Other calls: `PATCH T/regions/{regionId}` (`{ name?, countries? }`; `countries` replaces the list), `POST .../deactivate` (`{ mode }`; its countries go to the default region, warning `COUNTRIES_REROUTE_TO_DEFAULT`), `POST .../make-default` (dashboard session only, so an API key gets `403 UNAUTHORIZED`: ask the user to do it in the dashboard; pinned customers do not move), `DELETE T/regions/{regionId}` (`409 REGION_IN_USE` while pinned customers, subscriptions, checkouts or accounts reference it). A team that still holds Stripe or Razorpay credentials only in legacy project settings must first connect them as provider connections (`409 LEGACY_PROVIDER_CONNECTION_REQUIRED`). Lifetime campaigns in a multi-region team need a regional price for every active region (see legacy-billstack-lifetime-deals).

Merchant entities and revenue by currency (read these after regions exist):

- `GET T/entities`, `GET T/entities/{entityId}` (`billing:GetProviders`) and `PATCH T/entities/{entityId}` (`billing:ManageProviders`; `{ legalName?, country?, defaultCurrency? }`, ISO 3166-1 alpha-2 and ISO 4217; a test key gets `403 ENVIRONMENT_MISMATCH`). Every team has one default entity, named after the team until changed, and each new connection attaches to it. `country` and `defaultCurrency` fill from the first account that reports them (Stripe only) and are never overwritten. Regions and connections expose `entityId`; slots expose `accountCountry` and `accountCurrency`. Ask the operator for the real legal name before telling anyone who bills their customers. Errors: `ENTITY_NOT_FOUND` (404), `INVALID_ENTITY_NAME`, `INVALID_ENTITY_COUNTRY`, `INVALID_ENTITY_CURRENCY` (400).
- `GET T/financials/currency-report?mode=&projectId=&from=&to=` (`billing:GetBilling`) returns payments, fees, net and refunds per provider account grouped by currency, with no conversion. It answers `200 { enabled: false }` unless two or more regions are active in the mode; never add its currencies together.
- Outbound webhook endpoints carry an `apiVersion` (`2026-10-19` original, `2026-10-22` adds `region`, `2026-10-26` adds the entitlement, subscription and purchase events). Existing endpoints stay on their version and never receive event types introduced later, not even through `*`; `PATCH` the `apiVersion` to opt in. New endpoints default to the latest.
- Canonical provider-event capture needs no configuration. Routed checkout becomes ready after the provider delivers one signed event to the connection's `canonicalWebhookUrl` (step 4).

## 6. Verify purchase fulfillment and application synchronization

Use the integration skill's country-confirmation and checkout flow with this exact test variant/mode and the application's stable billing subject. Complete an authorized Stripe test payment. Verify its signed events reach the canonical endpoint, worker processing commits, and `GET P/entitlements/{externalId}?mode=test` returns the intended `effective.plan`, `effective.isEntitled`, period, and resolved grants. Then verify the application reconciles that entitlement into the correct workspace and the supported Stripe portal works.

Record sanitized BillStack request IDs, provider event IDs, mode, and account incarnation in private operational evidence. An HTTP 200 configuration read, credential verification, or successful country confirmation does not prove payments work. A readiness customer probe is not purchase fulfillment. Do not report setup or payment success until the corresponding checks pass.

## 7. Archive retired products and prices

Price variants are immutable: an amount, currency or interval cannot be changed. To change an amount, create a new variant (and publish or link it), switch routing and the application to it, then archive the old variant. Archiving is the only change a price variant takes, and it is one-way: there is no unarchive, so create a new product or variant to sell again. A product's `name`, `description` and `metadata` can still be edited (below) while it is active.

- `PATCH P/catalog/products/{productId}` needs `product:UpdateProduct`. Body: `{ name?, description?, metadata? }` with at least one field; `description` and `metadata` accept `null` to clear. Any other field (`isActive`, `priceVariants`) returns `400 INVALID_REQUEST`, and an archived product returns `409 PRODUCT_UNAVAILABLE`. BillStack updates the canonical product first, then pushes the new name and description to each verified Stripe product the key can see, so a `bs_test_` key updates test-mode Stripe products only and a dashboard session updates both; metadata stays in BillStack and is never sent to Stripe. The `200` response is `data.product` (each product link has `syncState`: `in_sync`, `out_of_sync`, or `unknown` for links that predate the first update) plus `data.sync`: `status` is `complete`, `partial` or `none` (no eligible provider product), and `results` has one entry per provider product with `outcome` `synced`, `failed` or `skipped` and a `code` (for example `PROVIDER_PRODUCT_MISSING`, `PROVIDER_WRITE_UNKNOWN`, `ACCOUNT_INACTIVE`, `CAPABILITY_UNSUPPORTED`). A `partial` result is still `200` and the canonical product has already changed: repeat the same PATCH to retry the failed links, then read `syncState` back. Report any `failed` result to the operator rather than assuming Stripe matches.
- `POST P/catalog/price-variants/{priceVariantId}/archive` needs `price:UpdatePrice` and returns `data.priceVariant` with `status: "archived"` (providerLinks included, filtered to the caller's environment).
- `POST P/catalog/products/{productId}/archive` needs `product:UpdateProduct` and `price:UpdatePrice`. It archives the product and all its price variants and returns `data.product` with `status: "archived"`.
- Neither takes a body. An id outside the project returns `404 PRODUCT_NOT_FOUND` or `404 PRICE_VARIANT_NOT_FOUND`.
- Archiving does not delete the provider price or product in Stripe; it stops BillStack from selling the variant. Checkout refuses an archived variant (the routing step reports it as `CANONICAL_PRICE_UNAVAILABLE`; do not rely on a different code), existing subscriptions are not changed, publishing an archived variant fails with `409 PRICE_VARIANT_INACTIVE`, creating a variant under an archived product fails with `PRODUCT_UNAVAILABLE`, and routing validation reports a rule that references an archived variant. Archive only after the operator confirms nothing should sell it, and read the catalog back afterwards.

## 8. Operators in the dashboard

An operator can do the catalog steps without the API in **Project -> Catalog** (`/v2/{team}/{project}/catalog`, or `/v2/{team}/test/{project}/catalog` for the test environment): create products and prices, publish a price to test or live, link an existing provider price, and archive products or prices. Live publishing always needs an explicit confirmation there. The page calls the same v2 catalog routes, so both show the same catalog. Connections, signed readiness and routing remain as described in this skill.

## Operator migration of existing history

For historical data, an operator with the repository and authorized database access runs these read-only commands first, with the explicitly verified Stripe account ID and actual source mode:

```bash
bun run scripts/preflight-billing-provider-migration.ts \
  --team-id=<team-id> --provider=stripe \
  --provider-account-id=<verified-stripe-account-id> --provider-mode=<test-or-live>
bun run scripts/backfill-billing-provider-data.ts \
  --team-id=<team-id> --provider=stripe \
  --provider-account-id=<verified-stripe-account-id> --provider-mode=<test-or-live>
```

The second command defaults to dry-run. Team scope can affect multiple projects; use project scope only after inspecting source attribution and the migration report. Obtain authorization for the reviewed scope before applying with `--apply --confirm=BILLING_PROVIDER_MIGRATION_APPLY`. Database credentials belong in operator secrets, never this catalog. Do not assume encrypted legacy credentials identify an account or that rows lacking mode evidence belong in test.

Backfill preserves explicit account mapping but leaves new connections pending, incarnations unverified, bindings pending, and imported price links unverified. It does not copy usable credentials, register a webhook, or activate routing. Provision credentials using `/rotate`, then verify the binding and provider price links and establish readiness through the steps above. Run `scripts/verify-billing-provider-data.ts` with the same account/team/provider/mode flags; resolve all quarantine, entitlement-provenance, and reconciliation failures. Team mirror charges cannot prove project-scoped financial parity. `scripts/rollout-billing-providers.ts --mode=audit` is a separate operator readiness report; canonical financial reads require resource-specific verification before an authorized rollout.

## Maintenance and failures

- `/rotate`: read returned test/live slots and canonical URLs; review dependent bindings, links, rules, and readiness after rotation. Same-account identity and readiness are distinct checks.
- `POST T/provider-connections/{connectionId}/disable` or `/disconnect`: inspect affectedProjectCount and dependent projects first.
- `POST P/provider-bindings/{bindingId}/disconnect`: accepts optional mode; inspect affected routing first.
- `POST P/routing-rules/{ruleId}/deactivate` and `DELETE P/routing-rules/{ruleId}`: read remaining rules afterward.

Do not retry generic configuration POSTs blindly after a timeout; list/read first to determine whether creation succeeded. Return error.code and meta.requestId without secrets. A 403 needs permission/key correction. RULE_ACTIVATION_INVALID needs its fieldErrors/readiness resolved. Live rollout requires separately verified live credentials, bindings, prices, links, signed readiness, routing, and application mode; changing a single example's mode is insufficient.
