메인 콘텐츠로 건너뛰기
FIM One은 인스턴스 액세스 모델 뒤에 완전한 Stripe 청구 파이프라인을 제공합니다. 프라이빗 배포는 No subscriptions으로 유지되며 결제 UI를 표시하지 않습니다. 카탈로그를 원하는 운영자는 Included + paid 또는 Paid only를 선택하면 호스팅된 Checkout, Customer Portal, 웹훅 기반 구독 라이프사이클 및 할당량 적용을 얻습니다.
소프트웨어 기본값은 No subscriptions입니다(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

전제 조건

  1. Stripe 계정 (라이브 모드 활성화됨). 싱가포르 법인은 KYC 완료 필요(사업 UEN, 이사 신분증, 은행 계좌). 승인은 일반적으로 1-3일 소요됩니다.
  2. Stripe 라이브 API 키 (제한된 유형 권장 — 표준 sk_live_***보다 해지하기 쉽고 권한 범위 지정 가능).
  3. 웹훅 엔드포인트 (<your-domain>/api/webhooks/stripe에서 공개적으로 접근 가능).
  4. 은행 계좌 (지급용). 다중 통화 결제(예: USD 계좌로 USD 지급)는 USD 기본값이 아닌 Stripe 계정의 경우 거래당 1.5-2% FX 손실을 피하기 위해 권장됩니다.

설정

1. Stripe 대시보드

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)

제한된 API 키 생성

  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_***

웹훅 엔드포인트 등록

  1. Developers → Webhooks → + Add endpoint
  2. URL: https://<your-domain>/api/webhooks/stripe
  3. 수신할 이벤트:
    • checkout.session.completed
    • customer.subscription.created
    • customer.subscription.updated
    • customer.subscription.deleted
    • invoice.payment_succeeded
    • invoice.payment_failed
  4. 저장 후 “Reveal signing secret” 클릭 → whsec_*** 복사

다중 통화 결제 구성(권장)

Stripe 계정의 기본 통화가 청구하는 가격 통화와 다른 경우(일반적인 경우: SGD 계정에서 USD 청구):
  1. Settings → Bank accounts and currencies → Add a settlement currency
  2. 가격 통화 선택(예: USD)
  3. 일치하는 은행 계좌 연결(예: Aspire USD 가상 계좌)
  4. 저장 — Stripe가 USD 청구를 USD 지급으로 직접 라우팅하므로 환율 변환 없음

2. Backend .env

프로덕션 .env에서 다음 세 개의 키를 설정하세요:
전체 참조는 Environment Variables를 참조하세요. .env를 편집한 후 백엔드를 다시 시작하여 키가 적용되도록 하세요:

3. 관리자에서 활성화

  1. 관리자로 로그인
  2. 관리자 → 시스템 설정 → 액세스 및 청구
  3. 하나의 포지션을 선택합니다(인스턴스는 항상 정확히 하나의 포지션에 있음):
    • 구독 없음(소프트웨어 기본값) — Stripe 미사용. 토큰 액세스는 기본 월간 할당량(0 = 무제한)입니다.
    • 포함됨 + 유료 — Stripe 필수. 새 사용자는 포함된 계층에 도착하며, 업그레이드할 수 있습니다. 취소된 유료 사용자는 기간 종료 시 포함된 계층으로 돌아갑니다.
    • 유료만 — Stripe 필수. 포함된 계층 없음. 사용자는 모델을 호출하기 전에 구독해야 합니다. 포함됨 + 유료에서 전환할 때 기존 포함된 계층 사용자는 할당량을 유지합니다.
  4. 백엔드는 Stripe 포지션을 선택할 때 STRIPE_SECRET_KEY와 STRIPE_WEBHOOK_SECRET이 모두 있는지 검증합니다 — 둘 중 하나라도 없으면 400을 반환합니다.
  5. Stripe 포지션을 처음 활성화할 때 백엔드는 멱등성 설정을 실행합니다:
    • 포함됨 + 유료: 포함된 플랜(slug=free) + 빈 가격 ID가 있는 Pro 템플릿을 시드합니다. default_plan_id를 설정합니다. 플랜이 없는 사용자를 역채웁니다.
    • 유료만: Pro 템플릿만 시드합니다. 역채우지 않습니다.
    • 해당 플랜이 시드될 때 default_token_quota를 포함된 플랜에 복사합니다(0은 0으로 유지, 무제한).
  6. 구독 없음으로 다시 전환하는 것은 데이터 부작용이 없는 순수 플래그 전환입니다. 포함됨 + 유료가 활성화되어 있는 동안 포함된 기본 플랜은 삭제할 수 없습니다.

4. Pro 플랜을 라이브 가격으로 업데이트

활성화 후, 시드된 Pro 플랜을 라이브 Stripe 가격으로 업데이트하세요:
  • Admin → Billing → Plans → Pro → Edit
  • 1단계에서 얻은 price_1***을 Stripe Price ID에 붙여넣기
  • 저장
또는 SQL을 통해 (직접 DB 접근을 선호하는 경우):

5. Smoke test

  1. /settings?tab=billing을 일반 사용자로 열기
  2. Switch to Pro 클릭
  3. Stripe Checkout이 열림; 소액 실제 카드로 완료 (이후 환불)
  4. Webhook이 실행되어야 함 — Stripe Dashboard → Webhooks → 최근 이벤트에서 2xx 응답 확인
  5. subscriptions 테이블에 구독 행이 나타남; users.plan_id가 pro로 변경됨
  6. UI에 Pro 플랜 + “Manage subscription” 버튼 표시

청구 비활성화

Admin → System Settings → Billing에서 Enable Stripe Billing 스위치를 OFF로 전환합니다. 비활성화되면:
  • 모든 /api/billing/* 엔드포인트가 503을 반환합니다
  • 웹훅 엔드포인트가 503을 반환합니다 (Stripe가 재시도한 후 Dashboard에 실패로 표시됩니다 — 청구가 영구적으로 비활성화된 경우 Stripe Dashboard에서 웹훅을 비활성화할 수 있습니다)
  • Plan & Billing 사용자 대면 탭이 사라집니다
  • Admin → 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’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.

3단계 오버라이드 의미론

users.token_quota는 사용자별 관리 오버라이드입니다. 하나의 열에 세 가지 의미를 담고 있습니다: 오버라이드는 항상 플랜과 기본값을 우선합니다. 관리자가 Stripe를 건드리지 않고도 개별 사용자를 플랜 계층 위 또는 아래에 고정할 수 있도록 존재합니다.

할당량 해결 체인 — v1 (현재)

인증된 요청의 경우 상한은 하향식으로 계산됩니다 — 첫 번째 일치가 우선입니다:
4단계는 구독 없음에 대한 인스턴스 전체 상한입니다. 유료만 설정에서는 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 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.

청구 비활성화 폴백

system_settings.billing_enabled = FALSE일 때:
  • 체인의 2단계가 건너뛰어집니다 — 체인이 override → default → unlimited로 축소됩니다.
  • /api/billing/* 및 /api/webhooks/stripe는 503을 반환합니다.
  • Plan & Billing 사용자 탭 및 Admin → Billing 네비게이션 그룹이 숨겨집니다.
  • 모든 청구 데이터(구독, 플랜, users.plan_id)는 보존됩니다 — 다시 활성화하면 마이그레이션 없이 동일한 상태에서 재개됩니다.

Reserved: quota chain v2 — Team seats

아직 출시되지 않았습니다. v2 작업이 알려진 착륙 지점을 가지도록 여기에 문서화되어 있습니다.
Team 플랜이 출시될 때:
  • Subscription.quantity는 좌석 수를 전달합니다(Stripe 기본).
  • 사용자의 유효한 플랜은 Team 멤버십을 통해 해결되며, 그 후 개인 플랜으로 폴백됩니다:
  • 할당량은 좌석당(각 Team 멤버는 전체 monthly_token_quota를 받음)이며, 풀링된 버킷이 아닙니다. 풀링된 버킷은 선착순 소진을 만들고 고객 친화적이지 않습니다.
  • 재정의 의미는 변경되지 않습니다 — Team 관리자는 여전히 users.token_quota = N을 통해 개별 멤버를 하드 캡할 수 있으며, 이는 team 플랜 체인 위에 있습니다.

Reserved: quota chain v3 — native Org allocation (no Stripe)

아직 출시되지 않음. Stripe를 통해 사용자당 비용을 지불하지 않고 내부적으로 할당량을 배분하는 온프레미스/엔터프라이즈 배포용으로 예약됨.
  • 새로운 테이블 org_quota_allocations(user_id, monthly_token_quota, org_id)는 상위 예산을 멤버 전체에 배분합니다.
  • 할당량은 공유 풀이 아닌 사용자별 — 모든 멤버가 명확한 개별 SLA를 가집니다.
  • 업데이트된 체인:
  • max(), sum() 아님. 유료 Pro 사용자는 조직 관리자가 낮은 할당량을 설정하더라도 결코 지불한 것보다 적게 받지 않습니다. Stripe 지불 할당량은 절대 불변입니다.

예약됨: 종량제 크레딧 잔액 (v3 별도 차원)

아직 출시되지 않음. 위의 체인과 별개의 축——크레딧은 구독 티어가 아닌 일회성 충전입니다.
  • 새로운 테이블 user_credits(user_id, balance_cents, currency) — Stripe Checkout mode='payment'를 통해 자금 조달됨.
  • 소비 순서: 구독 할당량 우선, 그 다음 크레딧 잔액 (구독이 소진된 후에만 크레딧 차감 시작).
  • 크레딧 잔액은 환불 불가능 (선불식 업계 표준).
  • UI는 두 개의 바를 노출: Subscription quota: 4.2M / 5M used + Credits: $7.40 remaining.

기본값

배포 시점의 기본값 — 명시된 경우를 제외하고 모두 설치 후 조정 가능합니다.

가격 책정 모델

V1은 정액 구독입니다. Free + Pro, 월간 청구, USD만 지원합니다. V1 범위 외 (의도적으로 로드맵으로 연기됨):
  • Team 플랜 (Stripe seats / subscription.quantity)
  • 연간 청구
  • 다중 통화 표시
  • 쿠폰 / 프로모션 코드
  • 세금 처리 (Stripe Tax 통합 — 별도 규정 검토 필요)
  • 사용량 기반 계량 / 초과 요금
  • 선불 크레딧 잔액 (일회성 충전)
다음 계획된 사항은 로드맵을 참조하세요.

문제 해결

활성화 엔드포인트에는 STRIPE_SECRET_KEY와 STRIPE_WEBHOOK_SECRET이 모두 설정되어야 합니다. .env에 존재하는지 확인하고 편집 후 백엔드가 다시 시작되었는지 확인하세요.
청구가 비활성화되어 있거나(토글이 OFF) 요청 서명 검증에 실패했습니다(STRIPE_WEBHOOK_SECRET 불일치). Stripe 대시보드 → 웹훅 → 최근 이벤트에서 실제 오류 본문을 확인하세요.
checkout.session.completed 웹훅이 백엔드에 도달하지 않았습니다. Stripe 대시보드의 엔드포인트 URL이 <your-domain>/api/webhooks/stripe와 정확히 일치하는지(후행 경로 포함) 확인하세요. 웹훅 최근 전달 기록에서 실패를 확인하세요.
시드 마이그레이션이 테스트 모드 가격 ID를 작성합니다. 프로덕션 청구를 활성화한 후 관리자 → 청구 → 요금제 → Pro → 편집을 통해 Pro 요금제를 라이브 price_1***을 사용하도록 업데이트하거나 직접 SQL UPDATE를 실행하세요.
Stripe 대시보드 → 설정 → 브랜딩에서 비즈니스 브랜딩을 구성하세요. 로고, 비즈니스 이름(예: “FIM Labs Pte. Ltd.”), 주소를 추가하세요. Stripe는 이를 모든 자동 생성 영수증 및 청구서에 적용합니다.
Stripe 계정 기본 통화가 청구 통화와 다르면 Stripe는 매번 지급할 때 환전합니다(1.5-2% 스프레드). 설정 → 은행 계좌 및 통화에서 일치하는 결제 통화를 추가하고 동일 통화 은행 계좌를 연결하면 Stripe가 환전 없이 동일 통화 결제를 라우팅합니다.