In this tutorial we add crypto payments to a Telegram bot written in aiogram 3. The bot issues a $1 invoice, the buyer picks which cryptocurrency to pay with, and the seller receives USDT. Once the invoice is paid, our webhook handler verifies the signature and sends the buyer an invite to a private channel. Everything runs on a testnet, so you don't need real money.
Creating an invoice and receiving a webhook is only half the job. Most of this article is about the other half: the things that break payment bots after launch. The same webhook arrives twice, but the product must be delivered once. A paid invoice still has to be matched against the order. A request to create an invoice times out, the buyer sends /buy again, and that must not end in a second payment for the same access. Invite links get forwarded to friends. And some buyers have no wallet at all and want to pay straight from an exchange.
For payments we use TgPay Crypto, a custodial crypto wallet that runs as a Telegram Mini App and has a Merchant API for bots. It's our own service, so besides the integration we also cover its fees and limitations.
The finished bot is live on the testnet, and you can try it before reading on: tgpaycrypto_demo_bot.
What you need
You need Python 3.10 or newer and aiogram 3. It pulls in aiohttp, which we use for the webhook handler.
pip install aiogram
Create a bot with BotFather and add it to your private channel as an administrator with the right to invite users. You also need a public HTTPS address for the webhooks; during development, any tunnel to a local port will do.
The Merchant API token comes from the testnet. Open tgpaycrypto_testnet_bot and, in the Mini App, go to "More → Merchant API → Create app". The token is shown only once, so copy it right away. The home screen has a "Get test coins" button. It's the buyer who needs the test funds, so a second Telegram account comes in handy.

In the app settings, set the webhook URL to https://<your-tunnel>/tgpay/webhook and, in the Webhook section, tap "Create secret". The wallet asks for your PIN and then shows a key that looks like whsec_…. Webhooks are signed with it.

Put everything into environment variables:
export BOT_TOKEN=... # from @BotFather export TGPAY_API_TOKEN=... # the app token export TGPAY_WEBHOOK_SECRET=whsec_... export CHANNEL_ID=-100... # the private channel ID
A thin API wrapper
Every method we need is called the same way: a POST with a JSON body and the token in the TgPayCrypto-API-Token header. The response always looks like {"ok": true, "result": ...}, so the whole wrapper fits in one function:
import asyncio import hashlib import hmac import json import os import time from decimal import Decimal from aiohttp import ClientSession, web from aiogram import Bot, Dispatcher from aiogram.filters import Command from aiogram.types import ChatJoinRequest, InlineKeyboardButton, InlineKeyboardMarkup, Message API = "https://testnet.tgpaycrypto.com/pay/api" # production: https://app.tgpaycrypto.com/pay/api TGPAY_TOKEN = os.environ["TGPAY_API_TOKEN"] SIGNING_KEY = hashlib.sha256(os.environ["TGPAY_WEBHOOK_SECRET"].encode()).digest() CHANNEL_ID = int(os.environ["CHANNEL_ID"]) PRICE_USD = "1" # a string! The API rejects a JSON number bot = Bot(os.environ["BOT_TOKEN"]) dp = Dispatcher() http: ClientSession # created in main() orders = {} # order_id -> order; use a database in production, of course seen = set() # update_id of every webhook already processed buyers = set() # user_id of everyone who has paid for access async def tgpay(method: str, **params): async with http.post(f"{API}/{method}", json=params, headers={"TgPayCrypto-API-Token": TGPAY_TOKEN}) as resp: data = await resp.json() if not data["ok"]: raise RuntimeError(f"{method}: {data['error']}") return data["result"]
Issuing an invoice
On /buy we create an order and issue an invoice for it. The first lines of the handler check whether access has already been bought; we'll come back to them at the end:
@dp.message(Command("buy")) async def buy(message: Message): user_id = message.from_user.id # Before invoicing, find out whether this account already has access member = await bot.get_chat_member(CHANNEL_ID, user_id) if member.status in ("creator", "administrator", "member"): await message.answer("You already have access. There's no need to pay again.") return if user_id in buyers: # paid but never joined, or left the channel await message.answer("Your access is already paid for. Here's the invite again:", reply_markup=await invite_keyboard()) return order_id = f"order-{user_id}-{message.message_id}" orders[order_id] = {"user_id": user_id, "status": "new"} invoice = await tgpay( "createInvoice", currency_type="fiat", fiat="USD", amount=PRICE_USD, # priced in dollars swap_to="USDT", # whatever the buyer pays with, we receive USDT description="Private channel access", payload=order_id, # comes back in the webhook unchanged client_invoice_id=order_id, # retrying won't create a second invoice expires_in=3600, # one hour to pay allow_comments=False, # the payment screen shows only the amount and the assets ) kb = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text=f"Pay ${PRICE_USD}", url=invoice["pay_url"]), ]]) await message.answer("Your invoice is ready. I'll send the invite once it's paid.", reply_markup=kb)
The price is in dollars (currency_type="fiat"), and the wallet works out the crypto amount at the rate in effect when the buyer pays. The buyer chooses what to pay with; you can narrow the list with accepted_assets. The swap_to parameter turns on automatic conversion: someone pays in BTC or GRAM, and USDT is credited to the app balance, so the seller doesn't have to hold volatile assets or watch the rates.
The API accepts amounts only as decimal strings, to avoid losing precision to floating point. An amount sent as a number is rejected.
client_invoice_id is our own order ID. If the response is lost to a timeout, you can repeat the same call and get the same invoice back. We put the same ID into payload: it comes back in the webhook and tells us which order was paid. From the response we need pay_url, the link that opens the invoice in the Mini App.
Receiving the webhook
After the payment, a POST request arrives at the webhook URL. Here is a real event from the testnet, with the fields we don't use removed:
{
"update_id": 123,
"update_type": "invoice_paid",
"request_date": "2026-11-25T09:26:21.123456Z",
"payload": {
"invoice_id": 43,
"status": "paid",
"currency_type": "fiat",
"fiat": "USD",
"amount": "1",
"paid_asset": "GRAM",
"paid_amount": "1.076257938",
"fee_asset": "GRAM",
"fee_amount": "0.016143869",
"swapped_to": "USDT",
"swapped_output": "0.980175",
"payload": "order-..."
}
}A $1 invoice was paid in GRAM, the fee was taken in the same asset, the rest was converted, and 0.980175 USDT was credited to the app balance.
The TgPayCrypto-API-Signature header carries an HMAC-SHA256 of the raw body, keyed with the SHA-256 hash of the signing secret. We verify the signature before we even look at the JSON, because anyone can send a POST to our address:
async def webhook(request: web.Request):
raw = await request.read() # the raw bytes, not json.dumps(json.loads(...))
expected = hmac.new(SIGNING_KEY, raw, hashlib.sha256).hexdigest()
got = request.headers.get("TgPayCrypto-API-Signature", "").strip().lower()
if not hmac.compare_digest(expected.encode(), got.encode()):
return web.Response(status=401)
update = json.loads(raw)
if update["update_id"] in seen: # the same event delivered again
return web.Response(text="ok")
seen.add(update["update_id"])
if update["update_type"] == "invoice_paid":
asyncio.create_task(fulfil(update["payload"])) # we have 10 seconds to respond
return web.Response(text="ok")There are two easy mistakes to make here. The signature covers the bytes exactly as they came over the wire: if you parse the body and serialize it again, the whitespace and key order change and the signature no longer matches. And the comparison has to go through hmac.compare_digest. A plain == takes longer the more leading characters match, so an attacker can work out the signature from response times.
If the server doesn't answer with a 2xx within 10 seconds, the platform sends the same event again with the same update_id, which is why we remember processed events in seen. To keep the example short, they live in memory and fulfillment runs as a background task. If that task fails after the 200 response, this handler won't retry it: the event is already marked as seen. In a production bot, save the event to the database before responding, in the same transaction that changes the order status, and separately make sure that access was actually granted.
Matching the payment to the order
A valid signature only proves that the event came from the payment service. It doesn't prove that our order was paid at our price: the price may have changed while the invoice was waiting, and the same app may be issuing invoices for other products. So we check the status, the currency and the price, and only then send the invite:
async def fulfil(invoice: dict):
order = orders.get(invoice.get("payload"))
if not order or order["status"] != "new":
return
# Is the invoice paid, and for the price we asked?
if invoice["status"] != "paid" or invoice.get("fiat") != "USD":
return
if Decimal(invoice["amount"]) != Decimal(PRICE_USD):
return
order["status"] = "paid"
buyers.add(order["user_id"])
text = f"Payment received: {invoice['paid_amount']} {invoice['paid_asset']}."
if invoice.get("swapped_to") == "USDT":
text += f" The seller was credited {invoice['swapped_output']} USDT."
await bot.send_message(order["user_id"], text, reply_markup=await invite_keyboard())We compare prices as Decimal rather than as strings, because "1" and "1.00" are the same amount. There's no need to check the crypto amount, and nothing to check it against: the wallet calculated it, while our price is one dollar. What the buyer paid is in paid_asset and paid_amount; what the seller received is in swapped_output. If the conversion hasn't finished by the time the webhook arrives, the swapped_* fields are empty, which is why the line about the credited amount is conditional.
Sending the invite
The simplest invite is a single-use link. But a link can be forwarded, and we also need to be able to issue it again if the buyer didn't join in time. So our link doesn't let anyone straight in. It creates a join request, and the bot approves it only for the account that placed the order:
async def invite_keyboard():
# The link doesn't admit anyone directly: it creates a join request
link = await bot.create_chat_invite_link(
CHANNEL_ID, creates_join_request=True, expire_date=int(time.time()) + 3600)
return InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text="Join the channel", url=link.invite_link),
]])
@dp.chat_join_request()
async def join_request(request: ChatJoinRequest):
# Approve only an account with a paid order
if request.chat.id == CHANNEL_ID and request.from_user.id in buyers:
await request.approve()
else:
await request.decline()The buyer sends a join request, and the bot approves it automatically. Somebody else can still pay the invoice, since the invoice link can be forwarded too, but access goes to the account that sent /buy.
Now for the first lines of /buy. When we tested the bot without that check, a second /buy issued a second invoice, and it was promptly paid. To the payment service these are two separate orders: one invoice can't be paid twice, but two different invoices are two payments, and the service has no idea they are for the same product. Only the seller knows what has already been sold. So before calling createInvoice we ask Telegram via getChatMember whether the person is already in the channel, and check whether they have a paid order. Otherwise we'd have to refund the second payment.
This check only guards against paying twice. Until access is paid for, our simplified code issues a new invoice on every /buy, whereas the demo bot shows the previous one.
All that's left is to run the webhook server and the bot's polling in one process:
async def main():
global http
http = ClientSession()
app = web.Application()
app.router.add_post("/tgpay/webhook", webhook)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "0.0.0.0", 8080).start()
# Join requests aren't among the default updates, so request them explicitly
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
if __name__ == "__main__":
asyncio.run(main())In this example orders, seen and buyers live in memory; in a production bot they are database tables. Since webhook delivery isn't guaranteed, it's also worth reconciling with getInvoices?status=paid every few minutes. The demo bot does all of this: SQLite, reconciliation and re-sending invites. Its code is in the repository.
Testing it
Start the bot, send /buy from the second account and tap the button. The invoice opens in the testnet Mini App, with the amount in dollars and a choice of assets to pay with.

Pick an asset and confirm, and a couple of seconds later the bot replies: "Payment received: 1.076257938 GRAM. The seller was credited 0.980175 USDT." Under the message is a "Join the channel" button. Tap it and send a join request; the bot approves it, and you're in. Sending /buy again from this account no longer issues an invoice.
We ran the code from this article against stubs standing in for Telegram and the API. On the testnet, we tested paying and joining the channel with the demo bot, which is the full version of this code.
If the invite doesn't arrive, first check that the webhook URL points exactly at your handler: the platform doesn't follow redirects, and a 3xx response counts as a failure. If the bot doesn't react to the join request, check that it was started with the allowed_updates from main() and has the right to invite users to the channel.
What we left out
Two API features didn't make it into the bot, so we'll just mention them. An invoice can be paid by a transfer to an address, from an exchange or any wallet, without Telegram or an account. You turn this on in the app settings, and an invoice paid this way arrives as the same invoice_paid event. The API also has an MCP server for AI agents, which works on the testnet too. The example uses neither; see the documentation for details.
Fees and limitations
The service takes 1.5% of every paid invoice, whether it's paid from the wallet or by a transfer to an address. The fee comes out of what the app receives, in the asset the buyer paid with; the buyer pays exactly the invoice amount. If you refund a payment, the fee isn't returned.
Automatic conversion isn't free either: what's left after the fee is converted at the wallet's rate, which includes a spread, 1.5% at the time of writing. When a $1 invoice is paid in anything other than USDT, the seller gets about 0.97 USDT. The testnet spread is smaller, which is why the example above came out at 0.98. If the buyer pays in USDT, there's no conversion and 0.985 USDT is credited to the app balance.
The service is custodial: it holds the keys, and the app's funds are held inside TgPay Crypto. You have to trust the operator with your funds; in return, payments from the wallet are instant and carry no network fee. KYC isn't required when you first sign in, but it may be requested under AML rules, including when you create a merchant app.
Withdrawing from the balance to an external address has a fee: at the time of writing, 4 USDT on TRON and 1.5 USDT on TON.
Wrapping up
The bot in this article is for learning: it keeps orders in memory and forgets them on restart. A production bot needs a database, a way to re-send invites after failures, and regular reconciliation of payments. The full SQLite example in the repository has all three.
The documentation is at docs.tgpaycrypto.com, and there are Python, Node.js and curl examples in the merchant-api repository.