These routes live in allternit-cloud-api (cmd/allternit-cloud-api) and are served at https://api.allternit.com. The web app’s client is src/lib/billing.ts in allternit-ai. Every authenticated route takes a Clerk session or an Allternit API key (alt_…, created under ACI › Operator keys; legacy allternit_* tokens still work) with the billing scope. Routes that call Stripe answer 503 {"error":"billing_not_configured"} when STRIPE_SECRET_KEY is unset, and 502 {"error":"billing_upstream_error"} when Stripe rejects the call.

Computers

Agents need a computer. Credit computers are started and stopped with POST /api/v1/provisioned-instances/credit and /credit/stop, billed per minute from the wallet. Free hosted computers are retired: POST /api/v1/provisioned-instances/free answers 410 free_computers_retired. See Computer pricing and Account compute status.

Credit packs

The pack Checkout Session is created for the person’s Stripe customer (created on first use with Idempotency-Key: customer-{user_id} and linked in user_billing_accounts) with payment_intent_data[setup_future_usage]=off_session, so the card is saved for auto top-up. If the customer can’t be created the pack still sells, without saving the card. The PaymentIntent behind the session carries the same metadata as the session (clerk_user_id, allternit_credits_usd, allternit_org_id when present) plus kind=credit_pack, so a chargeback on the payment can be traced to the person. Pack grants still come from the Checkout Session. return_url must be an https page on an allowed Allternit host with no query or fragment. The server adds ?checkout=success or ?checkout=cancelled.

Credit balance and Cloud models

cloud_models says whether the account can run Allternit Cloud models now. GET /api/v1/me/usage carries the same object, from the same server function. Clients lock a Cloud model row only when allowed is false and the row’s provider (from GET /v1/models) is not in byok_providers. A response with no cloud_models field means not locked, so older servers lock nothing. There is no free monthly allowance, and free_inference is no longer returned. On GET /api/v1/me/usage, a Free account with no credits row reports credits: 0 and a weekly limit and usage of 0.

Auto top-up

GET response:
status is ok, pending (a charge is in flight), failed (the last charge failed and auto top-up was turned off; see last_error) or disabled. card is null when no card is saved. When no card is stored but the person has a Stripe customer, GET picks up the newest card on it. PUT body:
Rules: threshold_usd at least 5, amount_usd one of the pack sizes, monthly_cap_usd at least the amount and at most 5000. Turning it on without a saved card answers 409 {"error":"auto_topup_no_card"}. While a chargeback is open, or after one was lost, turning it on answers 409 {"error":"auto_topup_dispute"}. New buyers get the same first-purchase limit as packs (403) until their first payment settles. The response is the GET shape. If the balance is already under the new threshold, a top-up starts right away.

Turning charges on

Auto top-up charges nothing until AUTO_TOPUP_LIVE=1 (or true / on) is set on cloud-api. Set it only after the live Stripe webhook endpoint sends the payment_intent.* events listed below; otherwise a successful charge would never grant its credits. While the switch is off, GET /api/v1/billing/auto-topup returns configured: false (the settings card shows auto top-up as unavailable), turning it on answers 503 billing_not_configured, and debits start no check. Saving a card still works.

The trigger

After every wallet debit (CostService::deduct_credits_for_usage, used by inference settlement and hosted-runtime session billing) cloud-api spawns a check, so the request path never waits on Stripe. A charge starts when all of these hold:
  • auto top-up is on and a card and customer are stored,
  • the balance after the debit is under the threshold,
  • no attempt is pending (a pending attempt older than 24 hours no longer counts),
  • this month’s successful top-ups plus the amount are within the monthly cap.
An attempt row is claimed first in billing_auto_topup_attempts (a partial unique index allows one pending attempt per person), then cloud-api creates a PaymentIntent with off_session=true, confirm=true, Idempotency-Key: autotopup-{user_id}-{attempt_id} and metadata kind=auto_topup, clerk_user_id, allternit_credits_usd, allternit_auto_topup_attempt. A decline, authentication_required or requires_action in the API answer marks the attempt failed, turns auto top-up off, stores the reason, and notifies the person (web push plus the auto_topup_failed customer email). A requires_action intent is canceled.

Paying inside the app

Web, Desktop and the phone web app can take payment without leaving Allternit. iPhone and Android buy through the stores instead (see Store purchases). Billing and usage replies in this section use snake_case keys.

Billing config

GET /api/v1/billing/config tells a client how to load Stripe.
mode is test or live, read from the key. The route answers the same billing_not_configured error as the other billing routes when STRIPE_PUBLISHABLE_KEY is missing, malformed, or in a different mode from STRIPE_SECRET_KEY. Set both keys in the same mode. Only card and link are offered.

Embedded checkout

