AIGov
Menu

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_id is the value from AIGOV_API_KEYS_JSON for the caller’s API key (see rust/src/audit_api_key.rs). It is not derived from X-AIGov-Project.
  • tenant_billing_accounts (migration 0014_tenant_stripe_billing.sql) stores one row per tenant_id with:
    • stripe_customer_id, stripe_subscription_id, optional stripe_subscription_item_id
    • subscription_status (Stripe subscription status, or none if no row / not yet linked)
    • current_period_start / current_period_end when known from subscription webhooks
    • billing_invoice_status (paid / failed) when invoice.paid / invoice.payment_failed match a known customer

Rows are created/updated by:

  1. POST /billing/checkout-session — does not insert DB rows by itself; Stripe Checkout creates the customer/subscription.
  2. Stripe webhooks — checkout.session.completed upserts using client_reference_id or metadata.tenant_id; customer.subscription.* upserts using subscription.metadata.tenant_id or, if missing, an existing row matched by stripe_customer_id.

Checkout flow#

Endpoint: POST /billing/checkout-session (Bearer API key required; not subject to billing enforcement.)

Body:

{
  "price_id": "price_…",
  "success_url": "https://…",
  "cancel_url": "https://…"
}

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_id from the API key mapping.
  • Calls Stripe /v1/checkout/sessions in subscription mode with:
    • client_reference_id = tenant_id
    • metadata[tenant_id] and subscription_data[metadata][tenant_id] = tenant_id
    • line_items[0][price] = price_id, quantity 1

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):

EventEffect
checkout.session.completedUpsert tenant_billing_accounts with customer + subscription ids; status incomplete if subscription id present
customer.subscription.created / updatedUpsert subscription fields, periods, first subscription item id
customer.subscription.deletedSet subscription_status to canceled
invoice.paid / invoice.payment_succeededIf customer maps to a tenant: set billing_invoice_status=paid
invoice.payment_failedIf 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#

  1. Traces: Each successful POST /evidence appends aigov_billing_usage_trace (ledger_tenant_id, run_id, billing_unit, default evidence_event).
  2. Summary: GET /billing/usage-summary — unchanged; aggregates traces for a time window.
  3. Stripe metered push: POST /billing/report-usage (Bearer; optional body { "billing_unit": "evidence_event" }):
    • Resolves the billing window: the subscription current_period_* from tenant_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_reports row per (tenant_id, billing_unit, period_start, period_end). The row freezes what Stripe is told: action=set at one fixed Stripe timestamp for 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 from AIGOV_STRIPE_PRICE_<UNIT>) and AIGOV_STRIPE_SECRET_KEY, posts the usage record and stores stripe_usage_record_id. The subscription's first (licensed contract) item is never used for usage. Without a usage item it stays recorded_local and is sent later if an item and an aligned period appear.

Report states (billing_usage_reports.status) and what the endpoint answers

StateMeaningEndpointWhat happens on the next call
pendingCreated, never sentn/asent
reportedStripe confirmed (or the usage was found at Stripe, reconciled: true) for the current revision200idempotent hit while the counted usage has not grown; a higher count becomes the next revision (pending) and is sent
rejectedStripe refused it (4xx, rate limit, or the connection failed before the request left): nothing was applied502 STRIPE_USAGE_REPORT_REJECTEDsent again, unchanged. Safe.
uncertainOutcome 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_UNCERTAINfirst 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_reviewStripe 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_REVIEWnothing is sent automatically until an operator re-runs or resolves it
resolved_manualAn operator decided it needs no further automatic action (confirmed_at_stripe, invoiced_manually or waived), with name and reason200idempotent hit; recorded, never silent
recorded_localNo Stripe-aligned window or no subscription item200idempotent 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 set at the same timestamp overwrites the same usage record instead of adding another (usage at different timestamps is summed under aggregate_usage = sum, which is why the timestamp is frozen).
  • Every attempt is written to the append-only billing_usage_report_events table before the request leaves, and its outcome after: attempt_started, reported, rejected, ambiguous, reconciled_match, reconciled_overcount, unfinished_attempt, and from migration 0054 revision_created, retry_scheduled, verified_match, verified_undercount, closed_out, escalated, manual_resolved, each with its revision and its actor (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 uncertain until 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 stays uncertain (nothing is double counted, and nothing is lost).
  • The guarantees assume the documented Stripe behaviour: an idempotency key replays the first result, and action=set overwrites 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 n exceeds the row's quantity, the row becomes revision r+1: quantity = n, a new idempotency key aigov-usage-<id>-r<r+1>, status pending, and a revision_created event. It is sent as action=set&quantity=n&timestamp=T: Stripe's one usage record of the period now holds n. Because it is a set at 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 < n makes 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 stays pending and is sent next.
  • reported_quantity is the cumulative usage known to be held by Stripe; quantity - reported_quantity is 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_at is 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:

  1. 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;
  2. close out ended periods (see above);
  3. 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). After AIGOV_BILLING_RECONCILE_MAX_ATTEMPTS unsuccessful passes (default 8, about 4 hours) the report is escalated to needs_review with its reason; every wait is a retry_scheduled event, the escalation an escalated event. An unresolved report is never marked reported without Stripe's own answer or figure confirming it;
  4. 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 set under 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):

MethodPathPurpose
GET/internal/billing/usage-reportsUnresolved 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/:idOne report with its full append-only event trail
POST/internal/billing/usage-reports/:id/rerunForget 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/resolveRecord 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/reconcileRun one pass now
POST/internal/billing/contracts/:tenantAppend 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/:tenantEvery contract version of the tenant and where its usage stands
GET/internal/billing/overviewTenants 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_records and usage_record_summaries were removed in API version 2025-03-31.basil; they remain available only to a request that pins 2025-02-24.acacia or older. The code does not rely on the account's default version: both calls send Stripe-Version: 2025-02-24.acacia (stripe_billing::USAGE_API_VERSION; AIGOV_STRIPE_USAGE_API_VERSION overrides 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 an identifier), which has different semantics (no set, 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 basil the subscription period moved from the subscription to its items; subscription_period reads 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=set overwrites 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.rs is 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 rowResult
status active or pending_legal_acceptance, plan free / developer / internal / trial / pilotallowed without a subscription (the legal gate still applies to pending_legal_acceptance)
status active or pending_legal_acceptance, any other planallowed only with tenant_billing_accounts.subscription_status active or trialing, otherwise 403 BILLING_INACTIVE
status restricted, suspended, deleted or any other value403 TENANT_NOT_ACTIVE, whatever the plan
no registry rowtreated 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/webhook
  • POST /billing/checkout-session
  • GET /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 — whether AIGOV_BILLING_ENFORCEMENT is on for this deployment
  • pro_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 passing price_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#

VariablePurpose
AIGOV_STRIPE_SECRET_KEYStripe API secret for Checkout, portal, invoices, usage records
AIGOV_STRIPE_WEBHOOK_SECRETWebhook signing secret (whsec_…)
AIGOV_STRIPE_PRICE_PRODefault Pro subscription Price for Checkout when price_id omitted
AIGOV_STRIPE_PRICE_TEAMLegacy alias for Pro Price
AIGOV_STRIPE_PRICE_ENTERPRISEMaps subscription items to enterprise entitlements
AIGOV_STRIPE_PRICE_* (metered)Optional unit prices — see stripe_billing.rs
AIGOV_API_KEYS + AIGOV_API_KEYS_JSONAPI keys and ledger tenant ids (required for meaningful multi-tenant billing)
AIGOV_BILLING_ENFORCEMENTOptional subscription gate on hosted billable routes (on by default in staging and prod)
NEXT_PUBLIC_AIGOV_API_BASE_URLDashboard /billing → Rust API (browser)

Local testing with Stripe CLI#

  1. Run Postgres + migrate (sqlx migrate / AIGOV_AUTO_MIGRATE / your deploy process).
  2. Export AIGOV_STRIPE_WEBHOOK_SECRET from stripe listen --forward-to localhost:8088/stripe/webhook.
  3. Trigger test events: stripe trigger customer.subscription.updated (extend payload JSON in Dashboard Send test webhook to include metadata.tenant_id matching a key in AIGOV_API_KEYS_JSON).
  4. Complete Checkout in test mode and confirm tenant_billing_accounts updates.

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 ledger tenant_id (tenant_billing_accounts) only.
  • Checkout and usage APIs call Stripe over the public network; failures return structured JSON errors.
  • rust/src/stripe_billing.rs — DB + Stripe HTTP helpers
  • rust/src/stripe_webhook.rs — verify + persist + dispatch
  • rust/migrations/0014_tenant_stripe_billing.sql — schema

← Back to home