aibillingkit
v0.1.0
Published
CLI starter for AIBillingKit, a plug-and-play AI SaaS billing and usage backend.
Downloads
175
Maintainers
Readme
AIBillingKit
AIBillingKit is a modular Java/Spring Boot backend infrastructure layer for AI SaaS products. It gives founders a plug-and-play starting point for authentication, organizations, API keys, provider-key storage, usage metering, credits, billing abstractions, webhooks, audit logs, and a normalized AI gateway.
Who It Is For
AI SaaS teams that want to ship product features without rebuilding billing, credits, quota checks, provider routing, key management, and admin APIs for every new app.
Architecture
The project starts as a modular monolith under com.aibillingkit and is intentionally organized by product capability:
auth,security,userorganization,tenantapi_key,provider,gatewayusage,credits,plan,subscription,billingwebhook,notification,audit,admincommon,config
Controllers stay thin. Business logic lives in services. Persistence is handled by Spring Data JPA repositories. Provider and billing integrations are interfaces with mock implementations so real OpenAI, Anthropic, Gemini, OpenRouter, and Stripe adapters can be added without changing the rest of the app.
Features
- JWT auth with refresh tokens and BCrypt password hashing
- Organization and member management with tenant isolation
- Platform API keys hashed at rest and shown only once
- AI provider keys encrypted at rest
- Mock AI provider adapters for OpenAI, Anthropic, Gemini, and OpenRouter
- Gateway endpoints for chat, embeddings, and images
- Usage records with token counts, latency, model, provider, cost, and credits charged
- Credit wallet with ledger entries and pessimistic locking
- Billing-ready plans and mock Stripe checkout/portal/webhook abstraction
- Paystack-ready checkout and webhook abstraction for African and global payments
- Subscription model prepared for lifecycle events
- Redis-backed rate limiting with local fallback
- Outgoing webhook endpoint storage and HMAC signing helper
- Audit log storage and admin APIs
- Flyway migrations, Docker Compose, Actuator, Prometheus metrics, Swagger/OpenAPI
Setup
Prerequisites:
- Java 21
- Maven 3.9+
- Docker and Docker Compose
Install With npm
AIBillingKit also ships as an npm CLI so teams can bootstrap the backend without manually cloning the repository:
npx aibillingkit init my-ai-saas
cd my-ai-saas
cp .env.example .env
docker compose up --buildThe generated starter uses Docker Compose and builds the Spring Boot backend from the public GitHub repository.
Run infrastructure:
docker compose up -d postgres redis rabbitmqRun the app locally:
cp .env.example .env
mvn spring-boot:runSwagger UI:
http://localhost:8080/swagger-ui.htmlHealth and metrics:
http://localhost:8080/actuator/health
http://localhost:8080/actuator/prometheusDocker
Run everything:
docker compose up --buildThe API will be available at http://localhost:8080.
Billing Providers
Set BILLING_PROVIDER=mock for local development.
Set BILLING_PROVIDER=paystack to use the Paystack provider:
BILLING_PROVIDER=paystack
PAYSTACK_SECRET_KEY=sk_live_or_test_key
PAYSTACK_WEBHOOK_SECRET=sk_live_or_test_keyPaystack webhook endpoint:
POST /api/v1/billing/webhooks/paystackThe provider verifies the x-paystack-signature header using HMAC SHA-512.
Tests
mvn testThe test profile uses H2 for fast local integration tests. The build includes Testcontainers dependencies for adding PostgreSQL-backed integration tests as the project grows.
Main Endpoints
POST /api/v1/auth/registerPOST /api/v1/auth/loginPOST /api/v1/auth/refresh-tokenPOST /api/v1/organizationsPOST /api/v1/organizations/{organizationId}/api-keysPOST /api/v1/organizations/{organizationId}/provider-keysPOST /api/v1/gateway/chatPOST /api/v1/gateway/embeddingsPOST /api/v1/gateway/imagesGET /api/v1/organizations/{organizationId}/usageGET /api/v1/organizations/{organizationId}/creditsGET /api/v1/plansPOST /api/v1/admin/plansPOST /api/v1/organizations/{organizationId}/billing/checkoutPOST /api/v1/organizations/{organizationId}/webhooksGET /api/v1/organizations/{organizationId}/audit-logs
Gateway Example
Create an API key, store the returned rawKey, then call:
curl -X POST http://localhost:8080/api/v1/gateway/chat \
-H "Content-Type: application/json" \
-H "X-API-Key: aibk_your_raw_key" \
-H "Idempotency-Key: request-123" \
-d '{
"organizationId": "00000000-0000-0000-0000-000000000000",
"provider": "OPENAI",
"model": "gpt-4.1-mini",
"input": "Write a short welcome email",
"metadata": {
"feature": "email-generator",
"customerId": "customer_123"
}
}'API Key Flow
- Register and login.
- Create an organization.
- Fund the credit wallet through the admin adjustment endpoint.
- Create a platform API key.
- Store the raw key immediately; only the hash is persisted.
- Send gateway requests with
X-API-Key.
Provider Key Flow
- Add a provider key with
POST /api/v1/organizations/{organizationId}/provider-keys. - The raw key is encrypted before storage.
- Gateway requests select the matching provider key for the requested provider.
- Mock adapters currently simulate provider responses; real adapters can use the same
AiProviderAdaptercontract.
Billing Flow
Plans are managed through admin endpoints. Billing is exposed through a BillingProvider interface and implemented by MockStripeBillingProvider. Replace that class with a real Stripe implementation when production credentials and webhook validation are available.
Credits Flow
Credits belong to an organization wallet. Gateway requests estimate credits from token usage, deduct from the wallet inside a transaction, and store a ledger entry. Wallet updates use pessimistic locking to avoid negative balances under concurrent usage.
Security Notes
- Platform API keys are SHA-256 hashed and never returned after creation.
- Provider keys are encrypted with AES-GCM.
- JWTs carry user ID, email, and role.
- Organization access is checked for tenant-scoped resources.
- Gateway endpoints support both JWT and API key authentication.
- Redis rate limiting is used where available and fails open for local development.
Roadmap
- Real OpenAI, Anthropic, Gemini, and OpenRouter adapters
- Real Stripe checkout, portal, and signed webhook validation
- PostgreSQL Testcontainers suite for concurrency and locking tests
- Quota policies by plan, model, API key, and billing cycle
- Webhook retry worker with exponential backoff
- Admin dashboard frontend
Open Source
AIBillingKit is released under the MIT License so anyone can use, modify, self-host, and build commercial AI SaaS products on top of it.
Useful project files:
Contributing
Keep modules cohesive, use constructor injection, add tests for tenant boundaries and money/credit behavior, and avoid returning raw secrets from any API response after creation.
