Billing, Payments & Credits
Relevant source files
The following files were used as context for generating this wiki page:
The Billing, Payments & Credits system is a critical infrastructure component of the SecondLayer platform, responsible for tracking resource consumption, managing user balances, and processing financial transactions. It encompasses a dual-layered approach: a consumption-based system for API usage (credits) and a professional legal billing system for time tracking and invoicing.
The system ensures that AI-powered legal document analysis and research tools remain sustainable by tracking costs per request and enforcing balance limits. It also facilitates legal practice management by allowing attorneys to track billable hours, generate PDF invoices, and record client payments.
Sources: mcp_backend/src/http-server.ts:109-115, IMPLEMENTATION_PHASES.md:16-21, mcp_backend/src/migrations/013_add_user_billing.sql:1-5
Core Billing Infrastructure
The backend utilizes a dedicated BillingService and CostTracker to monitor consumption. Every tool execution is tracked for its specific resource cost, including OpenAI/Anthropic token usage and execution time. The system supports multi-currency balances (USD and UAH) and enforces both daily and monthly spending limits.
Data Model
The database schema provides an audit trail for all financial activities through transaction records and real-time balance tracking.
| Table | Purpose | Key Fields |
|---|---|---|
user_billing | Stores user balances and limits. | balance_usd, balance_uah, daily_limit_usd, monthly_limit_usd |
billing_transactions | Ledger of all financial movements. | type (charge, topup, refund), amount_usd, payment_id |
cost_tracking | Records per-request resource consumption. | request_id, tool_name, total_cost_usd, openai_tokens |
Sources: mcp_backend/src/migrations/013_add_user_billing.sql:15-80, mcp_backend/src/http-server.ts:114-118
Cost Tracking Workflow
The following diagram illustrates the lifecycle of a request relative to cost tracking and balance enforcement.
The system estimates costs before execution and reconciles them with actual consumption data once the tool execution completes.
Sources: mcp_backend/src/http-server.ts:1022-1090, mcp_backend/src/migrations/013_add_user_billing.sql:126-155
Payment Processing & Gateway
SecondLayer supports multiple payment providers to facilitate top-ups and invoice settlements. The architecture utilizes a service-proxy pattern to handle various providers, including standard fiat gateways and decentralized crypto payments.
Payment Providers
| Provider | Purpose | Implementation Status |
|---|---|---|
| Stripe | Primary fiat gateway for USD/International. | Active / Mock available for testing |
| Fondy | Regional fiat gateway for UAH/Ukraine. | Active / Mock available for testing |
| MetaMask | Decentralized crypto payments. | Initialized (EVM-based) |
| Binance Pay | Centralized crypto payment gateway. | Initialized |
Sources: mcp_backend/src/http-server.ts:182-225, scripts/testing/test-payment-phase2.sh:110-125
Credit System (Phase 2)
A specialized CreditService manages the allocation and deduction of credits for API usage. This system is designed for high-frequency consumption where users purchase credits upfront.
Legal Practice Billing (Phase 1)
As part of the professional management suite, Phase 1 introduces time tracking and traditional legal invoicing. This allows attorneys to convert billable time directly into financial records.
Time Tracking to Invoicing Flow
- Time Entry: Users record billable minutes associated with a specific "Matter."
- Workflow: Entries progress through statuses:
draft→submitted→approved. - Generation: Approved entries are batched into a
matter_invoicesrecord. - PDF Generation: The system utilizes
pdfkitto generate professional invoice documents. - Payment: Payments are recorded against specific invoices, updating their status to
paidorpartially paid.
Sources: IMPLEMENTATION_PHASES.md:16-25, PHASE1_TESTING.md:40-100
Invoicing Data Structure
The matter_invoices table tracks the financial health of specific legal matters.
API Endpoints Summary
The following table summarizes the primary endpoints available for billing and payment management.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/billing/balance | Retrieves current user balance, spending stats, and limits. |
| POST | /api/billing/topup | Manually tops up balance (Admin) or records external payment. |
| GET | /api/billing/history | Returns a paginated transaction history. |
| POST | /api/invoicing/generate | Creates a new invoice from approved time entries. |
| POST | /api/billing/payment/:provider/create | Initiates a payment intent with Stripe, Fondy, or Crypto. |
| GET | /api/billing/invoices/:num/pdf | Downloads the generated PDF version of an invoice. |
Sources: mcp_backend/src/http-server.ts:600-650, IMPLEMENTATION_PHASES.md:55-75, mcp_backend/src/http-server.ts:875-900
Conclusion
The Billing, Payments & Credits system serves as the financial backbone of SecondLayer. By integrating consumption-based credit tracking with professional legal invoicing, the platform provides a unified financial experience for both AI resource management and traditional legal practice needs. The modular provider architecture ensures extensibility for future payment methods while maintaining strict auditability through the PostgreSQL ledger.
Sources: IMPLEMENTATION_PHASES.md:135-145, mcp_backend/src/migrations/013_add_user_billing.sql:125-150