developer

Build a Paid Telegram Community Bot with Instant UPI Verification

Learn how to build a paid Telegram subscription bot in Python. Automate member invite links, verify UPI payments via instant webhooks, and kick expired users.

GS Gaurav Sharma Automation Engineer & Python Specialist 2 min read
Build a Paid Telegram Community Bot with Instant UPI Verification guide
telegram paid channel bot upi monetize telegram group upi india telegram upi payment bot python telegram bot api python fintech automation

In India, Telegram has become a primary hub for paid premium communities, stock market research desks, crypto alpha signals, UPSC study groups, and digital education masterclasses.

However, most community managers still manage paid memberships manually: asking buyers to send payment screenshots on WhatsApp, manually verifying bank balances, and individually generating private invite links. This manual workflow suffers from fake screenshot fraud, high administrative labor, and delayed user onboarding.

Here is the complete engineering tutorial for building an automated Paid Telegram Community Bot in Python that verifies UPI payments in real time and manages channel memberships.


The Telegram Creator Economy in India

The scale of Telegram monetization in India is immense:

The Traditional Manual Bottleneck:
User pays via QR ──► Sends screenshot to Admin ──► Admin sleeps (6-hour delay)
                                                          │
User complains ◄── Admin wakes up & creates link ◄────────┘
(High churn, fake screenshot fraud, and missed sales)

The Automated Bot Pipeline:
User taps /subscribe ──► Bot generates Dynamic UPI ──► User pays via PhonePe / GPay
                                                              │
User added to channel in < 3 seconds ◄── Webhook verified ◄───┘

By connecting your bot to VyaparGateway, payments land directly in your bank account with 0% transaction fees, completely eliminating third-party aggregator cuts.


System Architecture: Telegram Bot & Payment Engine

[Telegram User] ──► Commands: `/subscribe`
      │
      ▼
[Python Bot Engine (Aiogram / FastAPI)]
      │
      ├─ 1. Calls VyaparGateway API: Creates dynamic order
      │
      ├─ 2. Sends user Inline Keyboard with Deep Link Intent
      │     [👉 Tap to Pay ₹999 on GPay / PhonePe]
      │
      ▼ (User Pays on Phone)
[Bank / VyaparGateway Webhook] ──► POST `/webhook/payment`
      │
      ├─ 3. Verifies HMAC SHA-256 signature
      ├─ 4. Calls Telegram Bot API: `createChatInviteLink(member_limit=1)`
      └─ 5. DMs the user their single-use private link

To prevent a paying user from leaking the channel link to WhatsApp or Reddit groups, always enforce single-use restrictions via the Telegram Bot API:

invite_link = await bot.create_chat_invite_link(
    chat_id=CHANNEL_ID,
    name=f"Sub_{user_id}",
    member_limit=1,            # Locks link to exactly 1 join
    expire_date=int(time.time()) + 900  # Link expires in 15 minutes
)

Complete Python Implementation with FastAPI & Aiogram (Code)

Here is a production-ready, asynchronous Python service running FastAPI and Aiogram 3:

import hmac
import hashlib
import time
import os
import httpx
from fastapi import FastAPI, Request, HTTPException
from aiogram import Bot, Dispatcher, types
from aiogram.filters import Command
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton

BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID"))
VYAPAR_KEY = os.getenv("VYAPAR_API_KEY")
VYAPAR_SECRET = os.getenv("VYAPAR_WEBHOOK_SECRET")

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
app = FastAPI()

@dp.message(Command("start", "subscribe"))
async def start_handler(message: types.Message):
    user_id = message.from_user.id
    amount = 999  # Subscription price in INR

    # Generate Dynamic Order on VyaparGateway
    async with httpx.AsyncClient() as client:
        res = await client.post(
            "https://api.vyapargateway.com/v1/orders/create",
            json={
                "amount": amount,
                "orderId": f"TG_{user_id}_{int(time.time())}",
                "customerName": message.from_user.full_name or "Subscriber",
                "orderNote": f"Telegram Pro Access for {user_id}"
            },
            headers={"Authorization": f"Bearer {VYAPAR_KEY}"}
        )
        data = res.json()

    intent_url = data.get("upi_intent_url")

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="⚡ Pay ₹999 via UPI Intent", url=intent_url)]
    ])

    await message.answer(
        f"👋 Welcome {message.from_user.first_name}!\n\n"
        "Unlock full access to the Private Research Channel.\n"
        "Click the button below to pay via GPay, PhonePe, or Paytm.\n"
        "Your private invite link will be issued immediately upon payment.",
        reply_markup=keyboard
    )

@app.post("/webhook/payment")
async def handle_payment_webhook(request: Request):
    signature = request.headers.get("x-vyapar-signature")
    body = await request.body()

    # 1. Cryptographic HMAC validation
    expected_sig = hmac.new(
        VYAPAR_SECRET.encode(), body, hashlib.sha256
    ).hexdigest()

    if signature != expected_sig:
        raise HTTPException(status_code=401, detail="Invalid signature")

    payload = await request.json()
    
    if payload.get("status") == "SUCCESS":
        order_id = payload.get("orderId")
        # Extract telegram user ID from orderId format "TG_<user_id>_<timestamp>"
        user_id = int(order_id.split("_")[1])

        # 2. Generate 1-time expiring invite link
        invite = await bot.create_chat_invite_link(
            chat_id=CHANNEL_ID,
            member_limit=1,
            expire_date=int(time.time()) + 900
        )

        # 3. Direct Message the private invite link
        await bot.send_message(
            chat_id=user_id,
            text=f"✅ Payment Confirmed! (Bank UTR: {payload.get('utr')})\n\n"
                 f"Here is your private, one-time link to join:\n{invite.invite_link}\n\n"
                 "⚠️ Note: This link expires in 15 minutes and can only be used once."
        )

    return {"status": "ok"}

Automated Membership Expiry and User Pruning

To handle recurring monthly subscriptions without manual oversight, run a daily cron job that queries your database for expired subscriptions:

# Daily task: Prune expired subscribers
async def prune_expired_members():
    expired_users = await db.get_expired_subscribers()
    for user in expired_users:
        try:
            # Kick user from private channel
            await bot.ban_chat_member(chat_id=CHANNEL_ID, user_id=user.id)
            await bot.unban_chat_member(chat_id=CHANNEL_ID, user_id=user.id) # Unban so they can rejoin later
            await bot.send_message(
                user.id, 
                "⚠️ Your subscription has expired. Run /subscribe to renew your membership."
            )
        except Exception as e:
            print(f"Failed to prune user {user.id}: {e}")

Deploying this architecture gives community operators a fully autonomous, fraud-proof digital subscription engine that collects 100% of revenue directly into their bank accounts.

Direct answers

Frequently asked questions

How do I monetize a private Telegram channel in India?
You can deploy a custom Telegram bot connected to VyaparGateway. When users click 'Subscribe', the bot generates an instant dynamic UPI payment link. Upon automated webhook verification, the bot issues a unique single-use invite link.
Can a user forward the paid Telegram invite link to their friends?
No. By using Telegram's Bot API method `createChatInviteLink` with `member_limit=1` and `expire_date` set to 15 minutes, the invite link permanently expires the exact second the paying user joins.
Why avoid using manual screenshot verification for Telegram groups?
Manual screenshot verification is easily cheated using spoof APKs (fake payment generators) and requires 24/7 administrative oversight. Automated webhook bots verify payments against bank UTR records in sub-second time.

Build your payment flow

Explore the API and browser-only merchant tools.

Create UPI checkout orders, verify signed events, or test the free calculators and generators without exposing credentials.