Skip to content

About

Embeddable, self-hosted subscription billing engine for Node.js

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Nomba Subscription Engine

Embeddable, self-hosted subscription billing engine for Node.js — plans, subscriptions, recurring payments via Nomba, retries, invoices, and webhooks.

🧪 Evaluating or judging this submission?

Go straight to docs/GUIDE.md — it's the test script. A 5-minute, copy-pasteable walkthrough that exercises the whole engine end-to-end (plans → subscriptions → billing → dunning → multi-tenancy → self-service portal → webhooks), with zero setup beyond Node.js: no Nomba credentials, no Postgres, no Redis.

⚠️ Nomba card tokenization is async. Recurring billing requires a one-time checkout flow to tokenize the customer's card. See Nomba Tokenization Flow below. Full API reference: developer.nomba.com.

Table of Contents

Features

  • Multi-tenant — every plan and subscription belongs to a Tenant; all reads/writes are tenant-scoped and a cross-tenant lookup returns "not found," never a leak
  • Plans — daily, weekly, monthly, yearly intervals with configurable interval counts
  • Subscriptions — create, cancel (immediate or at period end), auto-renew
  • Customer self-service portal — reference HTTP routes for a customer to view their own subscription/invoices, cancel, and swap their card, ownership-checked against (tenant, externalCustomerId)
  • Nomba payments — recurring charges via saved payment methods (pull-based model)
  • Dunning — configurable retry schedule (e.g. 1, 3, 7 days) with past_due status, cancel-or-pause on exhaustion, and a cancelAtPeriodEnd flag the billing worker actually enforces (stops renewal instead of charging once more)
  • Invoices — generated per successful payment attempt, queryable per subscription
  • Events & webhooks — HMAC-SHA256 signed delivery of subscription events to your application
  • Two databases — SQLite (zero-config, in-memory or file) and Postgres (production)
  • Two queue backends — DB polling (no dependencies) or BullMQ (Redis)
  • Concurrency safe — unique constraint guards against double-charge; FOR UPDATE SKIP LOCKED for workers
  • BYO infrastructure — bring your own DB connection and queue; engine never provisions resources

Run Locally

Not yet published to npm — clone the repo and build it locally:

git clone <this repo>
cd nomba-subscription-engine
pnpm install
pnpm run build          # compiles src/ -> dist/

All code samples below import from the local dist/ build (relative to the repo root), not a package name.

Peer dependencies

pnpm install above already pulls these in as dev dependencies for local use. If you later consume this engine from another project, install only what your deployment needs:

# SQLite (default, for dev/light usage)
npm install better-sqlite3

# Postgres (for production)
npm install pg

# Redis-backed queue (optional — otherwise uses DB polling)
npm install bullmq

All peer deps are optional. The engine falls back to SQLite in-memory and a no-op queue when nothing is provided.

Quick start

The engine is multi-tenant: every plan and subscription belongs to a Tenant (one per merchant/downstream product team using the engine). Create a tenant once and scope every plan/subscription call to its tenantId.

import { SubscriptionEngine } from "./dist/index.js";

// SQLite in-memory — no config needed
const engine = new SubscriptionEngine({
  webhook: { url: process.env.WEBHOOK_URL, secret: process.env.WEBHOOK_SECRET },
});

// Run migrations
await engine.migrate();

// Create a tenant (one per merchant — do this once and store id + apiKey)
const tenant = await engine.tenants.create({ name: "Acme Inc" });

// Create a plan, scoped to the tenant
const plan = await engine.plans.create(tenant.id, {
  name: "Pro Monthly",
  amountMinor: 1000, // 1000 kobo = NGN 10.00
  currency: "NGN",
  interval: "monthly",
});

// Create a subscription, scoped to the tenant
const sub = await engine.subscriptions.create(tenant.id, {
  externalCustomerId: "user_abc", // Your customer ID
  planId: plan.id,
  providerCustomerRef: "nomba_cus_xyz", // Nomba tokenized card key (see Nomba Tokenization Flow below)
});

// Cancel at period end
await engine.subscriptions.cancel(tenant.id, sub.id, { atPeriodEnd: true });

// Graceful shutdown
await engine.close();

tenant.apiKey is the credential your HTTP layer should require as Authorization: Bearer <apiKey> before trusting a caller's tenantId — see playground/server.mjs for a full reference implementation of that auth layer plus a customer self-service portal, or docs/GUIDE.md for a guided walkthrough.


Testing Locally (Reference Server)

The playground/ directory contains a ready-to-run HTTP server (playground/server.mjs) that exercises the engine end-to-end using SQLite in-memory and DB polling — no Redis, no external database, no Nomba credentials required. It demonstrates the full production shape: multi-tenant API-key auth, the customer self-service portal, dunning, and signed webhooks.

