Billing and invoicing
Billing turns the spend the gateway already tracks into invoices you can send to the people who caused it. You create a billing account for a team, an organization or an end user, set a currency, a markup and a tax rate, and the gateway builds invoices from that scope's daily spend per model group. Invoices can be collected by hand or through Stripe, and a Stripe account whose payment fails can be suspended automatically, which blocks its traffic until an admin reinstates it. Billing is an enterprise feature: every /billing route except the Stripe webhook answers 403 without a license that includes the billing feature, and the webhook checks the license per event.
A real-world scenario
An internal platform team runs the gateway for the whole company and charges each department back for its usage plus a 10 percent operating fee. Each department is a team on the gateway. The platform team creates one billing account per team with a 10 percent markup, lets the gateway draft an invoice for every team on the first of each month, checks the drafts on the Billing page, and issues them. For departments billed through Stripe, Stripe emails each issued invoice to the billing email and collects the payment. One department's card is declined after the grace period, Stripe reports the failed payment, and because its account opted into auto-suspend its requests stop until an admin reinstates it.
Bill a team
-
Create the account. In the Admin UI open Settings, then Billing, and click Create Account. Choose Team under Bills a, pick the team, enter a Display name and a Billing email, set Markup (%) to
10, pick Stripe or Manual under Payment provider, turn on Auto-suspend if a failed Stripe payment should block the team after the grace period, and click Create Account. The same step with the API, as a proxy admin:curl -X POST http://localhost:4000/billing/account/new \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"scope_type": "team", "scope_id": "team-nlp", "display_name": "NLP team", "billing_email": "nlp-finance@example.com", "markup_percent": 10, "payment_provider": "stripe", "auto_suspend": true}'Expected result: the account with its generated
account_id,status: "active",currency: "USD",grace_period_days: 7andtax_percent: 0. -
Preview a month before invoicing it. On the Invoices tab click Generate invoice, pick the account and the period, and read the Preview. With the API, the period runs from
period_start(billed) toperiod_end(the first day not billed):curl "http://localhost:4000/billing/usage?account_id=<account_id>&period_start=2026-09-01&period_end=2026-10-01" \-H "Authorization: Bearer $SPANWAY_API_KEY"Expected result: one line item per model group and provider with
requests,prompt_tokens,completion_tokens,spend(provider spend) andamount(what the team owes after markup), and the totalssubtotal,markup_amount,tax_amountandtotal, for example a subtotal of 412.35, a markup of 41.24 and a total of 453.59. -
Generate the draft. Click Generate draft in the dialog, or:
curl -X POST http://localhost:4000/billing/invoice/generate \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"account_id": "<account_id>", "period_start": "2026-09-01", "period_end": "2026-10-01"}'Expected result: a
draftinvoice numbered like3F2A9C10-2026-09-0001, with the same line items and totals as the preview. Nothing is sent yet. -
Issue it. In the invoice row's menu click Issue and confirm, or:
curl -X POST http://localhost:4000/billing/invoice/issue \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"invoice_id": "<invoice_id>"}'Expected result: the invoice is
openwithissued_atset anddue_atseven days later (the account's grace period). For a Stripe account the gateway creates the Stripe customer if needed, creates the invoice in Stripe with the same line items, finalizes it and asks Stripe to send it, so Stripe emails the hosted invoice to the billing email and takes the payment there. It storesstripe_invoice_idandhosted_invoice_url, which the row menu opens with Open in Stripe. For a manual account nothing is emailed, so send the invoice or the CSV yourself. -
Settle it. A Stripe payment arrives through the webhook and marks the invoice
paid. For a manual account, click Mark paid in the row menu after the money arrives, or callPOST /billing/invoice/mark_paidwith theinvoice_id. Download CSV in the row menu (orGET /billing/invoice/export?invoice_id=...) gives the line items as a CSV for the books.
To do step 3 for every account at once, click Generate for all accounts on the Invoices tab, or call POST /billing/invoice/generate_all with the period.
Draft invoices every month on their own
billing_auto_generate_invoices saves someone from remembering to run Generate for all accounts each month. It is off by default. Turn it on under Router Settings, General, or with general_settings.billing_auto_generate_invoices: true in config.yaml. When it is on, at 00:30 UTC on the first day of each month the gateway drafts an invoice for the previous calendar month for every active account with usage that is not already invoiced for it. Drafts are never issued or sent on their own, so you still check and issue them. One instance takes a lock for the job, so it runs once per fleet, and each draft writes an audit row by billing-monthly-job. The job needs the billing license feature and skips with a WARNING when the license no longer has it. When it is off, invoices are only made by hand.
Accounts
Each billed scope has at most one account. The scope must exist when the account is created and cannot change afterwards.
| Field | Default | Meaning |
|---|---|---|
scope_type | required | team, organization or end_user. |
scope_id | required | Id of the team, organization or end user. |
display_name | required | Name on the invoice, up to 200 characters. |
billing_email | none | For a Stripe account, Stripe emails each issued invoice here. For a manual account it is only recorded, nothing is emailed. |
currency | USD | Invoice currency, a three letter code. |
markup_percent | 0 | Added on top of provider spend. |
tax_percent | 0 | Applied after markup. |
payment_provider | manual | manual or stripe. |
grace_period_days | 7 | Days after issue before an invoice is due, and before a failed payment can suspend the account. |
auto_suspend | false | For a Stripe account, suspend automatically when Stripe reports a failed or uncollectible payment more than grace_period_days after the invoice was issued. A manual account is never suspended automatically, suspend it by hand. |
metadata | {} | Free-form data. |
An account's status is active, past_due or suspended. Accounts with a draft or open invoice cannot be deleted. Settled invoices are kept for the books, even after their account is deleted, and no route deletes an invoice, so invoices stay until someone removes them in the database directly.
Invoices
An invoice covers a period from period_start (inclusive) to period_end (exclusive). It has one line item per model group and provider pair, so a model group served by two providers gets two lines. Usage logged without a model group falls back to the model name, and to unknown when neither is known. Each line has requests, successful_requests, failed_requests, prompt_tokens, completion_tokens, spend (provider spend to the micro-dollar) and amount (what the customer owes after markup, in cents). Totals are subtotal, markup_amount, tax_amount and total. The totals are computed and stored as exact decimals to the cent, never as floating point numbers, so 0.10 plus 0.20 is always 0.30, and the API returns them as JSON numbers. Invoice numbers have the form <first 8 characters of the account id>-<YYYY>-<MM>-<sequence>.
An invoice moves through draft, open (issued), and then paid, void or uncollectible. A new invoice is refused when a non-void invoice of the same account already covers any part of the period. Voiding an unpaid invoice (Void in the row menu, or POST /billing/invoice/void) frees its period to be invoiced again.
Endpoints
| Method | Path | Summary |
|---|---|---|
| POST | /billing/account/new | Create a billing account |
| POST | /billing/account/update | Change a billing account |
| DELETE | /billing/account/delete | Delete a billing account |
| GET | /billing/account/info | Show one billing account |
| GET | /billing/account/list | List billing accounts |
| POST | /billing/account/suspend | Suspend a billing account |
| POST | /billing/account/reinstate | Reinstate a billing account |
| GET | /billing/usage | Preview what an invoice would contain |
| POST | /billing/invoice/generate | Generate a draft invoice |
| POST | /billing/invoice/generate_all | Generate draft invoices for every account |
| POST | /billing/invoice/issue | Issue a draft invoice |
| POST | /billing/invoice/mark_paid | Mark an invoice paid |
| POST | /billing/invoice/void | Void an unpaid invoice |
| GET | /billing/invoice/info | Show one invoice |
| GET | /billing/invoice/list | List invoices |
| GET | /billing/invoice/export | Download an invoice as CSV |
| POST | /billing/webhook/stripe | Receive Stripe webhook events |
Stripe setup
| Variable | Purpose |
|---|---|
STRIPE_SECRET_KEY | API key used to create customers and invoices. Unset by default, and then issuing or voiding a Stripe invoice answers 502. |
STRIPE_WEBHOOK_SECRET | Signing secret of the webhook endpoint in Stripe. Unset by default, and then every webhook call answers 400. |
In the Stripe dashboard, add a webhook endpoint pointing at <PROXY_BASE_URL>/billing/webhook/stripe and subscribe it to invoice.paid, invoice.payment_failed, invoice.marked_uncollectible and invoice.voided. See the Stripe webhook documentation for creating the endpoint.
The webhook does not use a Spanway key. The Stripe signature over the raw body is the only authentication, so an unsigned or badly signed request, a signed event whose object is not the shape Stripe sends, or any request when no webhook secret is configured, is rejected with 400. The answer's event is the gateway's own name for what happened: paid, payment_failed, uncollectible or voided for an invoice event, and the Stripe event type for an event it ignores. Signed events for invoices the gateway did not create are acknowledged and ignored, so Stripe stops retrying them. Invoice events need the billing feature, while the checkout, subscription, auto top-up and customer events of Spanway Cloud need the cloud feature, so a Cloud gateway licensed only for cloud still gets its credit purchases and top-ups. A signed event whose feature the license does not include is answered with 403 and is not applied, so Stripe keeps retrying it until the license allows it.
Usage metering
This is separate from the invoices above. A licensed gateway can report how many billable requests it served to Spanway's usage collector, which is how usage-based enterprise licenses are measured. It counts only successful (2xx) requests to the model, MCP and agent routes, and for each one sends the route, the status code, the model id when there is one, the license id and the gateway version. It never sends prompts, responses, keys, user or team names, or IP addresses.
It is off until all three of SPANWAY_BILLING_METRICS_ENDPOINT, SPANWAY_BILLING_METRICS_CLIENT_CERT and SPANWAY_BILLING_METRICS_CLIENT_KEY are set, and your license agreement says whether you need it. When they are set, counts are sent over mutual TLS as OpenTelemetry metrics every 60 seconds. To turn it off, unset the endpoint and restart.
| Variable | Default | What it does |
|---|---|---|
SPANWAY_BILLING_METRICS_ENDPOINT | unset | The collector address. /v1/metrics is added when missing. |
SPANWAY_BILLING_METRICS_CLIENT_CERT | unset | The client certificate, as a file path or the PEM text itself. |
SPANWAY_BILLING_METRICS_CLIENT_KEY | unset | The client key, as a file path or the PEM text itself. Never logged. |
SPANWAY_BILLING_METRICS_CA_CERT | unset | Only for a private collector whose certificate is not publicly trusted. |
SPANWAY_BILLING_METRICS_EXPORT_INTERVAL_MS | 60000 | How often counts are sent, in milliseconds. |
A licensed gateway without the first three logs Enterprise billing metrics disabled: licensed deployment missing config (...) at WARNING once at startup and sends nothing.
Non-payment and suspension
The gateway does not watch due dates on its own. It acts only when Stripe reports a failed payment, either invoice.payment_failed or invoice.marked_uncollectible, which both count as a failed payment. The account then becomes past_due. If the account has auto_suspend on and the invoice was issued more than grace_period_days ago, the account is suspended instead. A manual account never goes past due or suspended by itself, because no payment event arrives for it, so suspend it by hand when it does not pay.
Suspension blocks the billed scope, meaning the team, every team of the organization, or the end user, so its requests are refused. A scope that is already blocked for another reason, for example a team the gateway blocked after a leaked key or an end user an admin blocked, is left as it is, and reinstating never lifts a block billing did not set. A later payment returns a past_due account to active once no other open invoice is overdue, and since a past due account was never blocked, nothing is unblocked. A suspended account stays blocked even after it pays, until an admin clicks Reinstate in the account row's menu or calls POST /billing/account/reinstate. Admins can also suspend by hand with Suspend or POST /billing/account/suspend.
Audit
Every billing change writes an audit row. Account create, update and delete write created, updated and deleted on Spanway_BillingAccountTable, suspending writes blocked, reinstating writes unblocked, and turning past due writes updated. Generating, issuing, marking paid and voiding invoices write created or updated on Spanway_InvoiceTable without the line items, and Download CSV writes exported. An organization suspension also writes blocked and unblocked on Spanway_OrganizationTable, and team and end user blocks write their own rows. Changes a Stripe event caused are recorded as made by stripe-webhook, and drafts the monthly job made by billing-monthly-job, so you can tell them apart from an admin's.
Errors
| Status | Route | Meaning | Fix |
|---|---|---|---|
403 The 'billing' feature needs a Spanway enterprise license. ... or Your Spanway license does not include the 'billing' feature. Contact sales@spanway.ai to add it. | every /billing route | The license does not include billing. | Add a license with billing. The Billing page shows Billing needs a Spanway Enterprise license. |
403 Only proxy admins can change this resource or Only proxy admins can read this resource. | write routes, read routes | The key is not a proxy admin (reads also allow admin viewers). | Use a proxy admin key. |
404 account_id=<id> not found or invoice_id=<id> not found. | every route that takes an account or invoice id | No account or invoice has that id. | Check the id with GET /billing/account/list or GET /billing/invoice/list. |
404 team team-nlp not found. | /billing/account/new | The scope does not exist. | Create the team, organization or end user first. |
409 team team-nlp already has billing account .... | /billing/account/new | The scope already has an account. | Use /billing/account/update on the existing account. |
400 nothing to update. | /billing/account/update | The body carried only account_id. | Send at least one field to change. |
| 400 saying the account has a draft or open invoice. | /billing/account/delete | Unsettled invoices block deletion. | Void or settle them first. |
400 account ... is already suspended or already active. | /billing/account/suspend, /billing/account/reinstate | The account is already in that state. | Nothing to do. |
409 invoice ... already covers 2026-09-01 to 2026-10-01. | /billing/invoice/generate | A non-void invoice overlaps the period. | Void it, or pick another period. The Admin UI shows Could not generate the invoice with this reason. |
400 invoice <number> is <status>, only draft can be issued (or open/uncollectible can be marked paid, and so on). | /billing/invoice/issue, mark_paid, void | The invoice is not in a status that allows the action. | Check status with GET /billing/invoice/info. |
422 period_end must be after period_start. | /billing/usage, /billing/invoice/generate, /billing/invoice/generate_all | period_end is not after period_start. | Use a half-open period such as 2026-09-01 to 2026-10-01. |
502 stripe: .... | /billing/invoice/issue, /billing/invoice/void | Stripe refused the call, for example because STRIPE_SECRET_KEY is wrong. | Fix the key or the Stripe account and retry. |
400 Stripe-Signature header missing, invalid Stripe signature, payload is not a Stripe event or STRIPE_WEBHOOK_SECRET is not set. | webhook | The signature is missing or wrong, the event is malformed, or the secret is not set. | Set the secret from the Stripe endpoint and make sure Stripe calls the right URL. |
403 naming the billing or cloud feature. | webhook | A signed event needs a license feature this gateway lacks. Stripe retries it. | Add the feature to the license. |
500 DB not connected. This endpoint needs a database; .... | every route | The gateway has no database. | Set DATABASE_URL. |
Logs
| Level | Line | Meaning |
|---|---|---|
| WARNING | billing: stripe invoice <id> is not ours | Stripe sent an event for an invoice this gateway did not create, for example one made by hand in Stripe. The event is acknowledged and ignored. Normal when the Stripe account is shared. |
| WARNING | billing: the license does not include billing, skipping monthly invoices | billing_auto_generate_invoices is on but the license lost the billing feature, so no drafts were made. Renew the license or turn the setting off. |
| INFO | billing: another pod is generating this month's invoices, skipping | Another replica holds the monthly job lock. Normal with several replicas. |
| INFO | billing: generated <n> draft invoices, skipped <n> accounts | The monthly job finished. Skipped accounts had no usage or were already invoiced. Normal. |
Related
- Billing page for every control of the Admin UI.
- Cost tracking for how the daily spend that invoices are built from is recorded.
- Spend reports for totals without invoicing.
- End users for the customers an account can bill.
- Spanway Cloud for the Cloud events that share the Stripe webhook.
- Enterprise for the license features.