Passer au contenu principal
FIM One propose un pipeline de facturation Stripe complet derrière un modèle d’accès par instance. Les déploiements privés le laissent sur Pas d’abonnements et ne voient jamais l’interface de paiement. Les opérateurs qui souhaitent un catalogue choisissent Inclus + payant ou Payant uniquement et obtiennent Checkout hébergé, Customer Portal, cycle de vie d’abonnement piloté par webhook et application des quotas.
La valeur par défaut du logiciel est Pas d’abonnements (access_model = off, default_token_quota = 0 signifiant illimité). Les nouvelles installations et les auto-hébergements existants commencent là. Aucune interface de facturation n’apparaît jusqu’à ce qu’un administrateur choisisse une posture Stripe.

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

Prérequis

  1. Compte Stripe avec le mode Live activé. Les entreprises constituées à Singapour doivent compléter la vérification KYC (UEN commercial, ID du directeur, compte bancaire). L’approbation prend généralement 1 à 3 jours.
  2. Clé API Stripe Live de type Restricted (recommandée plutôt que Standard sk_live_*** — plus facile à révoquer, permissions limitées).
  3. Point de terminaison webhook accessible publiquement à <your-domain>/api/webhooks/stripe.
  4. Compte bancaire pour les versements. Le règlement multi-devises (par ex. versement en USD vers un compte USD) est recommandé pour les comptes Stripe non-USD par défaut afin d’éviter une fuite de change de 1,5 à 2 % par transaction.

Configuration

1. Tableau de bord Stripe

Créer le produit Pro

  1. Catalog → Products → + Add product
  2. Name: Pro, description: 5M tokens / month, priority support
  3. Pricing: Recurring, monthly, $20.00 USD (adjust to your pricing strategy)
  4. Save → copy the resulting price_*** ID (you will UPDATE the local billing_plans table with this value after activation)

Créer une clé API restreinte

  1. Developers → API keys → + Create restricted key
  2. Name: fim-one production
  3. Permissions (minimum):
    • Customers: Write
    • Subscriptions: Write
    • Checkout Sessions: Write
    • Customer portal: Write
    • Prices: Read
    • Products: Read
  4. Save → copy rk_live_***

Enregistrer le point de terminaison du webhook

  1. Developers → Webhooks → + Add endpoint
  2. URL: https://<your-domain>/api/webhooks/stripe
  3. Événements à recevoir:
    • checkout.session.completed
    • customer.subscription.created
    • customer.subscription.updated
    • customer.subscription.deleted
    • invoice.payment_succeeded
    • invoice.payment_failed
  4. Après l’enregistrement, cliquez sur “Reveal signing secret” → copiez whsec_***

Configurer le règlement multi-devises (recommandé)

Si la devise par défaut de votre compte Stripe diffère de la devise de prix que vous facturez (cas courant : compte SGD facturant en USD) :
  1. Paramètres → Comptes bancaires et devises → Ajouter une devise de règlement
  2. Sélectionnez la devise de prix (par ex. USD)
  3. Attachez le compte bancaire correspondant (par ex. un compte virtuel Aspire USD)
  4. Enregistrez — Stripe achemine les frais USD directement vers les versements USD, sans conversion de change

2. Backend .env

Définissez ces trois clés dans votre .env de production :
Consultez Variables d’environnement pour la référence complète. Redémarrez le backend après avoir modifié .env pour que les clés soient prises en compte :

3. Activer dans Admin

  1. Connectez-vous en tant qu’administrateur
  2. Admin → System Settings → Access and billing
  3. Choisissez une posture (l’instance est toujours dans exactement une) :
    • No subscriptions (logiciel par défaut) — Stripe inutilisé. L’accès par token est le quota mensuel par défaut (0 = illimité).
    • Included + paid — Stripe requis. Les nouveaux utilisateurs arrivent sur le tier inclus ; ils peuvent passer à une version payante. Les utilisateurs payants annulés reviennent au tier inclus à la fin de la période.
    • Paid only — Stripe requis. Pas de tier inclus. Les utilisateurs doivent s’abonner avant de pouvoir appeler les modèles. Les utilisateurs du tier inclus existants conservent leur quota si vous passez de Included + paid.
  4. Le backend valide que STRIPE_SECRET_KEY et STRIPE_WEBHOOK_SECRET sont présents lorsque vous choisissez une posture Stripe — si l’un des deux est manquant, il retourne 400
  5. À la première activation d’une posture Stripe, le backend exécute une configuration idempotente :
    • Included + paid : initialise le plan inclus (slug=free) + un modèle Pro avec un ID de prix vide ; définit default_plan_id ; remplit rétroactivement les utilisateurs sans plan
    • Paid only : initialise uniquement le modèle Pro ; ne remplit pas rétroactivement
    • Copie default_token_quota sur le plan inclus lors de son initialisation (0 reste 0, illimité)
  6. Revenir à No subscriptions est un simple changement de drapeau sans effets secondaires sur les données. Le plan par défaut inclus ne peut pas être supprimé tant que Included + paid est actif.