# 1. Build the engine (required — the server imports from dist/)
pnpm run build

# 2. Start the server (http://localhost:4000)
node playground/server.mjs

# Or use the combined script:
pnpm run playground:fresh

On boot it auto-creates a Demo Tenant and prints its API key — copy that key, every route below except /health and POST /tenants requires it as Authorization: Bearer <key>:

🚀  Subscription Engine — Reference Server
    http://localhost:4000
    Database: SQLite (in-memory, resets on restart)

Demo tenant created — use this for every authenticated request below:
  Authorization: Bearer sk_...

A Postman collection is included at playground/subscription-engine.postman_collection.json — import it for all routes pre-configured with auto-saving variables (tenant API key, plan ID, subscription ID).

For the full step-by-step walkthrough (plans → subscriptions → dunning → portal → webhooks, judge-oriented) see docs/GUIDE.md. Quick taste:

KEY="sk_..."   # from the server's startup log

# Create a plan
curl -s -X POST http://localhost:4000/plans -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"Pro Monthly","amountMinor":100000,"currency":"NGN","interval":"monthly"}' | jq

# Create a subscription
curl -s -X POST http://localhost:4000/subscriptions -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -d '{"externalCustomerId":"user_abc123","planId":"<plan id>","providerCustomerRef":"tok_sandbox_test"}' | jq

Interval options

interval Description
daily Every day
weekly Every week
monthly Every month
yearly Every year

Use intervalCount to multiply (e.g. "interval": "monthly", "intervalCount": 3 = every 3 months).


Usage with Postgres

Create the DB client explicitly and share it between the engine and the polling adapter:

import pg from "pg";
import { SubscriptionEngine } from "./dist/index.js";
import { PostgresDriver } from "./dist/adapters/postgres/driver.js";
import { PollingAdapter } from "./dist/adapters/queue/polling-adapter.js";

const pool = new pg.Pool({
  connectionString: "postgres://user:pass@host:5432/mydb",
});
const db = new PostgresDriver(pool);
const adapter = new PollingAdapter(db, 60_000);

const engine = new SubscriptionEngine({
  db,
  queue: adapter,
  webhook: { url: "https://myapp.com/billing-events", secret: "whsec_abc" },
});

await engine.migrate();
engine.startWorker();

For SQLite with a file path:

import { SubscriptionEngine } from "./dist/index.js";
import { SqliteDriver } from "./dist/adapters/sqlite/driver.js";
import { PollingAdapter } from "./dist/adapters/queue/polling-adapter.js";

const db = new SqliteDriver({ path: "./data/billing.db" });
const adapter = new PollingAdapter(db, 60_000);

const engine = new SubscriptionEngine({
  db,
  queue: adapter,
  webhook: { url: process.env.WEBHOOK_URL, secret: process.env.WEBHOOK_SECRET },
});

Architecture

Architecture Diagram

Configuration

SubscriptionEngineOptions

Option Type Default Description
db string | DatabaseDriver SQLite :memory: Connection URL or driver instance
queue QueueAdapter No-op (no worker) PollingAdapter, BullMQAdapter, or custom
webhook WebhookConfig — (required) URL + secret for event delivery
tablePrefix string sub_ Prefix for all engine tables
retryPolicy RetryPolicy [1, 3, 7], cancel Retry schedule + exhaustion action
nomba NombaConfig — Nomba API credentials (clientId, clientSecret, accountId)

Database URLs (convenience shorthand)

For simple setups without a queue adapter, you can pass a connection string directly:

// SQLite in-memory (default when db is omitted)
const e1 = new SubscriptionEngine({ webhook });

// SQLite file
const e2 = new SubscriptionEngine({
  db: "sqlite://./data/billing.db",
  webhook,
});

// Postgres
const e3 = new SubscriptionEngine({
  db: "postgres://user:pass@localhost:5432/db",
  webhook,
});

// Pre-configured driver (for DI or sharing with PollingAdapter)
const db = new PostgresDriver(pool);
const e4 = new SubscriptionEngine({ db, webhook });

Migrations

The engine owns its schema. Migrations live in migrations/ and are applied via the engine:

// Auto-detects dialect from the configured db
await engine.migrate();

// Or specify an explicit migrations directory
await engine.migrate("./migrations/postgres");

Workers

Without a queue adapter, the engine logs a warning and does nothing. Start background billing explicitly:

import pg from "pg";
import { SubscriptionEngine } from "./dist/index.js";
import { PostgresDriver } from "./dist/adapters/postgres/driver.js";
import { PollingAdapter } from "./dist/adapters/queue/polling-adapter.js";

