---
name: legacy-billstack-integration
description: "Legacy (v1, Stripe-first) BillStack API only. Maintain an application that already calls /api/billstack/teams/{teamId}/projects/{projectId}/...: find-or-create customers, checkout/start, entitlements by-external-id, BillStack-hosted portal sessions, legacy subscription cancellation, BillingQL, Stripe-mirror MCP tools and the BillStackClient SDK. Maintenance only; do not use for new integrations, load integrate-billstack (v2) instead."
---

# Legacy BillStack integration (v1)

This skill covers the **legacy (v1, Stripe-first)** generation only: routes under `/api/billstack/teams/{teamId}/projects/{projectId}/...` (no `/v2`) and the `BillStackClient` SDK client. Legacy is maintenance-only: use it to keep an application working that already calls these routes. For every new integration load [integrate-billstack](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack/SKILL.md) (v2) instead, and never mix the two generations in one flow.

Decide the generation from the application's own code: a call to `/api/billstack/teams/.../projects/...` or an import of `BillStackClient` means legacy, so use this skill; a call to `/api/billstack/v2/...` or `BillStackV2Client` means v2, so use the v2 skills.

## Credentials, environment and envelope

Use `https://billing.w3dev.app` with a server-side private Bearer key (`bs_test_` or `bs_live_`) and JSON bodies; keep the key in an environment variable or secret store. The key's prefix selects the environment: a `bs_test_` key reads and writes test data only, and a `bs_live_` key works only after the team is promoted to live (`403 LIVE_ENVIRONMENT_NOT_ENABLED` before). A legacy `bs_<hex>` key has no environment in its prefix and runs in the environment stored for it. Legacy routes take no `mode` parameter. Responses are not wrapped in `data`/`meta`; errors are usually `{ "error": string }`, with `code` added for `LIVE_ENVIRONMENT_NOT_ENABLED`. Legacy mutation routes use an admin-or-private-key access helper rather than v2 fine-grained IAM, so treat their credentials as privileged. Legacy and v2 identifiers, envelopes and data are separate; do not migrate a live project merely by changing URL prefixes.

Identify the team, project, key environment and authenticated app customer before acting. `externalId` is your app's stable customer identifier, not a provider customer ID; URL-encode it in paths.

## Checkout and entitlements (legacy routes)

Prefix `L = /api/billstack/teams/{teamId}/projects/{projectId}` without `/v2`:

- `POST /checkout/start`: `{ externalId, email or phone, name?, tier, cycle, successUrl, cancelUrl, provider?, referralCode? }`. Read `checkoutUrl` from its legacy response, not `data.url`.
- `GET /entitlements/by-external-id/{externalId}`: inspect top-level `isEntitled`.
- Legacy routes also run in the key's environment (a `bs_test_` key reads and writes test data only), but they take no `mode` parameter and return `{ error, code }` for `LIVE_ENVIRONMENT_NOT_ENABLED`.
- Legacy checkout always uses the team's default region provider (Stripe or Razorpay). It never takes a country, the phone number never selects a provider and there is no fallback to another provider; a `provider` in the request must match the default region's provider, otherwise checkout fails. A customer already pinned to a non-default region gets `409 REGION_REQUIRES_V2`: use the v2 checkout for them.

Existing team Stripe configuration does not automatically create v2 connections, bindings, canonical catalog, or routing. Empty authenticated configuration lists can coexist with an active legacy Stripe integration. Use the configuration skill for a new test setup on the same account or an operator-reviewed historical migration. Keep legacy and v2 identifiers, envelopes, and data separate. Do not migrate a live project merely by changing URL prefixes.


## Customers

Only use this on an existing legacy Stripe-first project.

`POST L/customers/find-or-create` accepts:

```json
{ "externalId": "<app-customer-id>", "email": "customer@example.com", "name": "Example customer" }
```

Returns `{ customer, created }`. It looks up externalId, then email within the project, and may link that email record to externalId. Confirm identity ownership before using email matching. Do not treat the lookup sequence as a guarantee of exactly-once behavior under concurrent requests. It creates a Stripe customer when none exists, in the Stripe account of the key's environment (a test key uses the team's test-mode Stripe keys); it is not a v2 provider-neutral provisioning endpoint.


## Customer portal: BillStack-hosted (Stripe and Razorpay)

`POST /api/billstack/teams/{teamId}/projects/{projectId}/portal/by-external-id` with `{ "externalId": "<authenticated-app-customer-id>", "ttlMs"?: number }` returns `201 { sessionId, token, portalUrl, expiresAt, url }` (`url` is a deprecated alias of `portalUrl`; default lifetime 24 hours, maximum 7 days; `404` when no customer has that externalId). Return `portalUrl` only to that customer. `POST .../portal` with `{ customerId }` is the same with BillStack's internal customer id. The SDK `portal.create()` (0.4.1+) returns `{ sessionId, token, portalUrl, expiresAt }`.

