软件默认为无订阅(
access_model = off、default_token_quota = 0 表示无限制)。全新安装和现有自托管部署从此处开始。在管理员选择 Stripe 方案之前,不会显示任何计费 UI。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
前置条件
- Stripe账户已启用实时模式。新加坡注册公司必须完成KYC(营业执照、董事身份证、银行账户)。审批通常需要1-3天。
- Stripe实时API密钥,类型为受限制(推荐使用,相比标准
sk_live_***更易撤销、权限范围更小)。 - Webhook端点可公开访问,地址为
<your-domain>/api/webhooks/stripe。 - 银行账户用于支付。建议多币种结算(例如USD支付到USD账户),以避免非USD默认Stripe账户每笔交易产生1.5-2%的汇兑损失。
设置
1. Stripe 仪表板
创建Pro产品
- Catalog → Products → + Add product
- Name:
Pro, description:5M tokens / month, priority support - Pricing: Recurring, monthly, $20.00 USD (根据您的定价策略调整)
- Save → 复制生成的
price_***ID(激活后,您将使用此值更新本地billing_plans表)
创建受限API密钥
- 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端点
- Developers → Webhooks → + Add endpoint
- URL:
https://<your-domain>/api/webhooks/stripe - 要接收的事件:
checkout.session.completedcustomer.subscription.createdcustomer.subscription.updatedcustomer.subscription.deletedinvoice.payment_succeededinvoice.payment_failed
- 保存后,点击”Reveal signing secret”→ 复制
whsec_***
配置多币种结算(推荐)
如果您的Stripe账户默认币种与您收费的价格币种不同(常见情况:SGD账户收取USD费用):- Settings → Bank accounts and currencies → Add a settlement currency
- 选择价格币种(例如USD)
- 关联匹配的银行账户(例如Aspire USD虚拟账户)
- 保存——Stripe将USD费用直接路由到USD支付,无需外汇转换
2. 后端 .env
在生产环境的 .env 中设置这三个密钥:
.env 后重启后端以使密钥生效:
3. 在管理员中激活
- 以管理员身份登录
- 管理员 → 系统设置 → 访问和计费
- 选择一种状态(实例始终恰好处于其中一种):
- 无订阅(软件默认值)— Stripe 未使用。令牌访问是默认月度配额(
0= 无限制)。 - 包含 + 付费 — 需要 Stripe。新用户进入包含层级;他们可以升级。已取消的付费用户在周期结束时返回包含层级。
- 仅付费 — 需要 Stripe。无包含层级。用户必须先订阅才能调用模型。如果从”包含 + 付费”切换,现有包含层级用户保留其配额。
- 无订阅(软件默认值)— Stripe 未使用。令牌访问是默认月度配额(
- 后端验证当你选择 Stripe 状态时,
STRIPE_SECRET_KEY和STRIPE_WEBHOOK_SECRET都存在——如果缺少任何一个,返回 400 - 首次激活 Stripe 状态时,后端运行幂等设置:
- 包含 + 付费:为包含计划(
slug=free)和带有空 Price ID 的 Pro 模板提供种子数据;设置default_plan_id;为没有计划的用户回填 - 仅付费:仅为 Pro 模板提供种子数据;不进行回填
- 当该计划被提供种子数据时,将
default_token_quota复制到包含计划(0保持0,无限制)
- 包含 + 付费:为包含计划(
- 切换回无订阅是纯标志翻转,没有数据副作用。当”包含 + 付费”处于活跃状态时,包含的默认计划无法删除。
4. 使用您的实时价格更新Pro套餐
激活后,更新预设的Pro套餐以指向您的实时Stripe价格:- Admin → Billing → Plans → Pro → Edit
- 将您的
price_1***(来自第1步)粘贴到Stripe Price ID - 保存
5. 烟雾测试
- 以普通用户身份打开
/settings?tab=billing - 点击升级到 Pro
- Stripe Checkout 打开;使用低额真实卡片完成支付(之后退款)
- Webhook 应该触发——在 Stripe Dashboard → Webhooks → 最近事件中验证显示 2xx 响应
- 订阅行出现在
subscriptions表中;users.plan_id切换为pro - UI 现在显示 Pro 计划 + “管理订阅”按钮
禁用账单
在管理员 → 系统设置 → 账单中,将启用 Stripe 账单开关切换为关闭。 禁用后:- 所有
/api/billing/*端点返回 503 - Webhook 端点返回 503(Stripe 将重试,然后在仪表板中显示为失败——这是正常的,如果账单永久关闭,你可以改为在 Stripe 仪表板中禁用 Webhook)
Plan & Billing用户界面标签页消失- 管理员 → 账单导航组被隐藏
- 配额链跳过计划层级,直接回退到
default_token_quota
subscriptions、billing_plans 和 users.plan_id 行保持不变。重新启用将从相同状态恢复,无需迁移。
计算参考——配额和令牌数学
这是权威参考,用于决定用户被允许消费的内容、计数器何时重置以及解析链如何组合的每条数值规则。在更改定价、调整配额、构建使用情况仪表板或规划v2/v3工作之前,请阅读本文档。尚未发布的未来规则记录在其保留位置,以便贡献者知道新逻辑在何处插入。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.
三态覆盖语义
users.token_quota 是按用户的管理覆盖。它在一列中承载三种含义:
覆盖始终优先于套餐和默认值。它的存在使管理员能够将单个用户固定在其套餐层级之上或之下,而无需接触Stripe。
配额解析链——v1(当前版本)
对于任何已认证的请求,上限从上到下计算——首次匹配获胜:default_token_quota为0,没有计划的用户也无权限(聊天返回402)。
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.
账单禁用回退
当system_settings.billing_enabled = FALSE 时:
- 跳过链的第 2 步——链折叠为
override → default → unlimited。 /api/billing/*和/api/webhooks/stripe返回503。Plan & Billing用户标签页和 Admin → Billing 导航组被隐藏。- 所有账单数据(订阅、套餐、
users.plan_id)被保留——重新启用时从相同状态恢复,无需迁移。
保留:配额链 v2 — 团队座位
尚未发布。此处记录以便 v2 工作有已知的落地点。
Subscription.quantity携带座位数(Stripe 原生)。- 用户的有效计划通过团队成员身份解析,然后回退到其个人计划:
- 配额是按座位(每个团队成员获得完整的
monthly_token_quota),而不是共享池。共享池会导致先到先得的耗尽,对客户不利。 - 覆盖语义保持不变——团队管理员仍然可以通过
users.token_quota = N对单个成员进行硬限制,该限制在链中位于团队计划之上。
Reserved: quota chain v3 — native Org allocation (no Stripe)
Not yet shipped. Reserved for on-prem / enterprise deployments that allocate quota internally without paying Stripe per user.
- New table
org_quota_allocations(user_id, monthly_token_quota, org_id)distributes a parent budget across members. - Allocations are per user, not a shared pool — every member has a clear individual SLA.
- Updated chain:
max(),而非sum()。付费Pro用户永远不会获得少于他们已支付的配额,即使他们的组织管理员设置了较低的分配。Stripe支付的配额是神圣的。
预留:按使用量付费的信用额度余额(v3 独立维度)
尚未发布。与上述链独立的轴——信用额度是一次性充值,而非订阅层级。
- 新表
user_credits(user_id, balance_cents, currency)——通过 Stripe Checkoutmode='payment'充值。 - 消费顺序:订阅配额优先,然后是信用额度余额(仅在订阅耗尽后才开始扣除信用额度)。
- 信用额度余额不可退款(预付款行业标准)。
- UI 同时展示两个进度条:
订阅配额:已使用 4.2M / 5M+信用额度:剩余 $7.40。
默认值
发货时的默认值——除特别说明外,所有值均可在安装后调整。定价模型
V1 是一个统一订阅。免费 + 专业版,按月计费,仅支持美元。 V1 范围外(有意推迟至路线图):- 团队计划(Stripe 座位 /
subscription.quantity) - 年度计费
- 多币种展示
- 优惠券 / 促销代码
- 税务处理(Stripe Tax 集成——需要单独的合规审查)
- 基于使用量的计量 / 超额费用
- 按次付费信用余额(一次性充值)
故障排除
切换开关无法激活——400错误
切换开关无法激活——400错误
激活端点需要同时设置
STRIPE_SECRET_KEY 和 STRIPE_WEBHOOK_SECRET。确认它们存在于 .env 中,并且编辑后后端已重启。Webhook返回503
Webhook返回503
要么是账单被禁用(切换开关为OFF),要么是请求签名验证失败(
STRIPE_WEBHOOK_SECRET 不匹配)。检查Stripe仪表板→Webhooks→最近事件以查看实际错误正文。用户已订阅但仍显示免费计划
用户已订阅但仍显示免费计划
checkout.session.completed webhook未到达你的后端。验证Stripe仪表板中的端点URL与 <your-domain>/api/webhooks/stripe 完全匹配,包括末尾路径。检查Webhook最近交付记录中的失败。Pro用户看到测试模式价格ID
Pro用户看到测试模式价格ID
种子迁移写入了测试模式价格ID。激活生产账单后,通过管理员→账单→套餐→Pro→编辑,或通过直接SQL UPDATE,将Pro计划更新为使用你的实时
price_1***。收据使用Stripe默认品牌
收据使用Stripe默认品牌
在Stripe仪表板→设置→品牌中配置你的业务品牌。添加你的徽标、业务名称(例如”FIM Labs Pte. Ltd.”)和地址。Stripe会将这些应用于所有自动生成的收据和发票。
支付中的汇兑损失
支付中的汇兑损失
如果你的Stripe账户默认货币与收费货币不同,Stripe会在每次支付时进行转换(1.5-2%的差价)。在设置→银行账户和货币下添加匹配的结算货币,附加相同货币的银行账户,Stripe将路由相同货币的付款而无需转换。