Billing and subscriptions
The billing module manages plans, prices, subscriptions and access to paid features. It is decoupled from the external provider — the system works the same with Stripe as with any other payment processor.
When the external provider fails on subscriptions, checkout, portal or price synchronization, the API does not propagate Stripe's raw error: it answers 502 with the code BILLING_PROVIDER_FAILURE and a fixed message, logs the failure and allows a retry.
The provider layer (BillingProvider) also exposes a single charge, a refund and a status query without coupling to Stripe. If there is no usable provider (BILLING_PROVIDER=noop or no credentials), those charge operations are rejected with an actionable error and never fake a success. Platform provider + Nimobase→tenant charges (listing): a super admin reads the status (GET /billing/platform/provider), connects or disconnects the provider (POST /billing/platform/provider/connect|disconnect), lists the global history (GET /billing/platform/charges) and can issue charges, subscriptions and refunds to tenants under /billing/platform/tenants/:companyId/.... Provider failures are never marked as success. Anyone who is not a super admin receives 403 on the provider status GET, connect/disconnect, the listing and refunds.
Platform → tenant charges — provider and history
The listing reuses billing_payments with metadata.side = platform_to_tenant. By default it includes every company; companyId is an optional filter. The platform provider's status and connection are super admin only (assertSuperAdmin).
| Method | Route | Role | Description |
|---|---|---|---|
GET | /billing/platform/provider | Platform super admin | Connection status (connected, providerName, providerUsable, usableForCharges). OWNER/ADMIN → 403 |
POST | /billing/platform/provider/connect | Platform super admin | Connects the provider for Nimobase→tenant charges. OWNER/ADMIN → 403 |
POST | /billing/platform/provider/disconnect | Platform super admin | Disconnects the provider — blocks new Nimobase→tenant charges and refunds. OWNER/ADMIN → 403 |
GET | /billing/platform/charges | Platform super admin | Global history; query companyId?, search, status, dateFrom, dateTo. Response { data } with company identity (companyName, companyEmail), refundedAmount / refundableAmount |
POST | /billing/platform/tenants/:companyId/charges/:chargeId/refund | Platform super admin | Full or partial refund (amount in minor units optional, reason optional). Invalid amount → 400 PLATFORM_BILLING_INVALID_REFUND_AMOUNT |
Tenant charge BYOK
OWNER/ADMIN can register, activate, deactivate and delete their company's charge BYOK credentials. The credentials live in the provider vault (family billing / type stripe); this API does not redefine the vault.
| Method | Route | Role | Description |
|---|---|---|---|
GET | /billing/byok/status | OWNER, ADMIN | Secret-free status: absent / usable / error |
GET | /billing/byok | OWNER, ADMIN | List charge BYOK credentials (no secrets) |
GET | /billing/byok/:id | OWNER, ADMIN | Get one set (no secrets) |
POST | /billing/byok | OWNER, ADMIN | Register (active by default); secrets can be revealed once |
PATCH | /billing/byok/:id | OWNER, ADMIN | Update / rotate (omitting the secret keeps the previous one) |
DELETE | /billing/byok/:id | OWNER, ADMIN | Delete — 204 |
POST | /billing/byok/:id/activate | OWNER, ADMIN | Activate (the only active one of its type) |
DELETE | /billing/byok/:id/activate | OWNER, ADMIN | Deactivate (no longer usable for new charges) |
MEMBER/VIEWER receive 403.
Connect
OWNER/ADMIN can start the tenant's charge account onboarding, read the status (not_connected / pending / connected / error, no secrets) and disconnect. After a successful onboarding Connect is connected/usable; after disconnecting it is no longer usable for new charges.
| Method | Route | Role | Description |
|---|---|---|---|
GET | /billing/connect/status | Authenticated | Connect status without secrets |
POST | /billing/connect/onboarding | OWNER, ADMIN | Starts onboarding (returnUrl, refreshUrl) |
DELETE | /billing/connect | OWNER, ADMIN | Disconnects — not usable for new charges |
Active mechanism
OWNER/ADMIN can query which mechanisms (BYOK / Connect) are usable and which one is active for new company→end-customer charges, and can mark exactly one as active. Resolution:
- Only one usable → it is treated as active.
- Both usable and one marked → the marked one is used.
- Both usable and none marked → actionable rejection
BILLING_CHARGE_MECHANISM_MUST_CHOOSE. - None usable → actionable rejection
BILLING_CHARGE_MECHANISM_NONE_USABLE.
| Method | Route | Role | Description |
|---|---|---|---|
GET | /billing/charge-mechanism | OWNER, ADMIN | Usables + active (no secrets) |
PUT | /billing/charge-mechanism/active | OWNER, ADMIN | Marks byok or connect as active |
Company→end-customer charges (listing) live under /billing/customer-charges (OWNER/ADMIN).
Company → end-customer charges
OWNER/ADMIN charge end customers with the usable active mechanism (BYOK or Connect), through the same BillingProvider layer. Platform commission is configurable in bps (settings.platform_billing_commission_bps, default 0); the charge result includes commissionAmount (minor units). The listing reuses the same billing_payments records (the tenant_to_customer side).
idempotencyKey (optional) in the single-charge body: if the same key is repeated in the same tenant, the API reuses the existing local row (same id / externalPaymentId) instead of inserting a second charge.
| Method | Route | Role | Description |
|---|---|---|---|
GET | /billing/customer-charges | OWNER, ADMIN | History of the active company; query search, status, dateFrom, dateTo. Response { data } with refundedAmount / refundableAmount |
POST | /billing/customer-charges | OWNER, ADMIN | Single charge (amount, currency, customerEmail, optional idempotencyKey, …); the response includes commissionAmount. Same idempotencyKey → same local row |
GET | /billing/customer-charges/:chargeId | OWNER, ADMIN | Read; another tenant or nonexistent → 404; includes commissionAmount / refundableAmount |
POST | /billing/customer-charges/:chargeId/refund | OWNER, ADMIN | Full or partial refund (amount in minor units optional, reason optional). Invalid amount → 400 BILLING_CUSTOMER_CHARGE_INVALID_REFUND_AMOUNT. Mechanism not operable → 400 |
POST | /billing/customer-charges/subscriptions | OWNER, ADMIN | Create an end-customer subscription (externalPriceId, customerEmail) |
PATCH | /billing/customer-charges/subscriptions/:externalSubscriptionId | OWNER, ADMIN | Update the subscription |
POST | /billing/customer-charges/subscriptions/:externalSubscriptionId/cancel | OWNER, ADMIN | Cancel the subscription |
MEMBER/VIEWER → 403. Normalized states: pending, succeeded, failed, canceled, refunded, partially_refunded.
Key concepts
| Concept | What it is |
|---|---|
| Plan | Defines which features a subscription includes and their limits (e.g. max users) |
| Price | A plan's rate: amount, currency and billing interval (monthly, yearly, etc.) |
| Billing customer | The tenant's representation in the payment system. One record per company |
| Subscription | The active contract between the tenant and a specific price |
| Entitlement | The actual access a tenant has to a feature, derived from its plan |
| Invoice | A record of a charge generated by the subscription |
Entitlements are the stable interface for the rest of the platform. Other modules ask "does this tenant have access to X?" without knowing anything about subscriptions or providers.
Subscription lifecycle
trialing → active → past_due → canceled
↘ ↗
paused
↘
expired- trialing — trial period active
- active — subscription in force, entitlements active
- past_due — failed payment, still in the grace period
- paused — subscription paused
- canceled — cancelled; entitlements revoked
- expired — definitively ended
State changes arrive through provider webhooks and are processed asynchronously so the HTTP response is not blocked.
Plans and prices
Listing available plans
GET /billing/plans
Authorization: Bearer <token>Returns the active plans with their prices. Requires no specific role. A deactivated plan (isActive: false) disappears from this listing — it stops being offered to new checkouts/subscriptions (see "Deactivating a plan" below). GET /billing/plans/:id still returns an inactive plan when its UUID is known.
Admin listing (includes inactive) — ?includeInactive=true
GET /billing/plans?includeInactive=true
Authorization: Bearer <super-admin-token>A variant for the platform super admin only (isSuperAdmin: true) that also includes deactivated plans — 403 for any other caller. Without the parameter (or with includeInactive=false) the public behaviour above is unchanged. It exists so that a plan deactivated from the Super Admin dashboard stays visible, editable and reactivatable right there instead of disappearing forever from the admin's own listing.
Public plans for the landing — GET /billing/plans/public
GET /billing/plans/publicA public route with no authentication — intended for the frontend's commercial landing (/), which needs to show real plans before the visitor signs up. It returns only plans that are active AND marked as visible on the landing (isVisibleOnLanding: true, see below). An inactive plan never appears here even when it is marked visible.
The response uses a strict field whitelist — never the raw entity object — so nothing internal leaks:
[
{
"name": "Pro",
"description": "Plan for teams",
"prices": [{ "amount": 2900, "currency": "usd", "interval": "monthly" }],
"features": ["api_access", "priority_support"]
}
]Fields never exposed: id, isActive, isVisibleOnLanding, limits, metadata, nor the payment provider id (externalPriceId, e.g. the Stripe price id). Only active prices (isActive: true) of each plan are included. It is subject to the same global rate limiting (ThrottlerGuard) as any other API route — there is no exception for public routes.
Landing visibility (isVisibleOnLanding)
Each plan has an isVisibleOnLanding flag (default false, hidden) controlling whether it appears in GET /billing/plans/public. Only a platform super admin can set it, and only from POST /billing/plans (create) or PATCH /billing/plans/:id (update) — the same assertSuperAdmin() gate as the rest of plan management. A newly created plan stays hidden until it is explicitly marked visible; plans that existed before this flag (e.g. the internal administrator plan) migrate to isVisibleOnLanding: false through the column's default, so they do not appear on the landing either until a super admin deliberately marks them.
PATCH /billing/plans/:id
Authorization: Bearer <super-admin-token>
Content-Type: application/json
{ "name": "Pro", "isVisibleOnLanding": true }Plans seeded by default (npm run seed + runtime ensure)
The Base / Pro / Max platform plan catalogue is materialized in two equivalent ways (the same PLATFORM_PLAN_LADDER constant in src/api/billing/constants/platform-plan-ladder.ts):
npm run seed→seedPlatformPlans()- Runtime (PLANS-041-ENSURE-001) →
PlansService.ensurePlatformLadderInstantiated()inonModuleInitand before everyGET /billing/plans
Validated ladder:
| Plan | max_users | max_companies | api_access | priority_support | custom_domain | reseller_enabled |
|---|---|---|---|---|---|---|
| Base | 3 | 1 | yes | no | no | no |
| Pro | 15 | 5 | yes | yes | no | no |
| Max | 150 | 25 | yes | yes | yes | yes |
This seed/ensure is idempotent but stricter than the rest of the script: if any platform plan already exists (even one not called Base/Pro/Max), the whole ladder seed is skipped — it neither fills missing tiers nor overwrites existing plans. It only runs when billing_plans is completely empty. It does not create prices: checkout still needs POST /billing/plans/:id/prices (or a Super Admin) to attach amounts.
These limits are enforced on the owner's account/tenant:
max_companies—CompaniesService.create()(PLANS-003) consults the activemax_companiesentitlement of the companies the owner already holds and rejects with 409 Conflict the creation of one more company once the plan limit is reached — see Companies for the behaviour and the error message.max_users—CompaniesService.addUser()consults the activemax_usersentitlement of that same company (unlikemax_companies, it is not aggregated at owner level) and rejects with 409 Conflict adding one more member once the limit is reached — see Companies.api_access—ApiKeysService.create()(POST /api-keys) reads the tenant's active subscription and rejects with 403 Forbidden the creation of an API key when that subscription's plan does not declare theapi_accessfeature — see API Keys. A tenant with no active subscription is not blocked (pre-existing, billing-agnostic behaviour).
In all three cases an owner/tenant with no active subscription is unaffected — there is nothing to enforce until a plan is purchased. priority_support and custom_domain are stored and shown in the catalogue but have no enforcement in this delivery: there is still no product module depending on them (out of scope for this module). See also company-ownership.md.
Creating a plan
POST /billing/plans
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "Pro",
"description": "Plan for teams",
"features": ["api_access", "priority_support"],
"limits": { "max_users": 15, "max_companies": 5 }
}Plans are a global platform resource — they belong to no tenant (BillingPlanEntity has no companyId). That is why creating or modifying a plan requires being a platform super admin (isSuperAdmin: true); being OWNER/ADMIN of a company is not enough: a company role only authorizes acting on that company's resources, and a plan belongs to none. The same applies to PATCH /billing/plans/:id and to adding prices (below).
isVisibleOnLanding is optional in the body — when omitted the plan stays hidden (false) by default; see "Landing visibility" above.
Catalogue validation: every features key must be a catalogue option of type flag (system or non-archived platform custom) and every limits key must be one of type limit with a numeric value ≥ 0 — see "Feature and limit catalogue" below. A nonexistent key, a key of the wrong type, or a negative/non-numeric limit returns 400 Bad Request. When editing a plan that already carried an archived custom key, that key can be kept without error; it is only rejected when trying to add it to a plan that did not have it.
Deactivating a plan
PATCH /billing/plans/:id
Authorization: Bearer <token>
Content-Type: application/json
{ "name": "Pro", "isActive": false }Deactivating a plan removes it from GET /billing/plans and blocks POST /billing/subscription and POST /billing/checkout for that plan with 400 Bad Request — it is not offered to new subscriptions. Tenants that already had an active subscription to that plan do not lose their entitlements immediately: they keep them until the current period ends or until they switch plans (there is no automatic revocation on deactivation).
Adding a price to a plan
POST /billing/plans/:id/prices
Authorization: Bearer <token>
Content-Type: application/json
{
"amount": 2900,
"currency": "usd",
"interval": "monthly"
}The amount is in cents (2900 = $29.00). Available intervals: monthly, yearly, weekly, one_time.
Only one active price per interval can exist on a plan. Requires being a platform super admin — same reason as creating/updating a plan.
If synchronization with the payment provider fails, it answers 502 BILLING_PROVIDER_FAILURE (retryable: true) and does not persist the local price — you can retry.
Feature and limit catalogue
Instead of writing a plan's features/limits as loose keys, there is a catalogue with human labels: system options (fixed, not removable) plus custom ones (added by whoever manages the catalogue). This section covers the platform scope (Super Admin → billing/plans plans); the company scope (Owner/Admin → resale plans, owner_plans) uses the same system-option model but with its own per-company custom catalogue — see Owner resale plans.
System options
GET /billing/catalog/system-options
Authorization: Bearer <token>Returns the fixed catalogue — requires no specific role:
key | label | type |
|---|---|---|
max_users | Maximum users | limit |
max_companies | Maximum companies | limit |
api_access | API access | flag |
priority_support | Priority support | flag |
custom_domain | Custom domain | flag |
reseller_enabled | Resale enabled | flag (platform plans only) |
provider_platform_stripe | Platform Stripe | flag |
provider_platform_s3 | Platform S3 storage | flag |
provider_platform_ai | Platform AI | flag |
ai_included_tokens | AI tokens included per cycle | limit |
ai_included_requests | AI requests included per cycle | limit |
ai_model_allowlist | Allowed AI models (platform) | list (in metadata / body lists) |
ai_max_tokens_per_request | Token ceiling per request | limit |
ai_rate_limit | Plan AI rate limit (≤ global) | limit |
ai_assistants | Assistants (tenant chatbots) | flag (different from platform AI) |
ai_public_widget | Public assistants widget | flag (different from ai_assistants) |
ai_max_assistants | Maximum assistants per company | limit (optional; not in the plan = no hidden cap) |
ai_max_skills | Maximum tenant skills per company | limit (optional; not in the plan = no hidden cap) |
This catalogue is not persisted and cannot be edited through the API — it lives as a constant in the code (src/api/billing/constants/system-catalog-options.ts) and is the source of truth for the keys used in BillingPlanEntity.features/.limits.
Platform custom options
GET /billing/catalog/custom-options?includeArchived=false
POST /billing/catalog/custom-options
Authorization: Bearer <token>
Content-Type: application/json
{
"key": "white_label_reports",
"label": "White-label reports",
"type": "flag"
}Creating, archiving and reactivating platform custom options requires being a platform super admin (same reason as creating/editing plans). key is unique against the system catalogue and against other custom options of the same scope — a clash returns 409 Conflict.
Archiving a custom option
POST /billing/catalog/custom-options/:id/archive
Authorization: Bearer <token>Archiving is a flag, never a deletion: the custom option stops being offered in the default listing (includeArchived=false, the one the plan editor uses when adding new options), but the value existing plans already carry is untouched — GET /billing/catalog/custom-options?includeArchived=true still returns it. POST .../unarchive reactivates it.
Subscriptions
The subscription, invoice, entitlement, checkout, portal and Connect routes operate on the active company that TenantInterceptor resolves in the request context. For any user JWT, including a Super Admin's, X-Company-Id can select only a company with an active UserCompany membership, and its current roles/grants apply. API keys stay bound to their company. The /billing/platform/* routes keep their explicit companyId and their global platform operation permissions.
Reading the tenant's current subscription
GET /billing/subscription
Authorization: Bearer <token>
X-Company-Id: <companyId>Returns the most recent subscription with its state, period dates and whether it is scheduled for cancellation; it answers null when the tenant does not have one yet. The plan and price relations may be omitted depending on the route that produced the response. Dates are serialized as ISO 8601.
Creating or updating a subscription
POST /billing/subscription
Authorization: Bearer <token>
X-Company-Id: <companyId>
Content-Type: application/json
{
"priceId": "price-uuid",
"trialDays": 14
}trialDays is optional. Requires the OWNER or ADMIN role. If the tenant already has an active subscription, this POST updates it in place (plan/price, period and entitlements) instead of inserting a second row.
If the payment provider fails during creation or update, the API answers 502 with the code BILLING_PROVIDER_FAILURE (fixed message, retryable: true). Success is not confirmed and no inconsistent subscription is left behind — you can retry the same operation.
Cancelling a subscription
DELETE /billing/subscription
Authorization: Bearer <token>
X-Company-Id: <companyId>
Content-Type: application/json
{ "atPeriodEnd": true }atPeriodEnd: true— the subscription continues until the end of the current period and then cancels. Entitlements stay active until then.atPeriodEnd: false— immediate cancellation. Entitlements are revoked instantly.
Requires the OWNER or ADMIN role. A provider failure on cancellation also answers 502BILLING_PROVIDER_FAILURE (retryable); the local state is not marked as cancelled when Stripe did not complete the operation.
Entitlements
Subscription, invoice and entitlement responses expose the fields of their existing records with ISO 8601 dates. A subscription may include plan and price; those relations are optional. Metadata is informative and must be treated as neither secret nor editable input.
Entitlements are the right way to ask whether a tenant has access to something:
Listing the tenant's entitlements
GET /billing/entitlements
Authorization: Bearer <token>
X-Company-Id: <companyId>Checking access to a feature
GET /billing/entitlements/check?feature=advanced_reports
Authorization: Bearer <token>
X-Company-Id: <companyId>Response:
{ "has": true, "feature": "advanced_reports" }This is the call other modules must make to gate access to paid features.
Invoices
GET /billing/invoices
Authorization: Bearer <token>
X-Company-Id: <companyId>Lists the tenant's invoices in reverse chronological order.
Payment sessions (Stripe)
For payment flows with a visual interface, Stripe sessions can be generated:
Checkout — subscribe to a plan
POST /billing/checkout
Authorization: Bearer <token>
X-Company-Id: <companyId>
Content-Type: application/json
{
"priceId": "price-uuid",
"successUrl": "https://my-app.com/billing/success",
"cancelUrl": "https://my-app.com/billing/cancel"
}Returns { "url": "https://checkout.stripe.com/..." }. Redirect the user to that URL.
If Stripe cannot create the session, it answers 502 BILLING_PROVIDER_FAILURE (retryable: true) — no success URL is invented.
Billing portal — manage an existing subscription
POST /billing/portal
Authorization: Bearer <token>
X-Company-Id: <companyId>
Content-Type: application/json
{ "returnUrl": "https://my-app.com/billing" }Returns { "url": "..." } with the Stripe portal session where the user can update their payment method, view invoices and cancel.
Provider failure → 502 BILLING_PROVIDER_FAILURE (retryable).
Connect (the tenant's charge account)
Links the tenant's charge account through the provider onboarding (e.g. Stripe Connect). It exposes no secrets.
Reading the status
GET /billing/connect/status
Authorization: Bearer <token>Response (example):
{
"status": "not_connected",
"usable": false,
"providerName": "noop",
"onboardingUrl": null,
"errorCode": null,
"errorMessage": null
}status values: not_connected | pending | connected | error. usable is true only when Connect is connected and usable for new charges.
Starting onboarding (OWNER / ADMIN)
POST /billing/connect/onboarding
Authorization: Bearer <token>
Content-Type: application/json
{
"returnUrl": "https://localhost:4201/settings/billing/connect/return",
"refreshUrl": "https://localhost:4201/settings/billing/connect/refresh"
}Returns status: pending and an onboardingUrl to redirect the user to. After completing onboarding, GET /billing/connect/status becomes connected / usable: true. MEMBER and VIEWER receive 403.
Disconnecting (OWNER / ADMIN)
DELETE /billing/connect
Authorization: Bearer <token>Marks Connect as not_connected and not usable for new charges. MEMBER and VIEWER receive 403.
Webhooks
The webhook endpoint is public (no JWT required) but it verifies the provider's cryptographic signature before processing anything.
POST /webhooks/stripe
stripe-signature: <signature>
Content-Type: application/json
<unparsed payload>The endpoint is managed by the generic Webhooks module — see the Webhooks page for the infrastructure details.
The flow is:
- Verify the signature → rejected with 400 when invalid
- Check idempotency → ignored when the event was already processed
- Store a pending record in the database
- Enqueue an asynchronous job to process it
- Return
{ "received": true }immediately
The real processing happens in the background, without blocking the response to the provider.
Automatic notifications
When billing events happen, the system automatically notifies every member of the affected tenant:
| Event | Notification |
|---|---|
| Failed payment | PAYMENT_FAILED — in-app and email alert |
| Subscription cancelled | SUBSCRIPTION_CHANGED |
| New invoice available | INVOICE_AVAILABLE |
| Trial period ending | TRIAL_ENDING |
Multi-tenancy
Billing belongs to the tenant (company), not to a specific user. Each company has its own billing customer, its own subscriptions and its own entitlements. A tenant can never see or affect another tenant's billing.
Configuration
| Variable | Description |
|---|---|
BILLING_PROVIDER | noop (default, no real payments) · stripe |
STRIPE_SECRET_KEY | Stripe secret key (required when BILLING_PROVIDER=stripe) |
STRIPE_WEBHOOK_SECRET | Stripe webhook signing secret |
In a local or test environment, use BILLING_PROVIDER=noop — everything works without calling any external API.