Skip to content

Jer123-dev/Subscription-Management-Engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Subscription Management System

Event-Driven Web3 Subscription & Client Onboarding Gateway

Python Telegram Bot API aiogram CryptoCloud License

A production-grade Telegram subscription bot that processes crypto payments via an Event-Driven Webhook Architecture, secured behind an enterprise Nginx reverse proxy and strict firewall policies.


πŸ“ Architecture β€” The Event-Driven Webhook Model

This Architecture does not use on-chain RPC listeners or polling-heavy payment monitors as the primary payment detection mechanism. Instead, it implements a delegated, event-driven architecture where:

  1. Payment processing is offloaded to CryptoCloud, a specialized crypto payment gateway
  2. State transitions are triggered by webhooks β€” CryptoCloud pushes payment confirmations to our dedicated endpoint
  3. The bot reacts to events, not polls for them β€” a fundamentally more scalable and resource-efficient pattern

This is the same architectural pattern used by Stripe, PayPal, and every major SaaS payment integration. By delegating the complexity of multi-chain payment monitoring, confirmation counting, and exchange rate calculation to a purpose-built service, the architecture achieves:

  • Reliability: No missed payments due to RPC node failures or network partitions
  • Scalability: Webhook ingestion scales horizontally; no per-user polling loops eating CPU
  • Security: Payment secrets and wallet private keys never touch the application server
  • Maintainability: Payment logic changes are handled upstream; the bot only reacts to state events

Design Note: A backup polling loop exists as a redundancy layer for edge cases where webhooks may be delayed or dropped. This belt-and-suspenders approach ensures zero missed activations.


πŸ”’ Security & DevOps Posture

The Model's infrastructure demonstrates enterprise-grade security practices for protecting a production payment gateway:

Dedicated Webhook Domain

webhooks.any-domain.xyz  β†’  Nginx (443/SSL)  β†’  localhost:8080 (Python)

A dedicated subdomain isolates webhook traffic from all other services. This enables:

  • Independent SSL certificate management
  • Granular rate limiting and access control
  • Clean separation in monitoring and logging

Nginx Reverse Proxy

  • SSL/TLS termination via Let's Encrypt (Certbot)
  • Path-based routing: Only POST /cryptocloud_webhook is forwarded; all other paths return 444 (connection drop)
  • Rate limiting: 10 req/s per IP with burst allowance
  • Security headers: Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options
  • Default server catch-all: Unmatched domains/IPs are silently dropped

UFW Firewall Lockdown

Port Protocol Policy Purpose
22 TCP ALLOW SSH administration
80 TCP ALLOW Certbot challenges + HTTP→HTTPS redirect
443 TCP ALLOW Webhook ingestion (Nginx β†’ Python)
8080 TCP DENY Internal Python server (localhost only)

The internal Python webhook server on port 8080 is never exposed to the public internet. SQLite is a file-based database β€” it has no network port to attack.


πŸ”„ System Flow

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Client  │────▢│   Telegram   │────▢│  Python Backend  β”‚
β”‚ (User)   β”‚     β”‚  Bot API     β”‚     β”‚  (aiogram 3.x)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β”‚
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚  CryptoCloud Invoice β”‚
                                    β”‚  (Payment Gateway)   β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β”‚
                                    User pays via crypto
                                    (USDT BEP20, TRC20, etc.)
                                               β”‚
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚  CryptoCloud Webhook β”‚
                                    β”‚  POST /cryptocloud_  β”‚
                                    β”‚  webhook (HTTPS)     β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β”‚
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚   Nginx Reverse     β”‚
                                    β”‚   Proxy (443β†’8080)  β”‚
                                    β”‚   SSL Termination   β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β”‚
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚  Python Backend     β”‚
                                    β”‚  (aiohttp webhook)  β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β”‚
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚  SQLite State       β”‚
                                    β”‚  Update + Channel   β”‚
                                    β”‚  Access Granted     β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Detailed Flow:

  1. Client interacts with the Telegram bot via /start
  2. Bot presents subscription plans and generates a CryptoCloud invoice
  3. Client completes the crypto payment on CryptoCloud's hosted page
  4. CryptoCloud fires a webhook POST to https://webhooks.your-domain.xyz/cryptocloud_webhook
  5. Nginx terminates SSL, validates the request, and proxies to 127.0.0.1:8080
  6. Python backend parses the webhook, activates the subscription in SQLite, and generates a unique channel invite link
  7. Bot sends the invite link to the user via Telegram DM

