This belongs to the standalone Laravel host. The reusable Composer package has no billing dependency. Payment approval is a financial assertion by an authorized platform administrator after checking an external receipt. The application does not collect money, verify bank receipts, contact a gateway or charge automatically. Operators must supply their payment instructions and verify the actual transfer outside this application before approving it. Do not approve live receipts as test fixtures.
Plans and amounts#
Plans are monthly, denominated in BDT. price_minor and invoice amount_minor are integers: 99000 represents BDT 990.00. Floats, zero and negative prices are rejected; the maximum is 1000000000 minor units. Limits max_providers, max_accounts, monthly_messages accept a positive integer up to 1000000000, or null for unlimited. Omitted limits on creation are unlimited. There is no trial, free plan, implicit grace period, discount, tax calculation or proration.
config/chat-billing.php supplies server-only defaults: currency='BDT', interval='month', legacy_unmetered=true. These are nonsecret PHP configuration, not browser options or environment variables. Other currencies/intervals are not supported by the current API or totals. Do not change them without a contract and migration review. Archiving uses is_active=false; no delete route exists. It hides a plan from service administrators and prevents new invoices, while previous invoices remain payable at their original amount and terms.
Access, pagination and schemas#
All routes below have prefix /api/admin/billing, individual Bearer authentication and the central authenticated 120 requests/minute/IP throttle. Platform administrators manage all services. Service administrators may browse active plans and manage only their stored service's subscription and submissions. Customers/sellers receive 403. Service-scoped object access outside the actor's service returns 404; a cross-service enrollment request returns 403. Service administrator list filters cannot widen their stored scope. Platform lists may filter subscriptions/invoices with ?service_id=...; their current chat-selected service does not reduce their global billing permission.
Lists accept page (default 1, maximum 100000), per_page (default 20, maximum 100), order by descending ID and return {data:[...],meta:{page,per_page,total,last_page}}. total covers the whole scoped collection; pagination is offset based and concurrent inserts can move pages. Invoice lists additionally return scoped whole-collection totals:{currency:'BDT',open_minor,submitted_minor,paid_minor,void_minor}. These are invoice-status totals, not a bank reconciliation report or recognized revenue.
IDs serialize as strings; dates are UTC ISO8601 or null. Successful mutations return HTTP 200. Authentication failures are 401, role denials 403, missing scoped objects 404, state/idempotency conflicts 409 and invalid input 422. No submitted amount or paid status can grant an entitlement. amount_minor/status are explicitly prohibited on invoice/payment mutations; amounts and status always come from server state.
Plan: {id,code,name,price_minor,currency:'BDT',interval:'month',max_providers,max_accounts,monthly_messages,is_active}. Code is globally unique lowercase letters/digits/underscore/hyphen, starts with a letter/digit, maximum 64 characters. Names have at most 120 characters.
Subscription: {id,service_id,plan_id,status,period_start,period_end,cancel_at_period_end,pending_invoice_id,entitlements,plan,billing}. entitlements is the approved limit snapshot; pending enrollment has null limits but billing.enabled=false, so it is not a free plan. plan is current catalog metadata and may differ from the approved snapshot. billing is the resolver result below. One subscription row exists per service; invoices preserve its historical plan/amount snapshots when that row later changes.
Invoice: {id,subscription_id,service_id,plan_id,plan_name,amount_minor,currency,status,created_at,paid_at,period_start,period_end,payment}. Status is open, submitted, paid or void. Price, currency, plan-name and limit snapshots are copied at issuance and have no update endpoint. Coverage dates are assigned only when approved. payment is the latest submission or null, with {id,method,reference,note,status,decision_note,submitted_at,decided_at}. Payment status is submitted, approved or rejected. Prior submissions remain in storage; the current API presents the latest one, not an audit-history browser.
| Method/path | Permission and request | Response |
|---|---|---|
GET /plans | Platform: all; service admin: active | Plan list |
POST /plans | Platform; {code,name,price_minor,max_providers?,max_accounts?,monthly_messages?,is_active?} | {data:plan} |
PATCH /plans/{id} | Platform; partial name/price_minor/limits/is_active; code/currency/interval prohibited | {data:plan} |
GET /subscriptions | Authorized service scope | Subscription list |
POST /subscriptions | {service_id,plan_id,client_request_id:UUID} | {data:subscription,invoice} |
POST /subscriptions/{id}/renew | Authorized scope; {client_request_id:UUID} | {data:subscription,invoice} |
POST /subscriptions/{id}/cancel | Authorized scope; no input | {data:subscription} |
GET /invoices | Authorized scope | Invoice list and totals |
POST /invoices/{id}/submit-payment | Authorized scope; {method,reference,note?,client_request_id:UUID} | {data:invoice,subscription} |
POST /invoices/{id}/approve-payment | Platform only; {decision_id:UUID,note?} | {data:invoice,subscription} |
POST /invoices/{id}/reject-payment | Platform only; {decision_id:UUID,note?} | {data:invoice,subscription} |
Payment method is a nonempty string up to 40 characters, trimmed and lowercased; reference is trimmed, nonempty and at most 120 characters. Notes have at most 1000 characters; notes do not support files. Use synthetic references in tests. No bank credentials, cards, passwords or other secrets belong in these fields.
State, renewal and retry behavior#
- Selecting an active plan creates an
openinvoice andpendingsubscription. Initial enrollment locks a service row before creating the subscription, so two requests cannot create separate subscriptions. An active paid subscription must renew its current plan; changing plan is supported after paid coverage ends and no unpaid invoice exists. An existing inactive subscription row is reused while past invoices remain intact. - Only one unpaid invoice may be attached to a subscription. Submitting a reference changes the invoice to
submitted; it grants no paid access. - Approval locks the service, subscription, invoice and pending submission in one transaction, writes the decision/audit and activates coverage. Rejection preserves the observed submission and reopens that invoice for a corrected submission. Approval/rejection without a pending submission is 409.
- Initial or lapsed coverage starts at approval time. An early approved renewal starts at the existing paid end and extends it by one calendar month with end-of-month overflow disabled. For example, 31 January 2028 becomes 29 February; its next month becomes 29 March. Subscription
period_startremains the beginning of continuous paid coverage; each paid invoice has its own coverage dates. Paid access ends exactly atperiod_end(exclusive). - Cancellation never refunds or removes history. It retains active access until the paid end, voids any pending invoice and keeps existing submissions as observations. A void invoice cannot be approved. Without paid coverage, cancellation is immediately effective. Repeating cancellation without a new pending invoice has no additional effect or audit row. Renewal may be requested after cancellation; access resumes/continues only after approval, which clears the cancellation flag. Cancelling again voids that new pending invoice.
The status resolver reports active while coverage is future, cancelled after cancelled coverage ends, payment_due for other lapsed paid subscriptions and pending for unapproved enrollment. There is no trialing implementation or scheduled charge worker. Approval applies the invoice's limit snapshot immediately, including on an early renewal; catalog edits alone do not change active limits.
Create/renew requests require stable UUID client_request_id; replay for the same service/plan or subscription returns current state and the same invoice. Payment submission retries additionally require the same actor, method, reference and note. Decision retries require the same UUID, invoice, action, actor and note and return current state without re-extending coverage or duplicating the audit. A UUID reused with different data returns 409. Replays may show later state transitions; they are not frozen HTTP-response snapshots. A different decision UUID cannot approve an already paid invoice. Unique approved-reference hashes prevent the same normalized method plus case-folded reference from paying two invoices; this is an application duplicate check, not external bank verification. Method aliases or incorrect receipt details still require human review. Conflicts roll back every invoice/subscription/audit change. Transaction deadlocks may retry up to three attempts before surfacing a failure; retry with the same UUID.
Entitlements and integration boundary#
App\Billing\BillingEntitlements::forService(string $serviceId) returns:
{
mode: 'legacy_unmetered' | 'subscription';
enabled: boolean;
status: 'legacy_unmetered' | 'pending' | 'active' | 'payment_due' | 'cancelled';
limits: {max_providers: number|null; max_accounts: number|null; monthly_messages: number|null};
usage: {providers: number; accounts: number; monthly_messages: number};
period_end: string|null;
}No subscription means explicit legacy-unmetered access, preserving existing services on deployment. A disabled/nonexistent service always has enabled=false. Enrolling a legacy service is an explicit switch to paid billing: it becomes pending and requires approval. Active provider and active service-account counts include service admins, sellers and customers; global admins have no fixed service. Monthly message usage counts durable messages for that service in the current UTC calendar month, including admin messages; it resets at the UTC month boundary rather than on the payment anniversary. Replays of a persisted message must not consume a second quota unit. Paid-limit changes never delete existing accounts/providers/messages.
The resolver reports policy and counts; it does not itself intercept endpoints. Central host enforcement must consume this contract, lock the same chat_services row before checking and persisting a limited write, and keep authentication, billing recovery and permitted history access reachable. Browser counters are not enforcement. Embedded hosts choose their own billing policy. No Reverb event alone grants or charges an entitlement. Coverage for the separate central enforcement integration is recorded in project status.
Storage, operations and evidence#
Forward migration 2026_10_07_000001_create_billing_tables.php adds chat_billing_plans, chat_billing_subscriptions, chat_billing_invoices, chat_billing_payments, chat_billing_audit. Foreign keys retain plan/subscription/ invoice relations; no production history deletion endpoint exists. Service and actor IDs are authoritative application references; services/accounts are disabled, not deleted. Approved reference and request/decision identifiers have unique indexes. Subscription locks plus the shared service lock serialize financial transitions with quota enforcement. Back up before production migration; do not reverse the migration to discard financial records during application rollback.
Audit rows contain actual actor, service, action, target, timestamp and identifiers, not copied references/notes or credentials. Payment records intentionally store references/notes and are available only through scoped billing authorization. Billing events are visible in Audit log → Event source → Billing and the combined all-event history through the console API. Service administrators see only their own service's events; global plan events are platform-only. The audit view omits receipt references, notes, monetary details and request/decision identifiers. No audit export, automatic retention, refunds, payment webhooks, multi-currency totals, tax receipts or statutory invoice compliance is claimed.
Run php artisan test --filter=BillingTest from examples/laravel-api for focused local SQLite verification: approval-only activation, immutable pricing/limits, retry conflicts, duplicate-reference rollback, rejection/resubmission, scope/role denial, month-end renewal, cancellation, expiry, archived plans, pagination and legacy/usage behavior. Real MySQL migration/locking/concurrency and approved production receipt evidence require separate operator verification; no live payment approvals were performed by these tests.
The focused local run passed 8 tests / 153 assertions, and scoped Pint checks passed. Laravel's route listing registered all 11 billing routes. These results verify the local implementation, not a live financial approval or production concurrency guarantee.