Die Software-Standardeinstellung ist No subscriptions (
access_model = off, default_token_quota = 0 bedeutet unbegrenzt). Neue Installationen und bestehende Self-Hosts starten dort. Keine Billing-UI wird angezeigt, bis ein Admin eine Stripe-Einstellung wählt.What you get
- Three access postures: no subscriptions, included + paid, or paid only
- Stripe-hosted Checkout — users upgrade without your code ever touching card data
- Customer Portal — users update payment methods, download invoices, cancel — all on Stripe’s UI
- Webhook-driven lifecycle — subscriptions provision and renew automatically; canceled paid users return to the included tier (or become unentitled in paid-only) at period end
- Quota enforcement — token usage recorded in an append-only ledger and summed per period; mid-stream cutoff with a structured upgrade prompt
- Admin pages for plan CRUD and subscription monitoring
Voraussetzungen
- Stripe-Konto mit aktiviertem Live-Modus. Unternehmen mit Sitz in Singapur müssen KYC abschließen (Business UEN, Ausweis des Geschäftsführers, Bankkonto). Die Genehmigung dauert normalerweise 1–3 Tage.
- Stripe Live API-Schlüssel vom Typ Restricted (empfohlen gegenüber Standard
sk_live_***— einfacher zu widerrufen, begrenzte Berechtigungen). - Webhook-Endpunkt öffentlich erreichbar unter
<your-domain>/api/webhooks/stripe. - Bankkonto für Auszahlungen. Multi-Währungs-Abrechnung (z. B. USD-Auszahlung auf ein USD-Konto) wird für Stripe-Konten ohne USD-Standard empfohlen, um 1,5–2 % Devisenverluste pro Transaktion zu vermeiden.
Einrichtung
1. Stripe Dashboard
Pro-Produkt erstellen
- Catalog → Products → + Add product
- Name:
Pro, description:5M tokens / month, priority support - Pricing: Recurring, monthly, $20.00 USD (adjust to your pricing strategy)
- Save → copy the resulting
price_***ID (you will UPDATE the localbilling_planstable with this value after activation)
Erstellen Sie einen eingeschränkten API-Schlüssel
- Developers → API keys → + Create restricted key
- Name:
fim-one production - Permissions (minimum):
- Customers: Write
- Subscriptions: Write
- Checkout Sessions: Write
- Customer portal: Write
- Prices: Read
- Products: Read
- Save → copy
rk_live_***
Webhook-Endpunkt registrieren
- Developers → Webhooks → + Add endpoint
- URL:
https://<your-domain>/api/webhooks/stripe - Zu empfangende Events:
checkout.session.completedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
- Nach dem Speichern auf “Reveal signing secret” klicken →
whsec_***kopieren
Multi-Währungs-Abrechnung konfigurieren (empfohlen)
Wenn sich die Standardwährung Ihres Stripe-Kontos von der Preiswahrung unterscheidet, die Sie berechnen (häufiger Fall: SGD-Konto mit USD-Abrechnung):- Settings → Bank accounts and currencies → Add a settlement currency
- Wählen Sie die Preiswahrung (z. B. USD)
- Fügen Sie das entsprechende Bankkonto an (z. B. ein Aspire USD Virtual Account)
- Speichern — Stripe leitet USD-Gebühren direkt zu USD-Auszahlungen weiter, ohne Devisenumrechnung
2. Backend .env
Legen Sie diese drei Schlüssel in Ihrer Produktions-.env fest:
.env neu, damit die Schlüssel übernommen werden:
3. In Admin aktivieren
- Melden Sie sich als Admin an
- Admin → System Settings → Access and billing
- Wählen Sie eine Posture aus (die Instanz befindet sich immer in genau einer):
- No subscriptions (Software-Standard) — Stripe wird nicht verwendet. Token-Zugriff ist das Standard-Monatskontingent (
0= unbegrenzt). - Included + paid — Stripe erforderlich. Neue Benutzer landen auf dem Included-Tier; sie können upgraden. Stornierte bezahlte Benutzer kehren am Ende des Abrechnungszeitraums zum Included-Tier zurück.
- Paid only — Stripe erforderlich. Kein Included-Tier. Benutzer müssen sich abonnieren, bevor sie Modelle aufrufen können. Bestehende Benutzer des Included-Tiers behalten ihr Kontingent, wenn Sie von Included + paid wechseln.
- No subscriptions (Software-Standard) — Stripe wird nicht verwendet. Token-Zugriff ist das Standard-Monatskontingent (
- Das Backend validiert, dass sowohl
STRIPE_SECRET_KEYals auchSTRIPE_WEBHOOK_SECRETvorhanden sind, wenn Sie eine Stripe-Posture wählen — wenn einer fehlt, wird 400 zurückgegeben - Bei der ersten Aktivierung einer Stripe-Posture führt das Backend ein idempotentes Setup durch:
- Included + paid: erstellt den Included-Plan (
slug=free) + eine Pro-Vorlage mit einer leeren Price ID; setztdefault_plan_id; füllt Benutzer ohne Plan auf - Paid only: erstellt nur die Pro-Vorlage; führt keine Auffüllung durch
- Kopiert
default_token_quotaauf den Included-Plan, wenn dieser Plan erstellt wird (0bleibt0, unbegrenzt)
- Included + paid: erstellt den Included-Plan (
- Das Zurückschalten auf No subscriptions ist ein reines Flag-Flip ohne Datennebenwirkungen. Der Standard-Included-Plan kann nicht gelöscht werden, während Included + paid aktiv ist.
4. Aktualisieren Sie den Pro-Plan mit Ihrem Live-Preis
Nach der Aktivierung aktualisieren Sie den vordefinierten Pro-Plan, um auf Ihren Live-Stripe-Preis zu verweisen:- Admin → Billing → Plans → Pro → Edit
- Fügen Sie Ihre
price_1***(aus Schritt 1) inStripe Price IDein - Speichern
5. Smoke-Test
- Öffnen Sie
/settings?tab=billingals normaler Benutzer - Klicken Sie auf Switch to Pro
- Stripe Checkout wird geöffnet; füllen Sie es mit einer echten Karte mit niedrigem Betrag aus (erstatten Sie danach)
- Webhook sollte ausgelöst werden — überprüfen Sie im Stripe Dashboard → Webhooks → aktuelle Ereignisse zeigen 2xx-Antworten
- Abonnementzeile erscheint in der Tabelle
subscriptions;users.plan_idwechselt zupro - Die Benutzeroberfläche zeigt jetzt Pro-Plan + Schaltfläche „Manage subscription”
Abrechnung deaktivieren
Schalten Sie den Schalter Enable Stripe Billing in Admin → System Settings → Billing AUS. Wenn deaktiviert:- Alle
/api/billing/*-Endpunkte geben 503 zurück - Der Webhook-Endpunkt gibt 503 zurück (Stripe wird erneut versuchen und dann im Dashboard als fehlgeschlagen angezeigt — das ist in Ordnung, Sie können den Webhook stattdessen im Stripe Dashboard deaktivieren, wenn die Abrechnung dauerhaft ausgeschaltet ist)
- Die Registerkarte Plan & Billing für Benutzer verschwindet
- Die Navigationsgruppe Admin → Billing ist ausgeblendet
- Die Quota-Kette überspringt die Plan-Stufe und fällt direkt auf
default_token_quotazurück
subscriptions-, billing_plans- und users.plan_id-Zeilen bleiben unverändert. Das erneute Aktivieren wird vom gleichen Status aus fortgesetzt, ohne dass eine Migration erforderlich ist.
Berechnungsreferenz — Kontingent- und Token-Mathematik
Dies ist die autoritative Referenz für jede numerische Regel, die entscheidet, was ein Benutzer verbrauchen darf, wann sein Zähler zurückgesetzt wird und wie die Auflösungskette zusammengesetzt wird. Lesen Sie dies, bevor Sie Preise ändern, Kontingente anpassen, Nutzungs-Dashboards erstellen oder v2/v3-Arbeiten planen. Zukünftige, aber noch nicht ausgelieferte Regeln sind in ihrem reservierten Slot dokumentiert, damit Mitwirkende wissen, wo neue Logik eingebunden wird.Glossary
What counts as a token
Token consumption is metered in the model client, from the provider’susage object on every call, and written to the usage ledger (usage_ledger): an append-only table with one row per turn, run or request and model. A user’s “used” is the sum of their ledger rows since their window began. The quota check, the Usage card in Settings, Admin → Users and the user export all read that sum. The token figures of the platform statistics (Admin → Overview, Analytics, the metrics API) and of each user’s dashboard are read from the same ledger, by the time the usage was recorded; the evaluation center’s tokens consumed is the one figure still summed from the evaluation runs.
- Counted: prompt tokens + completion tokens of every model call made on the user’s account (the provider’s own
total_tokenswhen it reports one) - Counted: every model call of a chat turn, not only the answer: the agent’s tool rounds, routing in Auto mode, domain classification, step titles, context compaction, follow-up suggestions, the conversation title, and the calls of an agent the turn delegated to with
call_agent - Counted: a turn that was stopped or abandoned and a turn that failed, for what they consumed up to that point. When the provider sends no usage for a call (a stream cut short, or a provider that reports none), the call is estimated and its row is marked
estimated. The estimate counts the messages sent, the tool calls in their history, the tool definitions sent with the call, a fixed 1,100 tokens per image, and the text, reasoning and tool-call arguments that had come back, and is rounded up. Against OpenAI’so200k_basetokenizer it comes within about 10% on a tool-heavy agent call, and between 0.8 and 1.5 times the real count on English, Chinese, Japanese, Korean, Russian, Greek, Arabic, Hebrew, Thai and Hindi text, code, JSON, emoji, base64, hex, random identifiers and whitespace - Counted: a chat request sent without a
conversation_id - Counted: workflow runs, against whoever ran them; a run started by a trigger key or a schedule counts against the workflow’s author. Single-step tests count too
- Counted: the model-backed helper endpoints (AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat), evaluation runs (the agent and the grader), and the vision model reading images and scanned pages while a document is added to a knowledge base
- Over quota or without a plan: adding a document to a knowledge base is not refused, but the document is read without the vision model (text only: no reading of images or scanned pages), the server logs it, and the document shows a warning with the reason; retrying the document once the quota allows reads it with the vision model
- Not counted: embedding, reranking and image generation requests
- Counted: a model call that had been sent but had returned nothing yet when its turn was stopped or abandoned (a call still waiting for its response, a stream before its first chunk, or a tool-call round whose arguments the model was still writing). The provider bills what it was sent, so the prompt is recorded, estimated, plus any tool-call arguments already received; the row is marked
estimated. The client cannot tell whether the request had reached the provider: a turn stopped while the call is still connecting is counted the same way, though the provider received nothing. During a provider outage, a user who presses Stop is therefore charged the prompt, and one who waits for the error is not - Not counted: requests that fail before reaching the provider (auth error, rate-limit pre-check, a call still waiting for the local rate limiter), and a call the provider refused or that broke on an error before its first chunk
- Cached input: counted at full price (no provider cache discount is applied). The ledger records cache-read and cache-creation tokens per row for later use.
source_type (conversation, workflow_run, eval_run or endpoint) with the id, entry (chat, dag, auto, background, a run mode such as trigger or schedule, ai_assist.*, kb_chat, db_chat, kb_ingest, eval), the model, and the organization of the agent, workflow, connector or knowledge base it ran through. conversations.total_tokens and workflow_runs.total_tokens are still kept as “what this conversation / this run reported” and can be lower than the ledger, which also holds interrupted turns, delegated agents and the streamed answer.
Rows are written when a turn, run or request ends, however it ends; a long one is also written as it goes, at most every 30 seconds. If the server process is killed, what its in-flight turns consumed in the last 30 seconds at most is not recorded. A write that fails is retried once and then logged at ERROR with the user and the numbers (Usage not recorded), and the turn is not failed for it.
Upgrading to the release that adds the ledger. The migration carries every conversation’s and run’s total_tokens into the ledger, so each user’s “used” is the same before and after. It then compares the result per user with the source tables once. If an instance of the previous release is still serving and changed a total while the migration ran, each user that differs is carried over again and compared in a single transaction (one snapshot on PostgreSQL), so a writer that keeps running does not stop the migration from finishing. The migration fails only if a user’s carry-over does not match the sources it read, which points to a fault, not to a running writer; it resumes where it was when run again. What an old instance writes after that has no ledger row: for a user who was carried over again, what was committed after their carry-over began; for everyone else, what was committed after the comparison, and everything written once the migration has finished. Once the last old instance has stopped, run the top-up command described in the next paragraph.
After rolling back and upgrading again. A release older than the ledger keeps adding to conversations.total_tokens and workflow_runs.total_tokens without writing ledger rows. If you roll back to one and later upgrade again, run python -m fim_one.core.usage.topup (with the application’s DATABASE_URL) to see what the ledger is missing, and again with --apply to record it: one adjustment row per conversation or run whose ledger rows add up to less than its total. It only adds rows, and a second run finds nothing left. The added usage counts in the window in which the command is run. Run it with the application stopped: against a live one it can count a turn twice whose conversation total was saved a moment before its ledger rows. It compares sums per conversation or run, so where the ledger already holds usage the total never reported (an interrupted turn, a delegated agent), that much of a gap is not recovered: a conversation reporting 180 whose rows add up to 170, 20 of them a delegated agent’s, is missing 30 and gets 10.
Three-state override semantics
users.token_quota ist die administrative Überschreibung pro Benutzer. Sie hat drei Bedeutungen in einer Spalte:
Die Überschreibung hat immer Vorrang vor Plan und Standard. Sie existiert, damit Admins einzelne Benutzer über oder unter ihrem Plan-Tier positionieren können, ohne Stripe zu berühren.
Quota resolution chain — v1 (current)
For any authenticated request, the cap is computed top-down — first match wins:default_token_quota is 0.
Period reset
- “Used” is not a counter that is reset: it is the sum of the user’s ledger rows from the start of their current window. A new window starts with nothing in it.
- For paid users the window is the subscription period: it starts on the monthly anniversary of the subscription and ends at
Subscription.current_period_end(mirrored onusers.quota_reset_at), which theinvoice.payment_succeededwebhook advances on each renewal. - For users without a Stripe subscription the window is the calendar month (UTC).
- Plan changes mid-period do not start a new window, only renewals do. This prevents quota-cycling exploits (“subscribe → use Pro quota → cancel → subscribe again”).
Mid-stream enforcement
- Pre-flight check at chat-call entry: cheapest path, blocks requests the user can’t afford to start.
- While an answer streams, the turn compares what the user had used when it started, plus what the turn itself has consumed so far (the calls that have finished, and an estimate of the answer being written), with the cap, about every 200 characters. No database query is made for this. Crossing the cap closes the stream with a structured terminator frame, not a network error. Usage from the same user’s other tabs during the turn is seen by the next turn’s pre-flight check.
- The frontend interprets the terminator and surfaces
<QuotaExceededDialog>with a deep link to/settings?tab=billing. - An evaluation run and a workflow batch are admitted once, and checked again the same way before each case or item starts: what the user had used when the run or batch started plus what it has consumed since (for an evaluation, its own meter; for a batch, the totals of the items that have finished). Once the cap is reached no further case or item starts; those under way finish. The evaluation run ends
failedwithtoken_quota_exceededand the number of cases not run in its error; each batch item not started isfailedwithtoken_quota_exceeded. A single workflow run is checked only when it starts (and when it continues after waiting for a decision). - A request made when the quota is already used up is refused before any stream starts: HTTP
429witherror_codetoken_quota_exceeded. Under Paid only, a user with no plan gets HTTP402witherror_codesubscription_required. - The same pre-flight check guards the other endpoints that call a model: AI-assisted agent and connector create and refine, connector action generation, database chat and schema annotation, knowledge-base chat, starting an eval run, and every way of starting a workflow. What they consume counts against the quota like a chat turn does.
Billing-deaktiviert-Fallback
Wennsystem_settings.billing_enabled = FALSE:
- Schritt 2 der Kette wird übersprungen — die Kette reduziert sich auf
override → default → unlimited. /api/billing/*und/api/webhooks/stripegeben503zurück.- Die Registerkarte
Plan & Billingfür Benutzer und die Admin → Billing-Navigationsgruppe sind ausgeblendet. - Alle Abrechnungsdaten (Abonnements, Pläne,
users.plan_id) bleiben erhalten — das erneute Aktivieren setzt den gleichen Status fort, ohne Migration erforderlich zu sein.
Reserviert: quota chain v2 — Team-Plätze
Noch nicht ausgeliefert. Hier dokumentiert, damit die v2-Arbeit einen bekannten Landeplatz hat.
Subscription.quantityführt die Platzanzahl (Stripe-nativ).- Der effektive Plan eines Benutzers wird durch Team-Mitgliedschaft aufgelöst, bevor auf seinen persönlichen Plan zurückgegriffen wird:
- Quota ist pro Platz (jedes Team-Mitglied erhält ein vollständiges
monthly_token_quota), nicht ein gemeinsamer Pool. Gemeinsame Pools führen zu First-Come-First-Served-Erschöpfung und sind kundenfeindlich. - Override-Semantik bleibt unverändert — Team-Administratoren können einzelne Mitglieder weiterhin hart begrenzen über
users.token_quota = N, was in der Kette über dem Team-Plan liegt.
Reserved: quota chain v3 — native Org allocation (no Stripe)
Noch nicht veröffentlicht. Reserviert für On-Prem- / Enterprise-Deployments, die Kontingente intern zuweisen, ohne pro Benutzer über Stripe zu bezahlen.
- Neue Tabelle
org_quota_allocations(user_id, monthly_token_quota, org_id)verteilt ein übergeordnetes Budget auf Mitglieder. - Zuweisungen sind pro Benutzer, kein gemeinsamer Pool — jedes Mitglied hat ein klares individuelles SLA.
- Aktualisierte Chain:
max(), nichtsum(). Ein bezahlter Pro-Benutzer erhält nie weniger als das, wofür er bezahlt hat, auch wenn sein Org-Administrator eine niedrige Zuweisung festlegt. Das über Stripe bezahlte Kontingent ist unverletzlich.
Reserviert: Pay-per-use-Gutschriftsaldo (v3 separate Dimension)
Noch nicht ausgeliefert. Eine separate Achse vom obigen Schema — Gutschriften sind eine einmalige Aufstockung, keine Abonnement-Stufe.
- Neue Tabelle
user_credits(user_id, balance_cents, currency)— finanziert über Stripe Checkoutmode='payment'. - Verbrauchsreihenfolge: Abonnement-Kontingent zuerst, dann Gutschriftsaldo (nur nach Erschöpfung des Abonnements beginnt die Gutschrift zu sinken).
- Gutschriftsaldo ist nicht erstattbar (Industriestandard für Prepaid).
- UI zeigt beide Balken:
Subscription quota: 4.2M / 5M used+Credits: $7.40 remaining.
Standardwerte
Standardwerte zur Bereitstellung — alle nach der Installation anpassbar, außer wo vermerkt.Preismodell
V1 ist ein pauschales Abonnement. Free + Pro, monatliche Abrechnung, nur USD. Nicht im Umfang von v1 (absichtlich, auf die Roadmap verschoben):- Team-Plan (Stripe-Plätze /
subscription.quantity) - Jährliche Abrechnung
- Multi-Währungs-Präsentation
- Gutscheine / Promo-Codes
- Steuerbehandlung (Stripe Tax-Integration — erfordert separate Compliance-Überprüfung)
- Nutzungsbasierte Messung / Überschussgebühren
- Pay-per-Use-Guthaben (einmalige Aufstockung)
Fehlerbehebung
Toggle wird nicht aktiviert — 400-Fehler
Toggle wird nicht aktiviert — 400-Fehler
Der Aktivierungsendpunkt erfordert, dass sowohl
STRIPE_SECRET_KEY als auch STRIPE_WEBHOOK_SECRET gesetzt sind. Bestätigen Sie, dass sie in .env vorhanden sind und dass das Backend nach der Bearbeitung neu gestartet wurde.Webhook gibt 503 zurück
Webhook gibt 503 zurück
Entweder ist die Abrechnung deaktiviert (Toggle ist AUS), oder die Anfragensignaturverifizierung ist fehlgeschlagen (nicht übereinstimmender
STRIPE_WEBHOOK_SECRET). Überprüfen Sie Stripe Dashboard → Webhooks → aktuelle Ereignisse auf den tatsächlichen Fehlertext.Benutzer abonniert, sieht aber immer noch kostenlosen Plan
Benutzer abonniert, sieht aber immer noch kostenlosen Plan
Der
checkout.session.completed-Webhook hat Ihr Backend nicht erreicht. Überprüfen Sie, dass die Endpunkt-URL im Stripe Dashboard genau mit <your-domain>/api/webhooks/stripe übereinstimmt, einschließlich des nachfolgenden Pfads. Überprüfen Sie die letzten Webhook-Zustellungen auf Fehler.Pro-Benutzer sieht die Test-Modus-Preis-ID
Pro-Benutzer sieht die Test-Modus-Preis-ID
Die Seed-Migration schreibt eine Test-Modus-Preis-ID. Nach der Aktivierung der Produktionsabrechnung aktualisieren Sie den Pro-Plan, um Ihre Live-
price_1*** über Admin → Abrechnung → Pläne → Pro → Bearbeiten oder über direktes SQL UPDATE zu verwenden.Quittungen sind mit Stripe-Standardeinstellungen gekennzeichnet
Quittungen sind mit Stripe-Standardeinstellungen gekennzeichnet
Konfigurieren Sie Ihr Geschäfts-Branding im Stripe Dashboard → Einstellungen → Branding. Fügen Sie Ihr Logo, Ihren Geschäftsnamen (z. B. „FIM Labs Pte. Ltd.”) und Ihre Adresse hinzu. Stripe wendet diese auf alle automatisch generierten Quittungen und Rechnungen an.
Devisenverluste bei Auszahlungen
Devisenverluste bei Auszahlungen
Wenn sich die Standardwährung Ihres Stripe-Kontos von Ihrer Abrechnungswährung unterscheidet, konvertiert Stripe bei jeder Auszahlung (1,5–2% Spread). Fügen Sie eine entsprechende Abrechnungswährung unter Einstellungen → Bankkonten und Währungen hinzu, verknüpfen Sie ein Bankkonto mit derselben Währung, und Stripe leitet Zahlungen mit derselben Währung ohne Umrechnung weiter.