4. Mettez à jour le plan Pro avec votre prix en direct

Après l’activation, mettez à jour le plan Pro pré-configuré pour pointer vers votre prix Stripe en direct :
  • Admin → Billing → Plans → Pro → Edit
  • Collez votre price_1*** (de l’étape 1) dans Stripe Price ID
  • Enregistrez
Ou via SQL (si vous préférez un accès direct à la base de données) :

5. Test de fumée

  1. Ouvrez /settings?tab=billing en tant qu’utilisateur ordinaire
  2. Cliquez sur Switch to Pro
  3. Stripe Checkout s’ouvre ; complétez avec une vraie carte à faible montant (remboursement après)
  4. Le webhook doit se déclencher — vérifiez dans Stripe Dashboard → Webhooks → les événements récents affichent des réponses 2xx
  5. Une ligne d’abonnement apparaît dans la table subscriptions ; users.plan_id bascule à pro
  6. L’interface affiche maintenant le plan Pro + le bouton « Manage subscription »

Désactiver la facturation

Basculez le commutateur Enable Stripe Billing sur OFF dans Admin → System Settings → Billing. Lorsque désactivé :
  • Tous les points de terminaison /api/billing/* retournent 503
  • Le point de terminaison webhook retourne 503 (Stripe réessaiera, puis s’affichera dans Dashboard comme défaillant — c’est normal, vous pouvez désactiver le webhook dans Stripe Dashboard à la place si la facturation est définitivement désactivée)
  • L’onglet Plan & Billing destiné aux utilisateurs disparaît
  • Le groupe de navigation Admin → Billing est masqué
  • La chaîne de quota ignore le niveau de plan et revient directement à default_token_quota
Les données sont préservées : les lignes subscriptions, billing_plans et users.plan_id existantes restent inchangées. La réactivation reprend à partir du même état sans migration.

Référence de calcul — mathématiques des quotas et des jetons

Ceci est la référence faisant autorité pour chaque règle numérique qui décide ce qu’un utilisateur est autorisé à consommer, quand son compteur se réinitialise, et comment la chaîne de résolution se compose. Lisez ceci avant de modifier la tarification, d’ajuster les quotas, de créer des tableaux de bord d’utilisation, ou de planifier les travaux v2/v3. Les règles futures non encore déployées sont documentées dans leur emplacement réservé afin que les contributeurs sachent où s’intègre la nouvelle logique.

Glossary

What counts as a token

Token consumption is metered in the model client, from the provider’s usage 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_tokens when 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’s o200k_base tokenizer 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.
Usage never goes down within a window. Deleting a conversation, a workflow run or a workflow, the retention clean-up of old runs, and deleting an agent leave “used” where it was: the ledger row has no link to what it was recorded for. Usage belongs to the window in which it was recorded, so a turn in a conversation created months ago counts in the current window. Where each row comes from is on the row: 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.

Sémantique de remplacement à trois états

users.token_quota est le remplacement administratif par utilisateur. Il porte trois significations dans une seule colonne : Le remplacement l’emporte toujours sur le plan et le défaut. Il existe pour permettre aux administrateurs d’épingler des utilisateurs individuels au-dessus ou au-dessous de leur niveau de plan sans toucher à Stripe.

Chaîne de résolution des quotas — v1 (actuelle)

Pour toute demande authentifiée, le plafond est calculé de haut en bas — la première correspondance gagne :
L’étape 4 est le plafond au niveau de l’instance pour Aucun abonnement. Sous Payant uniquement, un utilisateur sans plan n’a pas de droits (le chat retourne 402) même si default_token_quota est 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 on users.quota_reset_at), which the invoice.payment_succeeded webhook 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 failed with token_quota_exceeded and the number of cases not run in its error; each batch item not started is failed with token_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 429 with error_code token_quota_exceeded. Under Paid only, a user with no plan gets HTTP 402 with error_code subscription_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.

Fallback avec facturation désactivée

Quand system_settings.billing_enabled = FALSE :
  • L’étape 2 de la chaîne est ignorée — la chaîne se réduit à override → default → unlimited.
  • /api/billing/* et /api/webhooks/stripe retournent 503.
  • L’onglet utilisateur Plan & Billing et le groupe de navigation Admin → Billing sont masqués.
  • Toutes les données de facturation (abonnements, plans, users.plan_id) sont conservées — la réactivation reprend à partir du même état sans migration.

Réservé : chaîne de quota v2 — Sièges d’équipe

Pas encore livré. Documenté ici pour que le travail v2 ait un point de destination connu.
Quand le plan Team sera lancé :
  • Subscription.quantity porte le nombre de sièges (natif Stripe).
  • Le plan effectif d’un utilisateur se résout via l’appartenance à l’équipe avant de revenir à son plan personnel :
  • Le quota est par siège (chaque membre de l’équipe obtient un monthly_token_quota complet), et non un pool partagé. Les pools partagés créent un épuisement au premier arrivé, premier servi et sont contraires aux intérêts des clients.
  • La sémantique des remplacements reste inchangée — les administrateurs d’équipe peuvent toujours plafonner fortement les membres individuels via users.token_quota = N, qui se situe au-dessus du plan d’équipe dans la chaîne.

Réservé : chaîne de quota v3 — allocation native Org (sans Stripe)

Pas encore livré. Réservé pour les déploiements sur site / entreprise qui allouent le quota en interne sans payer Stripe par utilisateur.
  • Nouvelle table org_quota_allocations(user_id, monthly_token_quota, org_id) distribue un budget parent entre les membres.
  • Les allocations sont par utilisateur, pas un pool partagé — chaque membre a un SLA individuel clair.
  • Chaîne mise à jour :
  • max(), pas sum(). Un utilisateur Pro payant n’obtient jamais moins que ce qu’il a payé, même si son administrateur Org définit une allocation basse. Le quota payé via Stripe est sacrosaint.

Réservé : solde de crédits à l’usage (dimension v3 séparée)

Pas encore livré. Un axe distinct de la chaîne ci-dessus — les crédits sont un rechargement unique, pas un niveau d’abonnement.
  • Nouvelle table user_credits(user_id, balance_cents, currency) — financée via Stripe Checkout mode='payment'.
  • Ordre de consommation : quota d’abonnement en premier, puis solde de crédits (la décrémentation des crédits ne commence qu’après l’épuisement de l’abonnement).
  • Le solde de crédits n’est pas remboursable (standard industriel pour les prépayés).
  • L’interface expose les deux barres : Quota d'abonnement : 4,2M / 5M utilisés + Crédits : 7,40 $ restants.

Valeurs par défaut

Valeurs par défaut au moment du déploiement — toutes modifiables après installation sauf indication contraire.

Modèle de tarification

V1 est un abonnement forfaitaire. Gratuit + Pro, facturation mensuelle, USD uniquement. Hors du champ d’application pour v1 (intentionnel, reporté à la feuille de route) :
  • Plan d’équipe (sièges Stripe / subscription.quantity)
  • Facturation annuelle
  • Présentation multi-devises
  • Coupons / codes promotionnels
  • Gestion des taxes (intégration Stripe Tax — nécessite un examen de conformité distinct)
  • Mesure basée sur l’utilisation / frais de dépassement
  • Solde de crédit à l’usage (recharge unique)
Consultez la feuille de route pour connaître les prochaines étapes prévues.

Dépannage

Le point de terminaison d’activation nécessite que STRIPE_SECRET_KEY et STRIPE_WEBHOOK_SECRET soient définis. Confirmez qu’ils sont présents dans .env et que le backend a été redémarré après la modification.
Soit la facturation est désactivée (le bouton bascule est OFF), soit la vérification de la signature de la requête a échoué (clé STRIPE_WEBHOOK_SECRET non concordante). Consultez Stripe Dashboard → Webhooks → événements récents pour voir le corps d’erreur réel.
Le webhook checkout.session.completed n’a pas atteint votre backend. Vérifiez que l’URL du point de terminaison dans Stripe Dashboard correspond exactement à <your-domain>/api/webhooks/stripe, y compris le chemin de fin. Consultez les livraisons récentes du webhook pour les défaillances.
La migration de seed écrit un ID de prix en mode test. Après l’activation de la facturation en production, mettez à jour le plan Pro pour utiliser votre price_1*** en direct via Admin → Billing → Plans → Pro → Edit, ou via une UPDATE SQL directe.
Configurez votre image de marque commerciale dans Stripe Dashboard → Settings → Branding. Ajoutez votre logo, le nom de votre entreprise (par exemple « FIM Labs Pte. Ltd. ») et votre adresse. Stripe applique ces paramètres à tous les reçus et factures générés automatiquement.
Si la devise par défaut de votre compte Stripe diffère de votre devise de facturation, Stripe convertit à chaque versement (écart de 1,5-2 %). Ajoutez une devise de règlement correspondante sous Settings → Bank accounts and currencies, attachez un compte bancaire dans la même devise, et Stripe acheminera les paiements dans la même devise sans conversion.