POST /api/v1/billing/checkout (credit packs) and POST /api/v1/billing/subscribe (plans) take an optional ui_mode: Any other ui_mode value is rejected (422 from request parsing). An embedded session has a return_url and redirect_on_completion of if_required, and no success or cancel URL. The customer is always the signed-in account’s own Stripe customer; a customer field in the body is ignored.

Change, cancel and resume a plan

These routes change a card-paid (Stripe) plan inside the app. They need a Clerk session or a billing scoped API token. No request names a customer or subscription; both come from the session, and a subscription that is not the caller’s answers 404 like a missing one. Preview reply:
amount_due_usd is the next invoice with prorations included. effective is now for an upgrade and period_end for a downgrade. Send proration_date back to /change so the charge matches the preview; one older than an hour answers 409 preview_expired. /change, /cancel and /resume reply with the plan as it stands:
A downgrade fills pending_plan_id and pending_at; the current plan stays until then. Choosing the current plan while a downgrade is pending undoes it. Cancel drops a pending downgrade first.

Payment methods

Errors: 404 payment_method_not_found for a method that is not on the account. 409 default_payment_method_in_use when removing the card an active plan is billed to; make another card the default first. A backup card is never charged on its own.

Invoices

GET /api/v1/billing/invoices?limit=&cursor= lists the account’s Stripe invoices.
cursor is null on the last page; pass it back as cursor for the next. pdf_url is null when Stripe has no PDF.

Embedded auto top-up card

POST /api/v1/billing/auto-topup/setup?ui_mode=embedded returns { "client_secret", "setup_intent_id" } instead of a checkout URL. After Stripe confirms the card in the page, the client calls POST /api/v1/billing/auto-topup/setup/confirm with the setup intent id. Errors: setup_intent_not_found (not this account’s), setup_not_finished (the card was not confirmed) and auto_topup_card_unsupported (auto top-up needs a card or Link). Any ui_mode other than embedded or hosted is 400.

Webhook events

Stripe posts to POST /api/v1/webhooks/stripe (signed with STRIPE_WEBHOOK_SECRET). Auto top-up adds these events to the ones plans and packs already use: Payment intents without kind = auto_topup are acknowledged and ignored; pack purchases grant from their Checkout Session. Add the three payment_intent.* events to the Stripe webhook endpoint’s event list.

Disputes

A chargeback takes the disputed credits back out of the cloud wallet until Stripe decides the case. A dispute that cannot be traced to a person is recorded with status unmatched and answered 200, so Stripe does not retry it forever; the ops alert asks the team to look it up in Stripe. Both events also use the webhook_events dedupe, so a Stripe retry changes nothing. If the disputed pack named an organization and its credits went to that org’s fabric ledger, the hold still lands on the person’s cloud wallet; the ops alert says so, and the org ledger is corrected by hand. The live Stripe webhook endpoint must subscribe to charge.dispute.created and charge.dispute.closed. Without them, chargebacks leave the credits in place.

Store purchases (Apple and Google)

Status: AVAILABLE (dark until configured). The same plans and credit packs can be bought in the iPhone app (Apple In-App Purchase) and in the Play app (Google Play Billing). Store prices are higher than web prices; the credits are the same. Setup and secrets are in Store billing. Until a store’s secrets are set, that store’s store.enabled is false and its routes answer 503. The server never trusts the client. A client sends a transaction id (Apple) or a purchase token (Google); the server reads the purchase from the App Store Server API or the Play Developer API, grants credits once, and stores the result. Store notifications are only a prompt to look again.

Routes

All routes live under /api/v1/billing/store/. The first three authenticated routes need a signed-in account with the billing scope. The notification routes are unauthenticated and re-fetch from the store. Call preflight before every purchase. It checks that the store is on, that the account has no other open plan, and the first-purchase limit, then returns the product id to buy and the account’s account_token. iPhone passes the token to StoreKit as appAccountToken. The token is the same on every call for one account. Purchase answer (both purchase routes):
subscription appears for plans, balance_usd for packs. idempotent_replay: true means this transaction was granted before and nothing was added this time. When nothing is granted, granted is false and the answer carries reason (and sometimes message): sandbox_not_granted, refunded, unknown_account, account_closed for Apple, or unclaimed for a Google notification nobody has claimed yet. Clients must not consume a Play pack on the device; the server consumes it after the grant.

Errors

Every error is { "error": "<code>", "message": "..." }. Notification routes answer 200 with handled: false for a notification that cannot be applied (unknown account, unsupported type), so the store stops retrying. They answer 5xx only for failures worth retrying.

Additive fields on existing routes

All additions are optional for old clients.
  • GET /billing/plans and GET /billing/packs: each item gains store:
    enabled is true only when that store’s secrets are set. reference_price_usd is the intended store price for reference; clients show the store’s own localized price, not this number.
  • GET /billing/subscription: adds billing_provider (stripe, apple, google or null on Free), manage_url (where to change or cancel) and conflict (true when the account has more than one open plan). For an Apple or Google plan whose period end has passed, this route first re-reads the plan from the store, at most once per 10 minutes per plan, so a missed notification heals itself.
  • POST /billing/subscribe: the existing 409 already_subscribed now also carries billing_provider and manage_url.
  • POST /billing/portal: answers 409 store_billed (with current_plan_id, billing_provider, manage_url) when the plan is billed by Apple or Google. The Stripe portal cannot manage it.