The hosted page serves each provider the customer has an account with, with a Stripe | Razorpay switch when both exist:

- **Stripe:** subscriptions (cancel at period end, resume), invoices, payment methods.
- **Razorpay:** subscriptions (list, cancel at the end of the current cycle) and invoices (link to the Razorpay hosted invoice). No resume and no payment-method management. Only subscriptions BillStack has recorded for the customer are listed. A subscription id that does not belong to the session's customer answers `404`; a Razorpay outage answers `502 PROVIDER_UNAVAILABLE`.
- Externally billed projects (referrals only): mutations are blocked; listing still works.

Human guide: https://docs.billing.w3dev.app/integration/legacy-customer-portal


## Subscription cancellation

Prefer the v2 subscription routes (see manage-billstack-customers) for new work. These legacy routes remain for existing legacy Stripe-first projects. Only perform a requested change after identifying the customer's actual legacy project subscription and the intended timing. Use its BillStack subscription ID, not a v2 financial-row ID. Read `GET L/subscriptions/{subscriptionId}` before and after changes.

- `PATCH L/subscriptions/{subscriptionId}` with `{ "cancelAtPeriodEnd": true }` schedules cancellation.
- The same PATCH with false removes a scheduled cancellation; it does not resurrect a fully canceled subscription.
- `DELETE L/subscriptions/{subscriptionId}` cancels immediately in Stripe and updates BillStack. This is financially consequential; require explicit intent for immediate cancellation. Do not infer refund authorization.

Mutation response is `{ subscription }`. The legacy route uses an admin-or-private-key helper; do not claim v2 fine-grained IAM authorization applies to it. After changes, inspect the subscription and the generation-appropriate entitlement. Do not promise an automatic refund or immediate entitlement convergence. If the provider write or mirror update fails, reconcile the actual subscription before retrying rather than assuming rollback.


## BillingQL and Stripe-mirror reads

Use `POST /api/billstack/teams/{teamId}/query`, or add `/projects/{projectId}/query` for project data. Required IAM action: `query:Execute` plus read permissions for every referenced dataset. JSON body:

```json
{
  "query": "SELECT invoices.invoice_id, invoices.amount, invoices.currency, invoices.status FROM invoices WHERE invoices.status = :status LIMIT 50",
  "parameters": { "status": "paid" },
  "mode": "validate"
}
```

Validate, then explain when useful, then execute the same parameterized query by changing mode. Valid modes: validate, explain, execute (execute when omitted). Use explicit fields; at most 500 rows. Datasets: customers, subscriptions, invoices, products, prices, payments. Payments are team-only. BillingQL is not a SQL mutation API and does not expose arbitrary tables.

Team queries read the key's environment's Stripe mirror; if that mirror has not been synced yet the call returns `409 QUERY_MIRROR_NOT_SYNCED` (connect keys for that mode or run its backfill). A 403 with an `action` field names a dataset permission the caller lacks. Inspect columns, rows, rowCount, truncated, and warnings in the query result. Invoice dates are ISO-8601 strings; amounts are integer minor units. Truncated results are not a complete population. Use bounded date filters and explicit grouping supported by the language instead of extrapolating totals from the first rows. Mirror sync/backfill may be incomplete.


The billing MCP tools `query_billing_data`, `list_customers`, `list_subscriptions`, `list_invoices`, `list_disputes`, `list_payouts`, `list_balances`, `list_transactions`, `list_products`, `get_saas_metrics`, `get_arpa_by_tier` and `get_churn_breakdown` read the Stripe mirror; their descriptions start with `Legacy:`. They do not automatically represent canonical v2 providers. For v2 reads load [inspect-billstack-billing](https://billing.w3dev.app/.well-known/agent-skills/inspect-billstack-billing/SKILL.md).

## SDK

`BillStackClient` from `@billstack/sdk` wraps these routes (`@billstack/sdk/legacy` also exports it from 0.7.0). It has no wrapper for `checkout/start` or `portal/by-external-id`; call those with `fetch`. `@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.

## Errors and verification

Private route authorization failures commonly return 403. Legacy errors often have a string `error` field; preserve the actual response shape and do not blindly retry non-idempotent operations after a network error. Report the sanitized customer identifier, target project, environment, requested operation and read-back result. Verify with a `bs_test_` key and a test customer before making a live change.

## Moving to v2

Existing team Stripe configuration does not create v2 connections, bindings, canonical catalog or routing by itself. To move an integration, load [configure-billstack-billing](https://billing.w3dev.app/.well-known/agent-skills/configure-billstack-billing/SKILL.md) for a new v2 test setup, then replace calls one flow at a time with the v2 equivalents in [integrate-billstack](https://billing.w3dev.app/.well-known/agent-skills/integrate-billstack/SKILL.md).
