How to Build a Telegram Bot with Automated 0% Fee UPI Payments in Python & Node.js

Production engineering guide for building Telegram VIP channel and digital credit bots using FastAPI, httpx, atomic SQLite/PostgreSQL UTR locking, and webhook verification.

Why Manual UPI Verification Fails in Telegram Commerce

Indian Telegram ecosystems process thousands of daily purchases for paid study communities, coding bootcamps, SaaS AI credits, and digital memberships. Asking members to pay a static QR and forward screenshots to an admin bot fails for three reasons: moderators sleep while bots run 24/7, image-editing tools fake 12-digit UTR numbers easily, and manual checks destroy instant gratification right after payment.

By pairing your Telegram bot backend (Python aiogram/FastAPI or Node.js Telegraf) with UPIGateway.dev, every checkout session receives a unique order_id, an automated hosted checkout link (`https://upigateway.dev/pay/...`), and server-verified UTR confirmation at 0% MDR.

End-to-End Bot Payment State Machine

  1. Bot presents inline package buttons (`PRO_30D`, `VIP_90D`, `CREDITS_100`) mapped exclusively to authoritative server-side INR prices.
  2. Bot inserts a local database row `(order_id, telegram_user_id, expected_amount, status='PENDING')` BEFORE contacting any external payment host.
  3. Backend calls `POST https://upigateway.dev/api/create-order` using server environment secret `UPIGATEWAY_USER_TOKEN` and receives HTTP 201 with `result.payment_url`.
  4. Bot sends the buyer an InlineKeyboardButton URL opening `result.payment_url` plus an inline 'Verify Payment' fallback button.
  5. Either when `UPIGateway-Webhook-Dispatcher/2.0` posts to your webhook endpoint OR when the buyer taps 'Verify Payment', your backend runs `POST /api/check-order-status` to verify `status === 'SUCCESS'`, `txnStatus === 'COMPLETED'`, `amount >= expected_amount`, and unused `utr`.
  6. Backend updates the row atomically (`WHERE status = 'PENDING'`) and sends a private single-use invite link or credits wallet balance.

Production FastAPI + Anti-Replay SQLite Starter (`bot.py`)

import os
import sqlite3
import time
import httpx
from fastapi import FastAPI, HTTPException, Request

TOKEN = os.environ["UPIGATEWAY_USER_TOKEN"]
CATALOG_INR = {"PRO_30D": 199, "VIP_90D": 499, "CREDITS_100": 99}

db = sqlite3.connect("tg_orders.db", check_same_thread=False)
db.execute("""
CREATE TABLE IF NOT EXISTS bot_orders (
  order_id TEXT PRIMARY KEY,
  telegram_user_id INTEGER NOT NULL,
  expected_amount REAL NOT NULL,
  status TEXT NOT NULL DEFAULT 'PENDING',
  utr TEXT UNIQUE,
  created_at INTEGER NOT NULL
)
""")
db.commit()
app = FastAPI()

@app.post("/tg/create-checkout")
async def create_checkout(telegram_user_id: int, sku: str, mobile: str = "9999999999"):
    amount = CATALOG_INR.get(sku)
    if amount is None:
        raise HTTPException(status_code=400, detail="Unsupported SKU")
    order_id = f"TG_{telegram_user_id}_{int(time.time() * 1000)}"
    db.execute(
        "INSERT INTO bot_orders VALUES (?, ?, ?, 'PENDING', NULL, ?)",
        (order_id, telegram_user_id, float(amount), int(time.time())),
    )
    db.commit()
    async with httpx.AsyncClient(timeout=15) as client:
        r = await client.post("https://upigateway.dev/api/create-order", json={
            "user_token": TOKEN,
            "amount": str(amount),
            "order_id": order_id,
            "customer_mobile": mobile,
            "redirect_url": f"https://yourdomain.com/tg/return?order_id={order_id}",
            "remark1": sku,
            "remark2": str(telegram_user_id),
        })
        data = r.json()
    if not data.get("status"):
        raise HTTPException(status_code=502, detail=data.get("message", "Gateway error"))
    return data["result"]

Webhook Verification & Duplicate Click Race Prevention

async def verify_and_fulfill(order_id: str) -> dict:
    row = db.execute("SELECT expected_amount, status FROM bot_orders WHERE order_id = ?", (order_id,)).fetchone()
    if not row:
        raise HTTPException(status_code=404, detail="Unknown order")
    if row[1] == "SUCCESS":
        return {"fulfilled": True, "already_processed": True}

    async with httpx.AsyncClient(timeout=15) as client:
        verify = await client.post(
            "https://upigateway.dev/api/check-order-status",
            json={"user_token": TOKEN, "order_id": order_id},
        )
        res = verify.json()

    result = res.get("result") or {}
    if (
        res.get("status") is True
        and result.get("status") == "SUCCESS"
        and result.get("txnStatus") == "COMPLETED"
        and float(result.get("amount") or 0) >= float(row[0])
        and result.get("utr")
    ):
        try:
            cur = db.execute(
                "UPDATE bot_orders SET status = 'SUCCESS', utr = ? WHERE order_id = ? AND status = 'PENDING'",
                (str(result["utr"]), order_id),
            )
            db.commit()
            return {"fulfilled": cur.rowcount == 1, "utr": result["utr"]}
        except sqlite3.IntegrityError:
            return {"fulfilled": False, "reason": "duplicate_utr"}
    return {"fulfilled": False, "status": result.get("status", "PENDING")}

Security Rules for Production Telegram Payment Bots

Threat VectorMitigation Inside Bot Backend
User Double-Taps 'Check Status' During WebhookConditional SQL UPDATE `WHERE status = 'PENDING'` returns `rowcount == 1` once
Reused 12-Digit UTR Across Multiple Users`utr TEXT UNIQUE` constraint + UPIGateway PostgreSQL UTR anti-replay registry
Partial Payment Intent Edit (₹1 for ₹499)Reject `status === false` / `FLAGGED_UNDERPAID` and verify `amount >= expected_amount`
Timeout on Telegram Mobile WebViewProvide fallback `check-order-status` button so stalled browsers can verify reliably

Related Integration Guides & Developer Resources

Explore more technical articles, code examples, and architecture guides on our official blog. Automate your Indian payment collection at zero percent fees with UPIGateway.dev.

We provide comprehensive developer documentation, ready-to-deploy SDKs for PHP and Node.js, and plug-and-play e-commerce plugins for WordPress and WooCommerce. Build modern payment checkout flows with direct bank settlement and full financial autonomy.

Back to Blog Index | Engineering Reports | View API Documentation | Explore Pricing Plans