Products

Store prices are set in App Store Connect and Play Console. Credits are the same as web. Plan credits use the same rollover cap as Stripe plans. Each renewal grants once, keyed by the store transaction. A store plan sets the same plan tier as a Stripe plan and suspends a cloud computer the same way when it goes unpaid or is canceled.

Plan states

Apple grace period and Google grace map to past_due (access stays). Grace expired or on hold maps to unpaid (default tier, cloud computer stopped). Expired maps to canceled. A change inside the Apple subscription group, or a Play replacement purchase, updates the same plan.

Sandbox rule

Sandbox and test purchases reach the production server. A sandbox purchase grants credits and a plan only for accounts listed in STORE_SANDBOX_GRANT_USER_IDS (the App Review demo account and the internal test account). For anyone else the purchase is recorded and answers granted: false, reason: "sandbox_not_granted", message: "Test purchase. No credits were added.".

Refunds

An Apple REFUND or REVOKE, or a Google voided purchase, writes a negative ledger entry for the credits granted from that transaction, once. A refunded plan drops to the default tier. If the store later reverses the refund (Apple REFUND_REVERSED), the credits are given back once. A refund recorded for a transaction that never granted anything takes nothing; if that refund is later reversed, the transaction goes back to pending and the grant that follows adds its credits. The balance can go negative when the credits were already spent, as with Stripe disputes.

Double billing

An account never needs two plans. Preflight and POST /billing/subscribe answer 409 already_subscribed when any plan is open, naming who bills it. A change inside the same store (for example Plus to Max on Apple) is allowed. If two plans exist anyway, for example a purchase made on the device without preflight, the server records both, grants what was paid, sets conflict: true on GET /billing/subscription, and alerts the team. Clients then show “You have two plans. Cancel one.”

Tables

Migration 103_auto_topup.sql:
  • billing_auto_topup: one row per person (settings, stripe_customer_id, stripe_payment_method_id, card_brand, card_last4, status, last_attempt_at, last_error, month_spent_usd, month_key).
  • billing_auto_topup_attempts: one row per charge (payment_intent_id unique, amount_usd, status of pending, succeeded or failed).
  • customer_emails.kind gains auto_topup_failed.
Migration 106_billing_disputes.sql:
  • billing_disputes: one row per Stripe dispute (stripe_dispute_id, user_id or null when unmatched, charge, PaymentIntent and customer ids, amount_cents, held_usd, hold_transaction_id, release_transaction_id, status of open, unmatched, won, lost or closed).
Migration 148_store_billing.sql (see Store billing):
  • billing_subscriptions gains provider, store_product_id, store_environment, store_checked_at and store_purchase_token.
  • billing_store_accounts: one store account token per person.
  • billing_store_transactions: the store ledger, one row per store transaction.

Plans

Freeweights perk listing

GET /api/v1/billing/plans also returns a top-level freeweights block. It lists the Freeweights perks for each plan, so a plan page can show them before they are sold:
status is offered only while FREEWEIGHTS_PERKS_ENABLED is on. Otherwise it is not_offered: the perks are listed, but no account gets them and the entitlement claim’s perks stays empty. Purchase surfaces show nothing while the status is not_offered. Each line has a key, a label, a value and a unit (bytes, count or bool). Bytes are decimal (1 GB = 1,000,000,000 bytes). The current values are a draft that still needs sign-off: The same table feeds the entitlement claim once perks are on. FREEWEIGHTS_PLAN_PERKS replaces it (see Configuration below).

Freeweights entitlement

Freeweights signs people in with their Allternit account and never stores a plan, perk or price. Its Worker asks this route for a short signed claim instead. The contract is spec/accounts-v1.md section 3 in the freeweights repo. The JWS header is {"alg":"EdDSA","typ":"JWT","kid":"entitlement-v1"} (Ed25519). The payload: Errors: no credential is 401. A missing or unreadable signing key is 503 with {"error":"accounts_not_configured"}, which the Worker reads as accounts not being set up yet. A failed plan read or a failed Clerk org read is 503 with {"error":"entitlement_unavailable"} and Retry-After: 60. The rest of the API keeps working without the key. Browsers on https://freeweights.allternit.com and https://fw-preview.allternit.com may call this route and GET /api/v1/billing/plans. Those origins get no CORS access to any other route.

Configuration

Freeweights key scopes

POST /api/v1/api-keys accepts three Freeweights scopes and refuses any other name that starts with freeweights. with 400: The user guide is Credits and auto top-up.