Billing Module
๐ฏ Overviewโ
The Billing module owns every Stripe-backed financial workflow exposed by the Internal API. It brokers customer and subscription lifecycle events, orchestrates one-off purchases for marketplace add-ons, hydrates analytics dashboards, and keeps local data stores in sync with Stripe through webhook ingestion. The module consolidates domain logic behind dedicated services and utilities while controllers remain thin HTTP adapters.
๐ Directory Structureโ
internal/api/v1/billing/
โโโ index.js # Router registration and shared middleware
โโโ controllers/ # Express controllers (request/response glue)
โ โโโ charge.controller.js # Marketplace checkout orchestration
โ โโโ customer.controller.js # Customer, invoice, and payment method endpoints
โ โโโ overview.controller.js # Revenue analytics endpoints
โ โโโ payment-intent.controller.js # Payment intent purchase flows
โ โโโ payment-link.controller.js # Ad-hoc invoice + hosted link creation
โ โโโ payout.controller.js # Payout summaries and drilldowns
โ โโโ product.controller.js # Product and price catalogue management
โ โโโ webhook.controller.js # Stripe webhook ingestion
โ โโโ index.js # Controller exports
โโโ routes/ # Route definitions + middleware binding
โ โโโ charge.route.js
โ โโโ customer.route.js
โ โโโ overview.route.js
โ โโโ payment-intent.route.js
โ โโโ payment-link.route.js
โ โโโ payout.route.js
โ โโโ product.route.js
โ โโโ webhook.route.js
โ โโโ index.js
โโโ services/ # Business logic (Stripe + Mongo orchestration)
โ โโโ charge.service.js
โ โโโ customer.service.js
โ โโโ overview.service.js
โ โโโ payment-intent.service.js
โ โโโ payment-link.service.js
โ โโโ payout.service.js
โ โโโ product.service.js
โ โโโ webhook.service.js
โ โโโ index.js
โโโ middlewares/
โ โโโ stripe-check.js # Ensures account has connected Stripe keys
โ โโโ validate.js # Payload validation wrapper
โโโ validations/ # Joi schema definitions per route surface
โ โโโ charge.validation.js
โ โโโ custom.validation.js # Dynamic schema builder for linking configs
โ โโโ customer.validation.js
โ โโโ overview.validation.js
โ โโโ payment-intent.validation.js
โ โโโ payment-link.validation.js
โ โโโ payout.validation.js
โ โโโ product.validation.js
โ โโโ index.js
โโโ utils/ # Stripe + CRM helpers shared by services
โ โโโ add-mapping.js # CRM contact mapping transforms
โ โโโ ApiError.js # Normalised API error factory
โ โโโ index.js
โ โโโ pick.js # Light projection helper used in queries
โ โโโ stripe-account.js # OAuth account lookup utilities
โ โโโ stripe-config.js # Stripe SDK configuration (per connected account)
โโโ tests/
โโโ customer.test.js
โโโ overview.test.js
โโโ payout.test.js
โโโ product.test.js
โโโ fixtures/
โโโ customer.js
โโโ overview.js
โโโ payout.js
โโโ product.js
๐๏ธ MongoDB Collectionsโ
๐ Detailed Schema: See Database Collections Documentation
billing.chargesโ
- Purpose: Stores enriched charge payloads emitted by Stripe webhooks for reporting.
- Model:
shared/models/billing-charge.js - Primary Use: Read-heavy analytics (gross/net volume, success counts).
billing.customersโ
- Purpose: Local snapshot of Stripe customers for linking and analytics.
- Model:
shared/models/billing-customer.js - Primary Use: Read/write during webhook sync, link to CRM contacts.
billing.subscriptionsโ
- Purpose: Tracks subscription lifecycle metadata from Stripe.
- Model:
shared/models/billing-subscription.js - Primary Use: Aggregations powering overview metrics and CRM linking.
billing.disputesโ
- Purpose: Logs disputes and balance transaction deltas.
- Model:
shared/models/billing-dispute.js - Primary Use: Net volume adjustments, dispute count analytics.
billing.refundsโ
- Purpose: Tracks refunds for revenue reconciliation.
- Model:
shared/models/billing-refund.js - Primary Use: Deduct refunds from net volume analytics.
billing.productsโ
- Purpose: Cache of Stripe products to avoid repeated API lookups.
- Model:
shared/models/billing-product.js - Primary Use: Hydrated by overview analytics when catalogue cache miss occurs.
billing.notesโ
- Purpose: Stores account-scoped customer notes within the billing workspace.
- Model:
shared/models/billing-notes.js - Primary Use: CRUD via customer service endpoints and CSV export.
Supporting Collectionsโ
_accounts(shared/models/account.js) โ Validates ownership and parent account context.queues(shared/models/queues.js) โ Enqueues follow-up jobs (contact linking, checkout side effects)._store.prices/_store.products(shared/models/store-price.js,shared/models/store-product.js) โ Marketplace catalogue used by checkout logic.onebalance/onebalance-usage_logsโ Balance ledger for sub-accounts.crm.contacts(shared/models/contact.js) โ Synchronises Stripe customers to CRM.support.*collections โ Open conversations when payments complete via webhook service.
๐๏ธ Architecture Overviewโ
Key Responsibilities:
- Serve REST endpoints for customer, invoice, subscription, checkout, and payout operations.
- Bridge connected-account Stripe API calls with account-specific OAuth tokens.
- Generate finance dashboards via Mongo/Stripe aggregations (overview service).
- Keep Mongo caches consistent with Stripe through webhook upserts.
- Trigger downstream automations (Queue Manager, Support socket events) after key billing events.
Design Decisions:
- ๐งฉ Service Layer Isolation: All Stripe calls and Mongo pipelines live in
services/to keep controllers testable. - ๐ Connected Account Context:
stripeConfighydrates Stripe SDK with the requesting accountโs OAuth token to avoid global state. - ๐ Analytics via Aggregation: Overview metrics aggregate raw collections to avoid storing precomputed stats.
- ๐ Webhook Idempotency: Webhook service uses
findOneAndUpdate/upsertto guard against duplicate deliveries. - ๐งต Queue Offloading: Expensive or asynchronous actions (store fulfilment, conversations) are pushed to queues to keep API latency low.
๐ Submodulesโ
Analytics & Reportingโ
- ๐ Overview Service โ Sales KPIs, gross/net volume, dispute analytics, payout summaries.
Customer & Billing Recordsโ
- ๐ Customer Service โ Stripe customer CRUD, invoices, payment methods, subscriptions, CRM linking.
- ๐ Webhook โ Stripe event ingestion and Mongo sync.
Commerce & Checkoutโ
- ๐ Charge โ Marketplace checkout via direct charges for add-on products.
- ๐ Payment Intent Service โ Payment Intent-based top-ups and purchases.
- ๐ Payment Link Service โ Generates hosted invoices and short links.
Catalogue & Payoutsโ
- ๐ Product Service โ Stripe product/price management.
- ๐ Payout Service โ Payout listing, detail drilldowns, and balance transaction summaries.
๐ Data Flowโ
flowchart TB
UI[DashClicks UI] -->|REST| Router
Router --> Middleware
Middleware --> Controllers
Controllers --> Services
Services -->|Connected account key| Stripe
Services -->|Aggregations| Mongo[(MongoDB)]
Services --> QueueManager
Stripe --> Webhooks
Webhooks --> WebhookService
WebhookService --> Mongo
WebhookService --> SupportSockets[(Support Sockets)]
classDef ext fill:#f0f4ff,stroke:#3b6ae6;
class Stripe,SupportSockets ext;
๐ Configuration & Dependenciesโ
| Variable | Description | Required |
|---|---|---|
STRIPE_SECRET_KEY | Platform secret key used when creating parent-account subscriptions | โ |
APP_SECRET | JWT signing key for marketplace phone provisioning (charge.service) | โ |
API_BASE_URL | Internal router base URL for customer creation proxy calls | โ |
SETUP_PRODUCT | Stripe product ID for setup fees used in phone/listing bundles | โ |
BASE_CURRENCY | ISO currency code used for OneBalance ledger conversions | โ |
Key Librariesโ
stripeโ Official Stripe Node SDK (connected-account aware viastripeConfig).moment/moment-timezoneโ Date windowing for analytics queries.mongooseโ Aggregations and CRUD across billing collections.json2csvโ CSV export for billing notes (customer service).axiosโ Internal API proxying and phone number lookups.
๐ Quick Startโ
- Ensure the parent account has Stripe OAuth credentials (
stripe-checkmiddleware blocks otherwise). - Hit
GET /v1/billing/overviewwithstartDate/endDateto validate analytics connectivity. - Use
POST /v1/billing/payment-linkswith a CRM contact to generate a hosted invoice. - Monitor
tests/customer.test.jsandtests/overview.test.jsfor regression coverage when extending services.
Requirements Coverageโ
- โ Customer & Checkout Flows โ Documented under dedicated service pages linked above.
- โ Analytics โ Overview service doc details aggregations and growth calculations.
- โ Webhooks & Sync โ Webhook service doc explains idempotent upserts and downstream side effects.