// Create the DB driver first — share it between the adapter and engine
const pool = new pg.Pool({ connectionString: "postgres://..." });
const db = new PostgresDriver(pool);

// DB polling (no Redis needed)
const poller = new PollingAdapter(db, 60_000);

const engine = new SubscriptionEngine({ db, queue: poller, webhook });
engine.startWorker();
import pg from "pg";
import { SubscriptionEngine } from "./dist/index.js";
import { PostgresDriver } from "./dist/adapters/postgres/driver.js";
import { BullMQAdapter } from "./dist/adapters/queue/bullmq-adapter.js";
import { Queue } from "bullmq";

const pool = new pg.Pool({ connectionString: "postgres://..." });
const db = new PostgresDriver(pool);

const bullAdapter = new BullMQAdapter(new Queue("billing"));
const engine = new SubscriptionEngine({ db, queue: bullAdapter, webhook });
engine.startWorker();

Nomba tokenization flow

Nomba requires a one-time checkout to tokenize the customer's card before recurring charges can work.

import { NombaProvider } from "./dist/index.js";

const nomba = new NombaProvider({
  clientId: process.env.NOMBA_CLIENT_ID,
  clientSecret: process.env.NOMBA_CLIENT_SECRET,
  accountId: process.env.NOMBA_ACCOUNT_ID,
  callbackUrl: "https://myapp.com/nomba-callback",
});

// 1. Create a checkout order that tokenizes the card
const { checkoutLink, orderReference } = await nomba.createCheckoutOrder({
  customerEmail: "customer@example.com",
  amountMinor: 5000, // First payment + tokenization
  currency: "NGN",
  customerId: "user_abc",
});

// 2. Redirect customer to checkoutLink — they pay and Nomba
//    sends a `payment_success` webhook with `tokenizedCardData.tokenKey`

// 3. When creating the subscription, use the tokenKey as providerCustomerRef
const sub = await engine.subscriptions.create(tenant.id, {
  externalCustomerId: "user_abc",
  planId: plan.id,
  providerCustomerRef: "token_key_from_webhook",
});

// 4. Future billing will call NombaProvider.charge() with the tokenKey

Event delivery

Events are stored in sub_subscription_events and delivered via webhook:

const delivered = await engine.deliverEvents();
console.log(`Delivered ${delivered} events`);

API

Every plans/subscriptions method takes tenantId as its first argument. A lookup for a resource owned by a different tenant behaves identically to a nonexistent one (null from findById, an error from cancel) — the API never confirms cross-tenant existence.

Tenants

Method Description
engine.tenants.create(input) Create a tenant, returns it with a fresh apiKey
engine.tenants.findByApiKey(apiKey) Resolve a tenant from an API key (for HTTP auth)
engine.tenants.findById(id) Get tenant by ID

Plans

Method Description
engine.plans.create(tenantId, input) Create a pricing plan for a tenant
engine.plans.findById(tenantId, id) Get plan by ID (null if not this tenant's)
engine.plans.list(tenantId, filter?) List a tenant's plans (filterable)

Subscriptions

Method Description
engine.subscriptions.create(tenantId, input) Create a new subscription
engine.subscriptions.findById(tenantId, id) Get subscription by ID (null if not this tenant's)
engine.subscriptions.cancel(tenantId, id, options?) Cancel (immediate or at period end)

Engine

Method Description
engine.migrate(dir?) Apply pending schema migrations
engine.startWorker() Start background billing loop
engine.handleBillingJob(job) Process a single billing job
engine.deliverEvents() Deliver pending events via webhook
engine.close() Close database connections

Events

Event type Trigger
subscription.created New subscription created
subscription.cancelled Subscription cancelled
payment.success Charge succeeded
payment.failed Charge failed (with retry info)

Running Tests

Tests use in-memory fakes — no database or external service required.

# Install dev dependencies (includes better-sqlite3, pg, bullmq, vitest)
pnpm install

# Run all unit tests
pnpm test

# Watch mode (re-runs on file changes)
pnpm run test:watch

# Type-check without emitting
pnpm run lint

All tests live in tests/unit/ and cover:

File What it tests
engine.test.ts Plan/subscription CRUD, cancel, tenant isolation, worker startup, cancelAtPeriodEnd enforcement
billing.test.ts Successful billing, retry scheduling, exhaustion actions
entities.test.ts Period computation, validation rules
concurrency.test.ts Double-charge prevention via unique constraints
polling-adapter.test.ts DB polling tick, due-subscription discovery

License

MIT

About

Embeddable, self-hosted subscription billing engine for Node.js

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages