Help
Billing
AIGov billing (Stripe + Postgres)
This document describes the minimal production-safe billing path: ledger tenant ↔ Stripe customer/subscription, webhooks, Checkout, usage traces, metered reporting, and optional enforcement.
Contract pricing: customers are priced individually (one Stripe Price per contract; the tier comes from Price metadata). See commercial/stripe-contract-billing.md.
Tenant ↔ Stripe mapping#
- Ledger
tenant_idis the value fromAIGOV_API_KEYS_JSONfor the caller’s API key (seerust/src/audit_api_key.rs). It is not derived fromX-AIGov-Project. tenant_billing_accounts(migration0014_tenant_stripe_billing.sql) stores one row pertenant_idwith:stripe_customer_id,stripe_subscription_id, optionalstripe_subscription_item_idsubscription_status(Stripe subscriptionstatus, ornoneif no row / not yet linked)current_period_start/current_period_endwhen known from subscription webhooksbilling_invoice_status(paid/failed) wheninvoice.paid/invoice.payment_failedmatch a known customer
Rows are created/updated by:
POST /billing/checkout-session— does not insert DB rows by itself; Stripe Checkout creates the customer/subscription.- Stripe webhooks —
checkout.session.completedupserts usingclient_reference_idormetadata.tenant_id;customer.subscription.*upserts usingsubscription.metadata.tenant_idor, if missing, an existing row matched bystripe_customer_id.
Checkout flow#
Endpoint: POST /billing/checkout-session (Bearer API key required; not subject to billing enforcement.)
Body:
price_id is optional. When omitted, the server uses AIGOV_STRIPE_PRICE_PRO (or legacy AIGOV_STRIPE_PRICE_TEAM). If neither is set → 503 STRIPE_PRICE_NOT_CONFIGURED.
Production redirects (govbase.dev): use absolute URLs such as https://govbase.dev/billing?checkout=success and https://govbase.dev/billing?checkout=cancel.
Behavior:
- Resolves
tenant_idfrom the API key mapping. - Calls Stripe
/v1/checkout/sessionsin subscription mode with:client_reference_id=tenant_idmetadata[tenant_id]andsubscription_data[metadata][tenant_id]=tenant_idline_items[0][price]=price_id, quantity1
Response: { "ok": true, "tenant_id", "session_id", "checkout_url" }
Requires: AIGOV_STRIPE_SECRET_KEY (sk_test… / sk_live…). If missing or empty → 503 with STRIPE_NOT_CONFIGURED.
Webhook lifecycle#
Endpoint: POST /stripe/webhook (unsigned; uses Stripe-Signature + AIGOV_STRIPE_WEBHOOK_SECRET.)
Persistence: Every verified event is inserted into stripe_webhook_events (stripe_event_id PK). Duplicates return 200 with "duplicate": true once processing completed.
Processing (idempotent side effects):
| Event | Effect |
|---|---|
checkout.session.completed | Upsert tenant_billing_accounts with customer + subscription ids; status incomplete if subscription id present |
customer.subscription.created / updated | Upsert subscription fields, periods, first subscription item id |
customer.subscription.deleted | Set subscription_status to canceled |
invoice.paid / invoice.payment_succeeded | If customer maps to a tenant: set billing_invoice_status=paid |
invoice.payment_failed | If customer maps: billing_invoice_status=failed, subscription_status=past_due |
Events that cannot be mapped (e.g. invoice for an unknown Stripe customer) do not fail the webhook — Stripe still receives 200 after persistence.
Retries: If processing fails, the handler returns 500 and leaves processed_at null so a retry can re-run processing. After success, processed_at is set.
Configure in Stripe Dashboard: point the webhook URL at https://<host>/stripe/webhook and select at least the event types above.
Usage traces and reporting#
- Traces: Each successful
POST /evidenceappendsaigov_billing_usage_trace(ledger_tenant_id,run_id,billing_unit, defaultevidence_event). - Summary:
GET /billing/usage-summary— unchanged; aggregates traces for a time window. - Stripe metered push:
POST /billing/report-usage(Bearer; optional body{ "billing_unit": "evidence_event" }):- Resolves the billing window: the subscription
current_period_*fromtenant_billing_accounts. Without one the window is "UTC month start to now", which changes on every call and means nothing to Stripe, so such a report is recorded locally and never sent (recorded_local). - Counts traces in that window and keeps one
billing_usage_reportsrow per(tenant_id, billing_unit, period_start, period_end). The row freezes what Stripe is told:action=setat one fixed Stripetimestampfor the whole period and an idempotency key. The quantity is the cumulative counted usage and is a series of revisions (see below): a later call whose count is higher moves the row to the next revision and sends the new total; an unchanged count sends nothing. - With a registered usage item for the billing unit (
tenant_billing_subscription_items, matched fromAIGOV_STRIPE_PRICE_<UNIT>) andAIGOV_STRIPE_SECRET_KEY, posts the usage record and storesstripe_usage_record_id. The subscription's first (licensed contract) item is never used for usage. Without a usage item it staysrecorded_localand is sent later if an item and an aligned period appear.
- Resolves the billing window: the subscription
Report states (billing_usage_reports.status) and what the endpoint answers
| State | Meaning | Endpoint | What happens on the next call |
|---|---|---|---|
pending | Created, never sent | n/a | sent |
reported | Stripe confirmed (or the usage was found at Stripe, reconciled: true) for the current revision | 200 | idempotent hit while the counted usage has not grown; a higher count becomes the next revision (pending) and is sent |
rejected | Stripe refused it (4xx, rate limit, or the connection failed before the request left): nothing was applied | 502 STRIPE_USAGE_REPORT_REJECTED | sent again, unchanged. Safe. |
uncertain | Outcome unknown: 5xx, timeout, lost connection, unreadable reply, a conflict, or a worker that stopped mid-attempt. Stripe may have applied it. | 502 STRIPE_USAGE_REPORT_UNCERTAIN | first checked against Stripe's usage summary: found, so reported without sending; not found, so the identical request is replayed; more usage than recorded, so needs_review |
needs_review | Stripe holds more usage for the period than was recorded, or automatic reconciliation gave up after its bounded attempts (escalation_reason says which) | 409 STRIPE_USAGE_NEEDS_REVIEW | nothing is sent automatically until an operator re-runs or resolves it |
resolved_manual | An operator decided it needs no further automatic action (confirmed_at_stripe, invoiced_manually or waived), with name and reason | 200 | idempotent hit; recorded, never silent |
recorded_local | No Stripe-aligned window or no subscription item | 200 | idempotent hit; promoted to pending when both exist |
A call made while another worker holds the report answers 202 with status: in_flight; it sends nothing.
What is guaranteed, and what is not
- Within this failure model, no code path produces a second billable record for the same report: concurrent workers (one holds a lease at a time), repeated submissions, timeouts, 502s, and a worker that crashes mid-attempt. A resend is the same request, so Stripe replays its stored answer for the same idempotency key, and even if that key has expired (Stripe keeps it 24 hours) or the usage summary cannot be read, a
setat the same timestamp overwrites the same usage record instead of adding another (usage at different timestamps is summed underaggregate_usage = sum, which is why the timestamp is frozen). - Every attempt is written to the append-only
billing_usage_report_eventstable before the request leaves, and its outcome after:attempt_started,reported,rejected,ambiguous,reconciled_match,reconciled_overcount,unfinished_attempt, and from migration 0054revision_created,retry_scheduled,verified_match,verified_undercount,closed_out,escalated,manual_resolved, each with itsrevisionand itsactor(request,worker,operator). A crash therefore leaves a trace, and the next call knows the outcome is uncertain. - This is not exactly-once delivery, which Stripe cannot promise. An ambiguous outcome stays
uncertainuntil Stripe can be asked or answers; Stripe may replay a stored 5xx for the same key for up to 24 hours, during which the report staysuncertain(nothing is double counted, and nothing is lost). - The guarantees assume the documented Stripe behaviour: an idempotency key replays the first result, and
action=setoverwrites the usage at the same timestamp. They were tested against a local model of that behaviour (rust/tests/fake_stripe.rs), not against Stripe: confirm both with a test-mode subscription before relying on them, and note that Stripe's legacy usage-record endpoint is replaced by meters in newer API versions. - Usage recorded after a report is not lost: it becomes the next revision (previously, from migration 0053 until 0054, a later call returned the first report as an idempotent hit and the later usage was never sent). A count that goes down never lowers a report.
Revisions: usage recorded after a report#
Which Stripe model is used: the code reports legacy usage records (POST /v1/subscription_items/{id}/usage_records, pinned API version, see below), not Billing Meters. action=set at a timestamp overwrites the usage held at that timestamp (Stripe's documented behaviour for the legacy endpoint; modelled in rust/tests/fake_stripe.rs, not verified against Stripe here).
- The first report of a period creates revision 1 and freezes the period's Stripe timestamp
T(inside the period, never in the future). - Each later call (or worker pass) counts the usage again. If the count
nexceeds the row's quantity, the row becomes revisionr+1:quantity = n, a new idempotency keyaigov-usage-<id>-r<r+1>, statuspending, and arevision_createdevent. It is sent asaction=set&quantity=n×tamp=T: Stripe's one usage record of the period now holdsn. Because it is asetat the same timestamp, a replay, a retry after an uncertain outcome and a revision can never add to one another, also after the 24-hour idempotency window. - The conditional
update ... where quantity < nmakes two concurrent callers unable to create the same revision. If a revision is created while an older one is in flight, the older result is recorded (reported_quantity, event) but cannot mark the newer revision reported; the newer one stayspendingand is sent next. reported_quantityis the cumulative usage known to be held by Stripe;quantity - reported_quantityis what is still owed to Stripe.- Periods that already ended: usage cannot grow, but the last interval before the renewal may not have been reported. The worker's close-out step counts the ended period one final time; a higher count is a final revision, and
closed_out_atis set only when the count equals what was reported.
Reconciliation worker and operators#
Nothing depends on a customer calling POST /billing/report-usage. A pass (the in-process worker, POST /internal/billing/reconcile, or any scheduler that calls that endpoint) is bounded by AIGOV_BILLING_RECONCILE_BATCH rows per step and does, in order:
- sync current periods: every tenant with a Stripe-aligned period and an active item gets its current-period report created and brought up to the counted usage;
- close out ended periods (see above);
- drive unresolved reports of any period (
pending,rejected,uncertain): the same claim, reconcile and send steps as the endpoint (stripe_billing::drive_report), with exponential back-off (60 s doubling, capped at 3 h). AfterAIGOV_BILLING_RECONCILE_MAX_ATTEMPTSunsuccessful passes (default 8, about 4 hours) the report is escalated toneeds_reviewwith its reason; every wait is aretry_scheduledevent, the escalation anescalatedevent. An unresolved report is never markedreportedwithout Stripe's own answer or figure confirming it; - verify recent reported rows against Stripe's usage summary (period ended within 3 days or still open, at most every 6 hours): Stripe holding less than reported (an out-of-order or lost write) is restored by the identical
setunder a new key (verified_undercount), Stripe holding more is escalated (reconciled_overcount).
Operation: the worker starts with the API when a Stripe key is configured (AIGOV_BILLING_RECONCILER=off disables it; AIGOV_BILLING_RECONCILE_INTERVAL_SECS, 30 to 86400, default 300; the first pass runs 20 s after start so a restart recovers quickly). Passes are serialised by a Postgres advisory lock and each report has its own lease, so several replicas are safe. A pass can also be scheduled externally: curl -X POST -H "Authorization: Bearer $AIGOV_BILLING_OPERATOR_TOKEN" https://<host>/internal/billing/reconcile.
Operator endpoints (bearer AIGOV_BILLING_OPERATOR_TOKEN, not a tenant key; unset or empty means 503, wrong means 401):
| Method | Path | Purpose |
|---|---|---|
| GET | /internal/billing/usage-reports | Unresolved reports of every period (?status=a,b&tenant_id=&limit=), oldest period first, with attempts, next_attempt_at, escalation_reason, quantity vs reported_quantity, last event and a recommended_action |
| GET | /internal/billing/usage-reports/:id | One report with its full append-only event trail |
| POST | /internal/billing/usage-reports/:id/rerun | Forget the back-off and run the claim, reconcile and send steps once now (a needs_review report first goes back to uncertain, so Stripe's own figure is read first) |
| POST | /internal/billing/usage-reports/:id/resolve | Record a manual resolution: resolution (confirmed_at_stripe, invoiced_manually, waived), operator, note (at least 10 characters); refused for reported reports and for a report being sent right now |
| POST | /internal/billing/reconcile | Run one pass now |
| POST | /internal/billing/contracts/:tenant | Append the next contract version: tier, billing_interval, evidence_events_per_month, overage_enabled (default off), overage_cap_events (required when overage is on), optional stripe_price_id, note, operator. See commercial/stripe-contract-billing.md |
| GET | /internal/billing/contracts/:tenant | Every contract version of the tenant and where its usage stands |
| GET | /internal/billing/overview | Tenants with failed payments or past-due status, unprocessed webhook events with their error, counts of unresolved usage reports |
Compatibility: POST /billing/report-usage keeps its path, body and fields and gains revision and reported_quantity. What changed is behaviour: a repeated call in the same period is no longer always an idempotent hit; it bills usage recorded since the last revision (idempotent_hit: false, revision increased). Callers that expected a frozen quantity per period must read quantity as the cumulative total. Migration 0054 only adds columns, widens two check constraints and adds two indexes; existing rows keep their status, and reported rows start with reported_quantity = quantity.
Stripe API version and the legacy usage-record endpoint
- Per Stripe's changelog and migration guide,
POST /v1/subscription_items/{id}/usage_recordsandusage_record_summarieswere removed in API version2025-03-31.basil; they remain available only to a request that pins2025-02-24.acaciaor older. The code does not rely on the account's default version: both calls sendStripe-Version: 2025-02-24.acacia(stripe_billing::USAGE_API_VERSION;AIGOV_STRIPE_USAGE_API_VERSIONoverrides it with another valid date). - This keeps working only for legacy metered prices (
aggregate_usage). A price backed by a Billing Meter needs the meter-events API (POST /v1/billing/meter_events, additive, de-duplicated by anidentifier), which has different semantics (noset, asynchronous aggregation) and is not implemented. Whether the production prices are legacy or meter-backed cannot be read without the Stripe account, so it is an open question for the owner, and the migration is a product decision, not a silent change. - From
basilthe subscription period moved from the subscription to its items;subscription_periodreads either shape, so a webhook from an account on any version still gives the tenant its billing period. If neither is present the period stays empty and reports are recorded locally, never sent. - Idempotency, as documented by Stripe for API v1: the status and body of the first request are saved once the endpoint starts executing and returned for retries including
500; keys may be pruned after 24 hours; the same key with different parameters is an error; a request rejected by validation or by a concurrent request with the same key is not saved and can be retried. The code and the test model follow exactly that. - The statement that
action=setoverwrites the usage held for the same timestamp (so a resend at the frozen timestamp cannot add to the first) is Stripe's documented behaviour for the legacy endpoint but is not asserted by any test against Stripe; it is modelled.rust/tests/stripe_real_test_mode.rsis the check to run with a test-mode key.
Billing enforcement#
Variable: AIGOV_BILLING_ENFORCEMENT = on (1, true, yes, on) | off (0, false, no, off). When unset, enforcement is on in staging and prod and off in dev. Production-like environments log an error if it is disabled.
When on, the gate decides per ledger tenant from its public.tenants registry row (commercial_state::runtime_billing_verdict, the same plan rule as the commercial lifecycle):
| Registry row | Result |
|---|---|
status active or pending_legal_acceptance, plan free / developer / internal / trial / pilot | allowed without a subscription (the legal gate still applies to pending_legal_acceptance) |
status active or pending_legal_acceptance, any other plan | allowed only with tenant_billing_accounts.subscription_status active or trialing, otherwise 403 BILLING_INACTIVE |
status restricted, suspended, deleted or any other value | 403 TENANT_NOT_ACTIVE, whatever the plan |
| no registry row | treated as a paid tenant: needs an active/trialing subscription, otherwise 403 BILLING_INACTIVE; an exempt plan is never assumed. A subscription is not enough: with legal enforcement on, the legal gate also denies a ledger tenant without a registry row (403 LEGAL_ACCEPTANCE_REQUIRED) unless an operator listed it in AIGOV_UNREGISTERED_TENANT_ALLOWLIST (see docs/tenant-console/ledger-binding.md) |
A database error while deciding returns 500 BILLING_GATE_ERROR (fail closed). The plan is read from the registry by the key-derived ledger tenant; a caller cannot choose or claim a plan.
Never enforced on:
GET /health,GET /ready(core router / unauthenticated audit)POST /stripe/webhookPOST /billing/checkout-sessionGET /billing/status
Billing status and entitlements#
Endpoint: GET /billing/status (Bearer API key).
Returns Stripe ids, subscription_status, commercial_plan (free | pro | enterprise), commercial_plan_display, can_use_hosted_api (with enforcement on: whether the billing gate would let this tenant call the API, per the table above; with enforcement off: true when status is active or trialing), subscription_active (true when status is active or trialing), latest_invoice_status, mapped billing_units, and operator flags:
enforcement_enabled— whetherAIGOV_BILLING_ENFORCEMENTis on for this deploymentpro_list_price_monthly— authoritative list price, for in-app billing UI copy only (not published on the public site)stripe_configured/stripe_checkout_configured— whether Checkout can run without passingprice_id
commercial_plan may still show Pro for past_due / unpaid while can_use_hosted_api is false (display vs entitlement).
GET /usage (metering off) resolves the same commercial plan from tenant_billing_accounts for limit fields.
Environment variables#
| Variable | Purpose |
|---|---|
AIGOV_STRIPE_SECRET_KEY | Stripe API secret for Checkout, portal, invoices, usage records |
AIGOV_STRIPE_WEBHOOK_SECRET | Webhook signing secret (whsec_…) |
AIGOV_STRIPE_PRICE_PRO | Default Pro subscription Price for Checkout when price_id omitted |
AIGOV_STRIPE_PRICE_TEAM | Legacy alias for Pro Price |
AIGOV_STRIPE_PRICE_ENTERPRISE | Maps subscription items to enterprise entitlements |
AIGOV_STRIPE_PRICE_* (metered) | Optional unit prices — see stripe_billing.rs |
AIGOV_API_KEYS + AIGOV_API_KEYS_JSON | API keys and ledger tenant ids (required for meaningful multi-tenant billing) |
AIGOV_BILLING_ENFORCEMENT | Optional subscription gate on hosted billable routes (on by default in staging and prod) |
NEXT_PUBLIC_AIGOV_API_BASE_URL | Dashboard /billing → Rust API (browser) |
Local testing with Stripe CLI#
- Run Postgres + migrate (
sqlx migrate/AIGOV_AUTO_MIGRATE/ your deploy process). - Export
AIGOV_STRIPE_WEBHOOK_SECRETfromstripe listen --forward-to localhost:8088/stripe/webhook. - Trigger test events:
stripe trigger customer.subscription.updated(extend payload JSON in Dashboard Send test webhook to includemetadata.tenant_idmatching a key inAIGOV_API_KEYS_JSON). - Complete Checkout in test mode and confirm
tenant_billing_accountsupdates.
Known limitations#
- One metered path: usage records use the first subscription item id captured from webhook payloads; complex multi-item subscriptions need operator alignment.
- No hosted billing UI, proration, tax, or dunning automation beyond webhook state updates.
- Team tables from migration
0012(team_billing,team_subscriptions) are not wired into this path; this implementation uses ledgertenant_id(tenant_billing_accounts) only. - Checkout and usage APIs call Stripe over the public network; failures return structured JSON errors.
Related code#
rust/src/stripe_billing.rs— DB + Stripe HTTP helpersrust/src/stripe_webhook.rs— verify + persist + dispatchrust/migrations/0014_tenant_stripe_billing.sql— schema