Subscription billing
Subscription billing is the paid-product boundary for a tenant. Stripe manages the hosted account's customer, subscription, invoices, and payment methods. The subscription domain manages recurring product agreements and cycles. The web client gives tenant admins one place to view and manage the paid account.
Billing boundary
Hosted billing service
The billing service connects a hosted Gauzy deployment to Stripe without exposing Stripe credentials to the browser. It supports common in-product actions and sends users to Stripe's customer portal for Stripe-managed work. Billing stays optional for self-hosted deployments because it is inactive without a usable key. Live mode also needs explicit opt-in, and demo deployments do not use billing.
References: packages/…/stripe-subscription.service.ts• L82-170 packages/…/billing.service.ts• L100-121 packages/…/billing.module.ts• L10-21
Tenant billing identity
A Stripe customer is the billing identity for one tenant. The tenant stores the Stripe customer ID after a safe match. Later requests use this durable link instead of matching by email again, so an email change cannot move billing to another account.
The link requires a verified email, one tenant match, and an unclaimed Stripe customer. It is best effort during tenant creation and can be completed when the user first opens billing settings. Before billing data is served, the link is checked against the deployment's product.
References: packages/…/tenant.entity.ts• L27-43 packages/…/tenant.service.ts• L48-58 packages/…/tenant.service.ts• L111-215 packages/…/billing.controller.ts• L223-252
Billing API surface
The billing API exposes tenant-scoped reads and actions to account administrators. It resolves the Stripe customer from the request tenant and its stored link. The client cannot choose a customer ID.
The API supports:
- Billing availability and Stripe live or test mode.
- The current subscription and purchasable plans.
- Plan changes, end-of-period cancellation, and cancellation resume.
- Invoice history and limited card display data.
- Short-lived Stripe portal sessions with a safe return address.
Plans come from active Stripe prices for the Gauzy product and hosted deployment. Subscription and invoice reads use the same product scope when a customer has more than one Ever product.
References: packages/…/billing.controller.ts• L56-166 packages/…/billing.service.ts• L124-180 packages/…/billing.service.ts• L328-375
Recurring product subscriptions
The recurring subscription domain represents a customer agreement on a plan. A plan defines recurring terms and may point to a catalogue product or variant. A subscription keeps its recurring lines and calendar. A billing cycle records the period, attempt, and result.
The domain delegates catalogue checks, recurring prices, order creation, and payment instruments to platform capabilities. It owns the agreement, calendar, lines, cycle history, and lifecycle events. It does not own the order or payment records. Stripe tenant billing remains a separate boundary.
References: packages/…/subscription.plugin.ts• L20-43 packages/…/subscription.types.ts• L4-12 packages/…/subscription.types.ts• L97-164 packages/…/subscription.types.ts• L257-331
Customer and webhook flow
Checkout-to-tenant link
Checkout happens outside the product. A buyer pays through the shared checkout host, then registers in Gauzy. Registration checks the paid entitlement before it creates a hosted tenant.
This diagram shows how checkout becomes a durable tenant billing link.
flowchart LR
B[Checkout host] --> S[Stripe customer and subscription]
S --> R[Hosted registration]
R --> E[Entitlement check]
E --> T[Tenant creation]
T --> V[Verified email]
V --> L[Stored Stripe customer ID]
L --> A[Billing API]
A --> S
The link can be absent just after tenant creation while email verification is pending. The first billing settings visit can complete it after verification.
References: packages/…/subscription-required.guard.ts• L4-23 packages/…/auth.controller.ts• L129-150 packages/…/tenant.service.ts• L48-58 packages/…/tenant.service.ts• L177-215
Webhook customer linking
The webhook endpoint completes a missing tenant-to-customer link when a subscription starts outside Gauzy. It accepts a payload only after it verifies the Stripe signature against the raw body. It then uses the customer email only as a safe matching aid.
The endpoint writes a link only when the email is verified, the tenant match is unique, the customer is unclaimed, and the tenant has no existing link. It does not mirror Stripe subscription state locally. After signature verification, handler errors are logged and acknowledged so operators can replay the event.
References: packages/…/stripe-webhook.controller.ts• L10-77 packages/…/stripe-webhook.controller.ts• L79-177 packages/…/stripe-webhook.controller.ts• L179-209
Product subscription creation
Creation turns a sellable plan and customer into one recurring agreement. The plan must be active and its catalogue target must support recurring sale. The agreement, its lines, its first cycle, and its creation event commit as one result.
Creation can start billing, remain pending, or start a trial. A retry can name the originating order and receive the existing agreement. A trial's first cycle is zero and waived. Its expected recurring value is kept as context rather than reported as money owed.
References: packages/…/subscription.service.ts• L781-966 packages/…/subscription-item.service.ts• L59-125 packages/…/subscription-plan.service.ts• L321-341 packages/…/subscription.service.spec.ts• L961-1260
Subscription enforcement
Registration entitlement
An entitlement is the right to complete hosted registration because a Stripe customer has an allowed subscription. The guard checks the submitted email only for a new public registration. It does not block an authenticated administrator who adds a user to an existing tenant.
| Stripe result | Registration behavior |
|---|---|
| Active, trialing, or past due subscription | Allow registration. |
| No matching subscription | Send the visitor to checkout. |
| Stripe cannot answer | Allow registration and record the lookup problem. |
Billing is not enforced when Stripe is not configured. This keeps the normal registration flow for self-hosted deployments and favors continuity when a recent payment cannot yet be read.
References: packages/…/subscription-required.guard.ts• L11-23 packages/…/subscription-required.guard.ts• L25-76 packages/…/stripe-subscription.service.ts• L49-80 packages/…/stripe-subscription.service.ts• L162-215
Subscription state
The hosted billing page treats Stripe's live subscription as the tenant account state. Established subscriptions take priority over a newer incomplete checkout attempt. Subscription and invoice views remain limited to the deployment's product.
Plan changes follow Stripe's billing rules. A change can create a proration invoice. Cancellation waits until the current paid period ends. Resume removes that pending cancellation while the period still runs. A paid plan change needs a usable default payment method.
References: packages/…/billing.service.ts• L152-180 packages/…/billing.service.ts• L202-301 packages/…/billing.service.ts• L304-325 packages/…/billing.service.ts• L428-450 packages/…/billing.service.ts• L461-468
Product agreement states
Product agreements move through pending, active, paused, canceled, expired, and failed states. These states decide whether a billing pass may act and whether the plan still has live customers. A pause does not consume the period. Cancellation can preserve the paid period. Expiry follows the plan's cycle limit.
Mid-cycle plan or line changes settle only the unused part of the current period. The result can be an immediate charge, a later credit, a small waived amount, or a next-period change. Before settlement, a plan change reserves its target plan. Plan updates count that reservation as a live dependency, so they cannot deactivate or reprice a plan while a paid change moves a subscription onto it.
Next-period changes are signed for their subscription and checked when the period opens. A refused change is cleared and announced. If settlement completes but the change cannot be applied, the domain records and streams a reversal-needed result.
References: packages/…/subscription.types.ts• L39-87 packages/…/subscription-plan.service.ts• L147-227 packages/…/subscription-plan.service.ts• L427-455 packages/…/subscription.service.ts• L1462-1519 packages/…/subscription.service.ts• L4078-4122 packages/…/subscription.service.ts• L4155-4222
Recurring billing lifecycle
Billing cycle ledger
A billing cycle records one recurring period and its payment result. It can be pending, invoiced, paid, failed, refunded, or waived. It also keeps attempts and the next retry time, so dunning is visible and recoverable.
The billing run creates or reuses one cycle and claims it before it calls the order path. The claim blocks operator payment, waiver, correction, deletion, or rescheduling while an external charge is in flight. A dead worker leaves a stale claim for a later pass to recover. Recovery uses the frozen request and the same order idempotency key.
A successful charge settles the cycle. A declined charge records failure and its retry schedule. An unpaid invoice can hold rights and the subscription calendar until payment arrives. Payment receipts remain inside the caller's tenant and organization boundary.
References: packages/…/subscription-billing.entity.ts• L17-31 packages/…/subscription-billing.entity.ts• L124-147 packages/…/subscription-billing.service.ts• L524-582 packages/…/subscription.service.ts• L2426-2667 packages/…/1791000003520-AddSubscriptionBillingChargeClaim.ts• L14-26
Billing calendar
The billing calendar determines the next period. Daily and weekly plans use fixed spans. Monthly, quarterly, and yearly plans use calendar periods, so month-end dates do not drift through short months.
Preview and billing use the same period and price rules. Preview writes no cycle, charge, adjustment, order, or event. It reports what the next billing pass would use. An unpaid invoice keeps the calendar on its period until payment moves it.
References: packages/…/subscription.cycle.ts• L5-22 packages/…/subscription.cycle.ts• L79-110 packages/…/subscription.service.ts• L1882-2020 packages/…/subscription.service.ts• L3020-3041
Billing interfaces
The domain exposes the same lifecycle through REST and GraphQL. Both use the same scope, permission rules, actions, and billing services. A cycle billing write needs retry protection. Subscription writes use the caller's version so a stale change is refused.
GraphQL also exposes plans, agreements, recurring lines, and cycles. Mutation payloads return either the business object or a user error, so a client can show why a transition was refused.
References: packages/…/subscription.controller.ts• L59-86 packages/…/subscription.resolver.ts• L74-110 packages/…/schema-extensions.ts• L546-660 packages/…/subscription.entity.ts• L184-194
Subscription event stream
The event stream tells clients about agreement and payment changes. It includes creation, activation, pause, resume, cancellation, cancellation undo, expiry, payment failure, renewal, scheduled-change refusal, and settlement-reversal-required events.
The stream is a notification path, not the source of truth. A client that misses an event must read the agreement again. Payloads carry billing facts and never card data. A settlement-reversal-required event marks money that may have moved without its agreement change being applied.
References: packages/…/subscription-streamed-events.ts• L4-35 packages/…/subscription-streamed-events.spec.ts• L21-65 packages/…/subscription.service.ts• L4869-5009 packages/…/subscription.service.ts• L4434-4482
Web billing settings
Billing settings page
The web billing settings page is the tenant admin's view of the paid account. It shows the current plan and status, available plans, trial or renewal dates, pending cancellation, card summary, invoices, and the Stripe portal link. The browser calls the Gauzy API only.
The page keeps common actions in Gauzy:
- Switch plans.
- Cancel at the end of the period.
- Resume a pending cancellation.
- Review invoices and open hosted invoices.
- Open Stripe's portal for payment details and other Stripe-managed actions.
The page first checks billing availability. A disabled deployment shows a clear unconfigured state. A failed availability check also avoids a broken billing view. When enabled, subscription, plans, invoices, and payment method load independently. Missing resources become empty states. Other failures preserve successful data and show retry.
The page explains that a recent buyer may need to verify email before the tenant link exists. A plan switch that needs a payment method can return the administrator to Stripe's portal. After a plan change, invoice data refreshes because the change can create an invoice. Unpaid or failed invoice rows show the amount due, not a misleading zero amount paid. Pending cancellation is shown once with a resume action.
References: apps/…/billing.service.ts• L6-104 apps/…/billing.component.ts• L68-114 apps/…/billing.component.ts• L121-246 apps/…/billing.component.html• L8-100 apps/…/billing.component.html• L102-195
Billing visibility and access
Billing is a tenant-wide account setting. The API limits data and actions to tenant administrators. The web route requires the tenant-setting permission. Navigation hides the entry when the deployment reports billing as disabled.
The roles and permissions screen presents subscription operations under the commerce orders area. It presents tenant-wide settings under administration settings and integrations. This grouping is display-only; the route and API remain the access boundary.
The client uses false until the API confirms availability. This prevents self-hosted or unreachable deployments from showing a menu entry that cannot work. Menu hiding is not the security boundary; the route and API enforce access separately.
References: packages/…/app-init-service.ts• L60-87 packages/…/store.service.ts• L35-73 packages/…/base-nav-menu.component.ts• L1137-1150 apps/…/billing-routing.module.ts• L7-23 apps/…/permission-sections.ts• L21-29 apps/…/permission-sections.ts• L109-146 apps/…/permission-sections.ts• L479-522 packages/…/billing.controller.ts• L69-164
Related systems
Subscription billing crosses backend, subscription-domain, and web-client boundaries. Read Backend platform for the API context, Angular web application for the client context, API application lifecycle for startup context, Domain services and contracts for service boundaries, Identity and access control for tenant and permission scope, Plugin architecture for capability boundaries, Account deletion for tenant data removal, and Background jobs and scheduling for recurring billing runs.
Change checklist
When these files or sections are changed, remember to consider these:
- When Stripe customer-link rules change, check tenant creation, first billing-page linking, webhook linking, product scope, and unique customer ownership together.
- When entitlement states change, check registration, current-subscription selection, billing-page display, and incomplete or failed Stripe states.
- When plan or product keys change, keep product checks, Stripe price lookup, API validation, checkout links, and the web plan switcher aligned.
- When billing availability changes, check the API response, client startup flag, navigation, route permission, and disabled-deployment behavior.
- When billing response fields change, update API mapping and web display together for amounts, intervals, dates, invoices, and card summaries.
- When portal return handling changes, keep same-origin validation tied to the configured client URL.
- When page load handling changes, preserve the distinction between a missing resource and an unavailable request.
- When a plan change needs a payment method, keep the API response, portal session, and page recovery action aligned.
- When a product subscription state changes, keep REST actions, GraphQL mutations, billing selection, cycle transitions, and event names aligned.
- When plan or line rules change, check sellability, pricing, proration, next-cycle pricing, reservations, and the plan-change result together.
- When cycle writes change, preserve the link between period, payment result, retry state, charge claim, and calendar.
- When charge recovery changes, keep the cycle fence, frozen request, order idempotency key, and operator guards aligned.
- When scheduled changes change, keep their subscription-bound signature, secret rotation, next-period application, refusal event, and metadata boundary aligned.
- When mutation inputs change, keep version and retry-key rules aligned across REST, GraphQL, and schema inputs.
- When payment receipt handling changes, preserve organization membership checks and request-tenant ownership.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A request accepts a Stripe customer ID from the client | One tenant can read or change another tenant's billing | Resolve the customer from request context and the tenant record. |
| A link uses an unverified or ambiguous email | The tenant can gain another person's billing account | Require a verified user, one tenant match, and an unclaimed customer. |
| A webhook skips raw-body signature checks | An attacker can write links or replay events | Verify the Stripe signature and reject stale or invalid payloads. |
| A webhook replaces an existing link | Future billing uses the wrong Stripe account | Fill only a missing link and enforce unique ownership. |
| A link points to another product | The page exposes unrelated subscriptions or invoices | Check the deployment product before serving billing data. |
| An incomplete checkout replaces an established subscription | The page shows a false plan and actions target the wrong subscription | Prefer established live subscriptions. |
| Stripe is unavailable during entitlement lookup | A paying visitor cannot finish registration | Treat the result as unknown and allow registration. |
| A cycle is not claimed before an external charge | An operator can settle it while it is being charged | Claim pending or failed cycles and reject writes during a live claim. |
| A recovered attempt is repriced from current subscription data | A retry can charge different lines or credits | Freeze the attempt request and reuse its idempotency key. |
| A plan update ignores a reserved target | A paid change can move onto a deactivated or repriced plan | Count reservations as live subscriptions under the plan lock. |
| Scheduled-change metadata is trusted without a signature | A caller can apply an unapproved future change | Sign for the subscription and verify before application. |
| Settlement completes but application fails without a record | Money moves with no repair path | Record and stream a settlement-reversal-required outcome. |
| An invoice is treated as paid before payment arrives | Rights and the calendar move too early | Keep invoiced cycles open until payment releases them. |
| A missing resource is treated as a page failure | A new tenant sees errors instead of an empty state | Treat 404 responses as empty data and preserve other failures. |
| A hard delete removes billed history | The money record is lost | Use soft retirement for billed cycles and block hard deletion. |
| A stale subscription version is accepted | A newer lifecycle change is overwritten | Require the caller's version and reject conflicts. |
| A live Stripe key is used in a demo or non-opted-in deployment | Real payment data or charges become reachable | Disable demo billing and require explicit live-mode opt-in. |
| The portal accepts an external return URL | A billing session can end on an attacker-controlled site | Accept only the configured client origin. |
Key files
| File | Why to read it |
|---|---|
| packages/…/billing.controller.ts | Tenant-admin API boundary for subscriptions, invoices, cards, and portal actions. |
| packages/…/billing.service.ts | Stripe-backed hosted billing view and plan actions. |
| packages/…/stripe-subscription.service.ts | Billing enablement and registration entitlement decision. |
| packages/…/stripe-webhook.controller.ts | Signed webhook acceptance and customer-link recovery. |
| packages/…/tenant.service.ts | Tenant creation and best-effort Stripe customer linking. |
| packages/…/subscription-required.guard.ts | Hosted registration enforcement and self-hosted behavior. |
| packages/…/payment.service.ts | Tenant and organization boundary for payment receipts. |
| packages/…/subscription.plugin.ts | Subscription capability dependencies, feature boundary, schema, and migrations. |
| packages/…/subscription.service.ts | Agreement lifecycle, scheduled changes, recurring billing, dunning, and proration. |
| packages/…/subscription.entity.ts | Agreement calendar, payer references, version, and plan reservation. |
| packages/…/subscription-plan.service.ts | Sellable plan rules and protection for live or reserved subscribers. |
| packages/…/subscription-item.service.ts | Recurring lines, price resolution, quantities, and line history. |
| packages/…/subscription-billing.service.ts | Cycle states, charge claims, outcomes, retries, and history. |
| packages/…/subscription-billing.entity.ts | Cycle record and external-charge fence. |
| packages/…/subscription.cycle.ts | Period, price, discount, and proration rules. |
| packages/…/subscription.schedule-signature.ts | Trust boundary for future changes. |
| packages/…/subscription-streamed-events.ts | Lifecycle, payment, refusal, and repair events sent to clients. |
| packages/…/1791000003520-AddSubscriptionBillingChargeClaim.ts | Durable fields for charge fencing and recovery. |
| packages/…/1791000003540-AddSubscriptionReservedPlan.ts | Durable plan reservation used during mid-cycle changes. |
| apps/…/billing.service.ts | Browser-to-API billing contract. |
| apps/…/billing.component.ts | Billing settings state, recovery actions, and display rules. |
| apps/…/billing.component.html | User-facing plan, payment, invoice, verification, and portal sections. |
| apps/…/billing-routing.module.ts | Tenant-setting permission boundary for the billing route. |
| apps/…/permission-sections.ts | Display grouping for subscription and tenant-setting permissions in the roles screen. |
| packages/…/app-init-service.ts | Client billing-availability state. |