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.
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:
- Payment processing is offloaded to CryptoCloud, a specialized crypto payment gateway
- State transitions are triggered by webhooks β CryptoCloud pushes payment confirmations to our dedicated endpoint
- 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.
The Model's infrastructure demonstrates enterprise-grade security practices for protecting a production payment gateway:
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
- SSL/TLS termination via Let's Encrypt (Certbot)
- Path-based routing: Only
POST /cryptocloud_webhookis forwarded; all other paths return444(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
| 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.
ββββββββββββ ββββββββββββββββ βββββββββββββββββββ
β 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:
- Client interacts with the Telegram bot via
/start - Bot presents subscription plans and generates a CryptoCloud invoice
- Client completes the crypto payment on CryptoCloud's hosted page
- CryptoCloud fires a webhook
POSTtohttps://webhooks.your-domain.xyz/cryptocloud_webhook - Nginx terminates SSL, validates the request, and proxies to
127.0.0.1:8080 - Python backend parses the webhook, activates the subscription in SQLite, and generates a unique channel invite link
- Bot sends the invite link to the user via Telegram DM
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
| 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 |
- 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)
# 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# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Install dependencies
pip install -r requirements.txt# Run schema migrations
python -m scripts.db_migrate migrate# Make the script executable and run it
chmod +x infrastructure/ufw-setup.sh
sudo ./infrastructure/ufw-setup.sh# 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# 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-runsudo 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 paymentsIn your CryptoCloud dashboard:
- Navigate to Project Settings β Webhooks
- Set the webhook URL to:
https://webhooks.your-domain.xyz/cryptocloud_webhook - Save and verify with a test payment
# 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| 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 |
-- 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)Proprietary β All rights reserved.
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:
- π¬ Telegram: @Jerrooooo
If this architecture template helped you secure your infrastructure or scale your backend operations, consider dropping a tip!
Solana Wallet: [vHRCCSnkwEZHQkw9cApDJKWQvTKG7Z1fxrp23h9SH7Y]