πŸ“ Project Structure

Subscription-Management-Engine/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── bot.py                 # Bot, Dispatcher, Router initialization
β”‚   β”œβ”€β”€ handlers/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ user_commands.py       # /start, /myplan, terms, plan selection
β”‚   β”‚   β”œβ”€β”€ payment.py             # Payment verification + polling loop
β”‚   β”‚   β”œβ”€β”€ admin.py               # /activate, /edit, /export, referrer mgmt
β”‚   β”‚   β”œβ”€β”€ referral.py            # /referral, payout FSM, commission system
β”‚   β”‚   └── channel.py             # Invite links, join requests, expiry checker
β”‚   β”œβ”€β”€ database/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ connection.py          # SQLite connection factory (WAL mode)
β”‚   β”‚   β”œβ”€β”€ schema.py              # Table creation + column migrations
β”‚   β”‚   └── crud.py                # All CRUD operations with retry logic
β”‚   β”œβ”€β”€ webhooks/
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── cryptocloud.py         # CryptoCloud webhook handler (aiohttp)
β”‚   └── utils/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ config.py              # Environment variable loader (dotenv)
β”‚       β”œβ”€β”€ logger.py              # Centralized logging configuration
β”‚       └── retry.py               # SQLite retry decorator
β”œβ”€β”€ scripts/
β”‚   └── db_migrate.py              # Database migration CLI tool
β”œβ”€β”€ infrastructure/
β”‚   β”œβ”€β”€ nginx.conf                 # Nginx reverse proxy configuration
β”‚   └── ufw-setup.sh              # UFW firewall setup script
β”œβ”€β”€ main.py                        # Application entrypoint
β”œβ”€β”€ .env.example                   # Environment variable template
β”œβ”€β”€ .gitignore                     # Git ignore rules
β”œβ”€β”€ requirements.txt               # Python dependencies
└── README.md                      # This file

πŸ› οΈ Tech Stack

Layer Technology Purpose
Bot Framework aiogram 3.x Async Telegram Bot API client
Webhook Server aiohttp Lightweight async HTTP server for webhook ingestion
Database SQLite (WAL mode) Subscription state, user data, referral tracking
Payment Gateway CryptoCloud Delegated crypto payment processing
Reverse Proxy Nginx SSL termination, rate limiting, request routing
Firewall UFW (iptables) Port-level access control
SSL/TLS Let's Encrypt (Certbot) Free, auto-renewing SSL certificates
Config Management python-dotenv Environment-based secret management

πŸš€ Production Setup Guide

Prerequisites

  • Ubuntu 20.04+ VPS (e.g., DigitalOcean, Hetzner, AWS Lightsail)
  • A domain with DNS configured (e.g., webhooks.your-domain.xyz)
  • Python 3.10+
  • Nginx installed (sudo apt install nginx)

Step 1: Clone & Configure

# Clone the repository
git clone https://github.com/Jer123-Dev/Subscription-Management-Engine.git
cd Subscription-Management-Engine

# Create environment file from template
cp .env.example .env

# Fill in your production values
nano .env

Step 2: Python Virtual Environment

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

Step 3: Initialize Database

# Run schema migrations
python -m scripts.db_migrate migrate

Step 4: Configure Firewall (UFW)

# Make the script executable and run it
chmod +x infrastructure/ufw-setup.sh
sudo ./infrastructure/ufw-setup.sh

Step 5: Configure Nginx

# Copy Nginx config
sudo cp infrastructure/nginx.conf /etc/nginx/sites-available/payments-webhooks

# Enable the site
sudo ln -s /etc/nginx/sites-available/payments-webhooks /etc/nginx/sites-enabled/

# Remove default site (optional)
sudo rm /etc/nginx/sites-enabled/default

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

Step 6: SSL Certificate (Let's Encrypt)

# Install Certbot
sudo apt install certbot python3-certbot-nginx

# Obtain SSL certificate
sudo certbot --nginx -d webhooks.your-domain.xyz

# Verify auto-renewal
sudo certbot renew --dry-run

Step 7: Create Systemd Service

sudo tee /etc/systemd/system/payments.service > /dev/null <<EOF
[Unit]
Description=Subscription Bot
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/Subscription-Management-Engine
Environment="PATH=/home/ubuntu/Subscription-Management-Engine/.venv/bin"
ExecStart=/home/ubuntu/Subscription-Management-Engine/.venv/bin/python main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable payments
sudo systemctl start payments

# Check status
sudo systemctl status payments

Step 8: Register Webhook with CryptoCloud

In your CryptoCloud dashboard:

  1. Navigate to Project Settings β†’ Webhooks
  2. Set the webhook URL to: https://webhooks.your-domain.xyz/cryptocloud_webhook
  3. Save and verify with a test payment

Step 9: Verify Deployment

# Check bot is running
sudo systemctl status payments

# Check Nginx is serving
curl -I https://webhooks.your-domain.xyz/cryptocloud_webhook

# Monitor live logs
sudo journalctl -u payments -f

πŸ”§ Admin Commands

Command Description
/activate <user_id> <days> Manually activate a user's subscription
/edit <user_id> remove Revoke subscription and remove from channel
/edit <user_id> setdays <days> Reset subscription expiry
/edit <user_id> marktrial Mark trial as used
/edit <user_id> resettrial Reset trial availability
/export Export all users as CSV
/refree_add <id> <pct> Enroll a referral partner
/refree_remove <id> Deactivate a referral partner
/export_refree Export referrer stats as CSV

πŸ“Š Database Schema

-- Core subscription state
users (user_id, username, first_name, last_name, accepted_terms,
       trial_used, subscription_plan, subscription_expiry,
       nowpayments_invoice_id, invite_link, invoice_locked,
       cryptocloud_invoice_id, invite_hash, payment_processed, last_check)

-- Referral system
referrers (telegram_id, commission_pct, balance, is_active, created_at)
referrals (id, referrer_id, referred_id, joined_at, commission, status)
payout_requests (id, referrer_id, amount, wallet, requested_at, approved_at, is_paid)

πŸ“ License

Proprietary β€” All rights reserved.


🌐 Live Demo & Custom Infrastructure

Test the Live Gateway: Want to see the event-driven architecture and automated tier-routing in action? You can interact with the live production deployment of this subscription manager here: πŸ‘‰ Interact with the Live Bot

Open for Custom Builds: Looking to architect your own automated Web3 payment gateway, decentralized subscription engine, or scalable backend infrastructure? I build custom, high-availability revenue pipelines for Web3 founders and agencies.

My DMs are always open. Let's engineer your backend:


If this architecture template helped you secure your infrastructure or scale your backend operations, consider dropping a tip! Solana Wallet: [vHRCCSnkwEZHQkw9cApDJKWQvTKG7Z1fxrp23h9SH7Y]


Built with πŸ”₯ by Jerome β€” Demonstrating Event-Driven Payments Architecture, DevOps Security and Web3 Payment Integration

About

Engineered an event-driven Web3 payment gateway and subscription manager. Built with asynchronous Python, secured by an Nginx reverse proxy and hardened with strict zero-trust firewall routing.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors