{"id":51606166,"url":"https://github.com/mehediakash01/billing-system","last_synced_at":"2026-07-12T02:30:28.651Z","repository":{"id":359775279,"uuid":"1247440355","full_name":"mehediakash01/billing-system","owner":"mehediakash01","description":"A system With secure, stateless authentication, automated tier management, manual \u0026 automatic subscription lifecycles, and cryptographic webhook handlers to orchestrate seamless billing flows.","archived":false,"fork":false,"pushed_at":"2026-05-23T12:53:04.000Z","size":44,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-23T13:06:25.791Z","etag":null,"topics":["docker","express","mongodb","moongoose","nodejs","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mehediakash01.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-23T10:16:16.000Z","updated_at":"2026-05-23T12:55:34.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/mehediakash01/billing-system","commit_stats":null,"previous_names":["mehediakash01/billing-system"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/mehediakash01/billing-system","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehediakash01%2Fbilling-system","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehediakash01%2Fbilling-system/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehediakash01%2Fbilling-system/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehediakash01%2Fbilling-system/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mehediakash01","download_url":"https://codeload.github.com/mehediakash01/billing-system/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehediakash01%2Fbilling-system/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35380480,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-12T02:00:06.386Z","response_time":87,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","express","mongodb","moongoose","nodejs","typescript"],"created_at":"2026-07-12T02:30:27.838Z","updated_at":"2026-07-12T02:30:28.642Z","avatar_url":"https://github.com/mehediakash01.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SaaS Subscription Billing System Engine\n\nA robust, enterprise-grade subscription and billing engine built with **Node.js, Express, TypeScript, and MongoDB**. This system provides secure, stateless authentication, automated tier management, manual \u0026 automatic subscription lifecycles, and cryptographic webhook handlers to orchestrate seamless billing flows.\n\n---\n\n## 🚀 Core Technologies \u0026 Ecosystem\n\nThe engine is engineered for type-safety, rapid compilation, and reliable horizontal scale under heavy traffic:\n\n*   **Runtime \u0026 Language:** Node.js (v22-alpine) \u0026 TypeScript 6.x\n*   **Web Framework:** Express 5.x (optimized for robust routing and modern middleware workflows)\n*   **Database \u0026 ORM:** MongoDB \u0026 Mongoose ORM 9.x\n*   **Security \u0026 Encryption:**\n    *   Stateless sessions via **JSON Web Tokens (JWT)**.\n    *   Cryptographically-secure password hashing using **bcrypt**.\n    *   **HMAC-SHA256 signature verification** on Webhooks to ensure requests originate exclusively from authorized payment gateway providers.\n*   **Runtime Validation:** **Zod schemas** checking structural validity and input constraints on incoming requests.\n*   **Development Utilities:** `ts-node-dev` for hot-reloading compilation and file system change detection.\n*   **Logging:** Lightweight custom logging utility containing timestamps, structured contexts, and error traceback routing.\n\n---\n\n## 📂 Modular Folder Structure\n\nThe codebase adheres to a modular pattern. Business domain layers are encapsulated into isolated sub-modules inside the `module` directory, separating controllers, models, validations, and services from other unrelated domains.\n\n```text\nBilling-system/\n├── dist/                          # Compiled production JavaScript files\n├── src/\n│   ├── app.ts                     # Main Express Application setup \u0026 middleware mounts\n│   ├── server.ts                  # Server entrypoint (database setup, server instantiation, crash hooks)\n│   └── app/\n│       ├── config/                # Environment variables parsing and configuration object\n│       │   └── index.ts\n│       ├── errors/                # Global Application Error types and handlers\n│       │   └── AppError.ts\n│       ├── middlewares/           # Custom authentication, validation and logging middlewares\n│       │   ├── auth.ts\n│       │   ├── globalErrorHandler.ts\n│       │   └── ValidateRequest.ts\n│       ├── routes/                # Global router registry linking all API endpoints\n│       │   └── index.ts\n│       ├── utils/                 # General helpers (custom logger, catchAsync wrapper)\n│       │   ├── CatchAsync.ts\n│       │   ├── SendResponse.ts\n│       │   └── logger.ts\n│       └── module/                # Domain specific business modules\n│           ├── plan/              # Plan endpoints, model, schema validation, and services\n│           ├── subscription/      # Subscription purchasing, cancellation, and validation\n│           ├── user/              # User Authentication, password hashing, and JWT generation\n│           └── webhook/           # Signature checks and automated payment lifecycle hooks\n├── .env                           # Local environment variables configurations (git-ignored)\n├── .env.example                   # Template containing keys for setting up environment configs\n├── Dockerfile                     # Multi-stage production ready Docker packaging descriptor\n├── docker-compose.yml             # Local Multi-Container setup (Node Service + MongoDB)\n├── package.json                   # Dependencies, scripts and build configurations\n├── postman_collection.json        # Pre-configured API queries for Postman Client import\n└── tsconfig.json                  # Compiler configurations adjusted for robust build pipelines\n```\n\n---\n\n## 🔌 API Endpoints Catalog\n\nThe billing engine mounts all domain endpoints under the `/api/v1` namespace.\n\n### Authentication Module (`/api/v1/auth`)\n\n| Method | Endpoint | Authorization | Payload (JSON) | Description |\n| :--- | :--- | :--- | :--- | :--- |\n| `POST` | `/register` | Public | `{ \"name\", \"email\", \"password\", \"role\" }` | Creates a new user account inside the database. Valid values for role: `'client'` \\| `'admin'`. |\n| `POST` | `/login` | Public | `{ \"email\", \"password\" }` | Verifies login credentials and returns a stateless Access Token (JWT). |\n\n### Plans Module (`/api/v1/plans`)\n\n| Method | Endpoint | Authorization | Payload (JSON) | Description |\n| :--- | :--- | :--- | :--- | :--- |\n| `POST` | `/` | Admin Only | `{ \"name\", \"price\", \"durationInDays\", \"isActive\" }` | Registers a subscription tier option into the engine catalog. |\n| `GET` | `/` | Public | *None* | Retrieves all available active subscription tier options. |\n\n### Subscriptions Module (`/api/v1/subscriptions`)\n\n| Method | Endpoint | Authorization | Payload (JSON) | Description |\n| :--- | :--- | :--- | :--- | :--- |\n| `POST` | `/purchase` | Client Only | `{ \"planId\", \"autoRenew\" }` | Signs up the client for a subscription plan tier. Returns the subscription record. |\n| `PATCH`| `/:id/cancel` | Client Only | *None* | Toggles the active status or schedules the cancellation of the specific subscription contract. |\n\n### Webhook Gateway Module (`/api/v1/webhooks`)\n\n| Method | Endpoint | Headers Required | Payload (JSON) | Description |\n| :--- | :--- | :--- | :--- | :--- |\n| `POST` | `/payment-update` | `x-webhook-signature` | `{ \"event\", \"data\": { \"subscriptionId\" } }` | Integrates with the payment processors' webhooks. Updates status to `'active'` or `'expired'` dynamically. |\n\n*Webhook Signature Validation is calculated via HMAC-SHA256:* `crypto.createHmac('sha256', WEBHOOK_SECRET).update(JSON.stringify(req.body)).digest('hex')`.\n\n---\n\n## 🛠️ Local Development \u0026 Setup Setup Guidelines\n\nFollow these directions to stand up the local environment:\n\n### Prerequisites\n*   Node.js (v20+ recommended)\n*   MongoDB Instance (Local Community Server or MongoDB Atlas cluster connection string)\n\n### 1. Repository Setup\nClone the repository and install the development and core packages:\n```bash\ngit clone \u003crepository-url\u003e\ncd Billing-system\nnpm install\n```\n\n### 2. Configuration Settings\nCreate a `.env` file at the root level of the codebase. Copy the settings block below or duplicate and modify `.env.example`:\n```ini\nPORT=5000\nNODE_ENV=development\nMONGO_URI=mongodb://localhost:27017/subscription-billing\nJWT_ACCESS_SECRET=your_super_complex_random_jwt_access_secret_key_here\nJWT_ACCESS_EXPIRES_IN=1d\nBCRYPT_SALT_ROUND=12\nWEBHOOK_SECRET=your_cryptographically_secure_hmac_webhook_signing_key\n```\n\n### 3. Running Locally\nRun the server locally inside development mode:\n```bash\nnpm run dev\n```\nThe hot-reloader daemon (`ts-node-dev`) will spin up, watch your source directory for modifications, and output log logs directly into standard stdout.\n\n### 4. Compiling the Production Bundle\nTo compile and test the server using standard built JavaScript packages:\n```bash\n# Build the TypeScript files to JS\nnpm run build\n\n# Start the node server using the dist bundle\nnpm run start\n```\n\n---\n\n## 🐳 Docker Deployment Setup\n\nA multi-stage `Dockerfile` and `docker-compose.yml` configurations are available to bootstrap both the API server and database dependencies without manual installations:\n\n```bash\n# Spin up both MongoDB and the Billing API Engine containers in detached mode\ndocker-compose up -d --build\n```\nOnce initialized:\n*   The billing API service will dynamically bound and expose itself on host port `5000`.\n*   A persistent database volume (`mongo_billing_data`) will automatically save MongoDB state.\n\nTo check container operations and logs:\n```bash\ndocker-compose logs -f\n```\n\n---\n\n## 🛡️ Professional Production-Ready Features\n\nThe engine is packed with design paradigms that make it immediately drop-in ready for modern production environments:\n\n### 1. Robust Graceful Shutdown Flow\nThe HTTP Server intercepts crash and termination signals (`SIGTERM`, `uncaughtException`, `unhandledRejection`). Upon detection, the engine closes the active HTTP listener, stops processing new client requests, terminates the MongoDB connection cleanly via Mongoose, and closes process bindings safely:\n```typescript\nprocess.on('unhandledRejection', (reason, promise) =\u003e {\n  logger.error('Unhandled rejection detected.', { promise, reason });\n  if (server) {\n    server.close(() =\u003e process.exit(1));\n  } else {\n    process.exit(1);\n  }\n});\n```\n\n### 2. Cryptographic Integrity Guard on Webhooks\nTo protect business endpoints against counterfeit billing triggers or spoofed invoices, the Webhook Gateway strictly inspects `x-webhook-signature` header using `crypto` hashing to verify origin integrity before modifying database contracts.\n\n### 3. Schema Enforcement\nEvery single input request payload undergoes runtime deserialization and assertion checks via custom validation middlewares running Zod schemas. This completely blocks garbage parameters or script-injections from ever traversing near database drivers.\n\n### 4. Custom Structured Logger\nThe logger formats logs with high-resolution ISO timestamps, severity tiers (`INFO`, `WARN`, `ERROR`), and structured payload context dumps, allowing modern log aggregation tools (Elasticsearch, Datadog, Grafana Loki) to effortlessly scan, parse, and catalog app actions.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmehediakash01%2Fbilling-system","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmehediakash01%2Fbilling-system","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmehediakash01%2Fbilling-system/lists"}