Skip to main content

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: stripeConfig hydrates 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 / upsert to 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โ€‹

VariableDescriptionRequired
STRIPE_SECRET_KEYPlatform secret key used when creating parent-account subscriptionsโœ…
APP_SECRETJWT signing key for marketplace phone provisioning (charge.service)โœ…
API_BASE_URLInternal router base URL for customer creation proxy callsโœ…
SETUP_PRODUCTStripe product ID for setup fees used in phone/listing bundlesโœ…
BASE_CURRENCYISO currency code used for OneBalance ledger conversionsโœ…

Key Librariesโ€‹

  • stripe โ€“ Official Stripe Node SDK (connected-account aware via stripeConfig).
  • 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โ€‹

  1. Ensure the parent account has Stripe OAuth credentials (stripe-check middleware blocks otherwise).
  2. Hit GET /v1/billing/overview with startDate/endDate to validate analytics connectivity.
  3. Use POST /v1/billing/payment-links with a CRM contact to generate a hosted invoice.
  4. Monitor tests/customer.test.js and tests/overview.test.js for 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.
๐Ÿ’ฌ

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM