Developers
How to Accept Crypto Payments in a Telegram Bot or Mini App
Set up a crypto payment gateway for Telegram bot checkouts and Mini Apps: Stars and TON rules, payment links, deposit addresses and TON Connect code.
Flexrix Pay··7 min read
To accept crypto in Telegram, your bot's backend creates a payment with a crypto payment gateway for Telegram bot checkouts, sends the customer a link or address, and waits for a signed webhook before delivering. Telegram's own rules decide which route you may use: digital goods sold inside Telegram must be paid in Telegram Stars, and any crypto feature inside a Mini App must run on TON through TON Connect. Plain bots without a Mini App have more freedom.
This guide covers those rules, then three working patterns: payment links from a bot, permanent deposit addresses for bot balances, and a TON checkout inside a Mini App.
Telegram's payment rules come first
Two Telegram documents shape every design decision. Read the current versions yourself, because they change.
Digital goods require Stars. Telegram's payments documentation says payments for digital goods and services must be carried out exclusively in Telegram Stars (currency code XTR). The Bot Platform Developer Terms add that such payments cannot be processed through third-party payment providers. The same documents say sellers of physical goods and services may use other currencies or payment providers.
Mini Apps must use TON for crypto. Telegram's blockchain guidelines for Mini Apps require Mini Apps to use the TON blockchain exclusively for blockchain functionality and to connect wallets only through the TON Connect SDK. The developer terms also say Mini Apps must not direct users to external websites where non-TON crypto assets are used. The guidelines state that regular bots without a Mini App component are exempt from these blockchain rules.
| What you build | What you sell | Payment route |
|---|---|---|
| Bot or Mini App | Digital goods or services | Telegram Stars |
| Plain bot (no Mini App) | Physical goods or services | Crypto payment link or deposit address, any network |
| Mini App | Physical goods or services | Crypto on TON only, via TON Connect |
How these rules apply to a particular business is not always obvious. This post is not legal advice; if your case is unclear, get professional advice.
What a crypto payment gateway for Telegram bot checkouts needs
Whatever route you pick, Telegram crypto payments have the same moving parts:
- Your backend, which holds the API keys and the order database. Never put payment API keys in bot client code or a Mini App.
- An order per purchase, with your own order id.
- A payment request created by the gateway: an invoice with an amount, an address and an expiry, or a permanent deposit address per user.
- A trustworthy payment signal. A signed webhook from the gateway tells you when a payment is final. Nothing the user says or the Mini App reports counts as proof.
- A message back to the user through the Bot API once the order is paid.
The examples below use the Flexrix Pay API, where every request is signed with HMAC-SHA256 using the headers X-FP-Key, X-FP-Timestamp, X-FP-Nonce and X-FP-Signature. The same structure works with most gateways. For the general website version of this flow, see how to add a crypto payment gateway to your website.
Pattern 1: a Telegram crypto payment bot that sends payment links
This is the simplest pattern for a plain bot selling physical goods or services. When the user taps "Buy", your backend creates an invoice and the bot replies with a button that opens the hosted payment page. The customer picks a coin and network there, scans a QR code or pays from their wallet, and returns to the chat.
First, the request signer, taken from the API reference:
import crypto from 'node:crypto';
function signed(keyId, secret, method, pathWithQuery, body = '') {
const ts = Math.floor(Date.now() / 1000).toString();
const nonce = crypto.randomBytes(18).toString('base64url');
const bodyHash = crypto.createHash('sha256').update(body).digest('hex');
const canonical = ['v1', ts, nonce, method.toUpperCase(), pathWithQuery, bodyHash].join('\n');
const sig = crypto.createHmac('sha256', secret).update(canonical).digest('hex');
return { 'X-FP-Key': keyId, 'X-FP-Timestamp': ts, 'X-FP-Nonce': nonce, 'X-FP-Signature': sig };
}Then create the invoice and send the link. Pricing in fiat without network and asset lets the customer choose the coin on the payment page; allowed_assets limits the choice, and metadata carries the chat id so the webhook can reply later:
const { FP_KEY_ID, FP_SECRET, BOT_TOKEN } = process.env;
async function startCheckout(chatId, orderId, priceUsd) {
const body = JSON.stringify({
foreign_id: orderId,
price_amount: priceUsd, // decimal string, e.g. "19.90"
price_currency: 'USD',
allowed_assets: ['USDT-TRON', 'USDT-BSC', 'USDT-TON', 'TON', 'BTC'],
expires_in: 1800, // 5 to 60 minutes
metadata: { chat_id: String(chatId) },
});
const res = await fetch('https://api.flexrixpay.com/v1/invoices', {
method: 'POST',
body,
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': `tg-invoice-${orderId}`, // 8-128 chars
...signed(FP_KEY_ID, FP_SECRET, 'POST', '/v1/invoices', body),
},
});
if (!res.ok) throw new Error((await res.json()).error.code);
const { invoice } = await res.json();
await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: `Order ${orderId}: ${priceUsd} USD. Tap below to pay in crypto.`,
reply_markup: { inline_keyboard: [[{ text: 'Pay with crypto', url: invoice.checkout_url }]] },
}),
});
}Re-sending the same foreign_id with the same content returns the existing invoice, so a user who taps "Buy" twice does not get two invoices.
Confirming the payment
Register an HTTPS webhook endpoint, verify every delivery, and only then mark the order paid and message the user. Flexrix Pay follows the Standard Webhooks format, so verification needs the raw request body:
import express from 'express';
const app = express();
const WHSEC = process.env.FP_WEBHOOK_SECRET; // whsec_...
function verifyWebhook(secret, headers, rawBody) {
const id = headers['webhook-id'], ts = Number(headers['webhook-timestamp']);
if (!id || !Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
const want = 'v1,' + crypto.createHmac('sha256', key).update(`${id}.${ts}.${rawBody}`).digest('base64');
return (headers['webhook-signature'] || '').split(' ').some((s) =>
s.length === want.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(want)));
}
app.post('/flexrixpay/webhook', express.raw({ type: 'application/json' }), (req, res) => {
if (!verifyWebhook(WHSEC, req.headers, req.body.toString('utf8'))) return res.status(400).end();
res.status(200).end(); // acknowledge fast, then process
const event = JSON.parse(req.body.toString('utf8'));
const { foreign_id, status, metadata } = event.data;
if (event.type === 'invoice.paid' || event.type === 'invoice.overpaid') {
// mark order paid in your database (idempotently, keyed on event.id), then:
notify(metadata.chat_id, `Payment received for order ${foreign_id}. Thank you!`);
} else if (event.type === 'invoice.underpaid') {
notify(metadata.chat_id, `We received less than the full amount for order ${foreign_id}. Our team will contact you.`);
}
});
function notify(chatId, text) {
return fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId, text }),
});
}Webhooks are retried if your endpoint is down, and delivery order is not guaranteed, so de-duplicate on the webhook-id and make status updates idempotent. If you prefer a no-code start, you can also create a payment link in the dashboard and paste it into the chat by hand; see how to create a crypto payment link.
Pattern 2: permanent deposit addresses for bot balances
Some bots keep a balance per user: a service that bills against prepaid credit, for example. Instead of an invoice per purchase, give each user a permanent deposit address. With Flexrix Pay that is one call, POST /v1/channels, with the network and your user id as foreign_id:
{ "network": "tron", "foreign_id": "tg-123456789" }The same user always gets the same address on that network, so the call is safe to repeat. Every transfer to it is detected, screened and credited, and your webhook receives deposit.credited with the foreign_id, asset, amount, fee, net and txid. Credit the user's in-bot balance from that event.
Two details matter on Telegram's favorite networks. On TON, deposit addresses are shared and each user gets a numeric comment (returned as destination_tag) that must be included in the transfer; without it, the payment cannot be matched automatically. The bot should show both the address and the comment and say plainly that the comment is required. On every network, transfers below the network's minimum deposit are recorded as below_minimum and not credited.
Pattern 3: TON payments in Telegram Mini Apps
For TON payments, Telegram Mini Apps have the strictest rules: inside a Mini App, crypto must stay on TON and wallets must connect through TON Connect. That rules out a payment page offering other networks or wallet connectors. Build the payment screen in your Mini App instead, with the invoice created on your backend.
Step 1: authenticate the user
When the Mini App opens, Telegram provides signed launch data, initData. Send the raw string to your backend and validate it before trusting the user id. The secret key is an HMAC-SHA256 of your bot token with the constant WebAppData as the key:
function validateInitData(initData, botToken, maxAgeSec = 3600) {
const params = new URLSearchParams(initData);
const hash = params.get('hash');
if (!hash) return false;
params.delete('hash');
const dataCheckString = [...params.entries()]
.map(([k, v]) => `${k}=${v}`).sort().join('\n');
const secretKey = crypto.createHmac('sha256', 'WebAppData').update(botToken).digest();
const calc = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest('hex');
const fresh = Date.now() / 1000 - Number(params.get('auth_date')) < maxAgeSec;
return fresh && calc.length === hash.length &&
crypto.timingSafeEqual(Buffer.from(calc), Buffer.from(hash));
}Step 2: create a TON invoice
Your backend creates the invoice with the TON network fixed:
{
"foreign_id": "tg-order-5531",
"network": "ton",
"asset": "TON",
"price_amount": "39.00",
"price_currency": "EUR",
"expires_in": 900,
"metadata": { "telegram_user": "123456789" }
}The response contains the crypto amount (locked at creation), the shared address, the numeric comment in destination_tag and expires_at. Return those to the Mini App.
Step 3: request the transfer through TON Connect
For a payment in Toncoin, the comment travels as a text payload: a cell that starts with a 32-bit zero opcode followed by the text, as the TON Connect docs describe. Using @ton/core and the TON Connect UI library:
import { beginCell, toNano } from '@ton/core';
const payload = beginCell()
.storeUint(0, 32) // text comment opcode
.storeStringTail(invoice.destination_tag)
.endCell();
await tonConnectUI.sendTransaction({
validUntil: Math.floor(Date.now() / 1000) + 600,
messages: [{
address: invoice.address,
amount: toNano(invoice.amount).toString(), // nanotons
payload: payload.toBoc().toString('base64'),
}],
});For USDT on TON, use asset: "USDT-TON". The message is then a jetton transfer sent to the payer's own jetton wallet, with your invoice address as the destination and the comment in the forward payload. The TON docs have a jetton transfer cookbook with the full layout. Note that USDT uses 6 decimals, so do not use toNano for the jetton amount. Test with small amounts first.
Step 4: confirm on the backend
Treat the TON Connect result only as "the user signed something." The order is paid when your webhook receives invoice.paid (or invoice.overpaid or invoice.underpaid). TON payments are typically credited in about a minute. Meanwhile, the Mini App can poll your own backend for the order status and show a "waiting for confirmation" state.
Edge cases to plan for
- Missing TON comment. A payment sent from outside your flow without the comment cannot be matched automatically. Flexrix Pay records it for manual review instead of crediting the wrong order. Ask the user for the transaction hash.
- Wrong amount. Underpayments and overpayments are still credited to your balance, and the invoice status tells you which happened. Decide in advance whether you ask for the rest or refund the difference by payout.
- Late payment. A payment that lands after the invoice expires is still credited and reported with
late: trueininvoice.payment_received. Have a policy for it. - No gas coin. A user holding USDT but no TON (or TRX on TRON) may be unable to pay the network fee. Say so on the payment screen.
- Fake tokens. Only the official Tether jetton on TON, and the standard USDT contracts elsewhere, are credited. Look-alikes are ignored.
FAQ
Can a Telegram bot accept crypto payments?
Yes, for physical goods and services. A plain bot can send payment links or deposit addresses on any network your gateway supports. Digital goods and services sold inside Telegram must use Telegram Stars.
Do Telegram Mini App payments have to use TON?
For crypto, yes. Telegram's blockchain guidelines require Mini Apps to use TON exclusively and to connect wallets through TON Connect. Digital goods in Mini Apps use Stars.
Is TON the same as Telegram Stars?
No. Stars are an in-app item that users buy inside Telegram, used for digital goods. Toncoin is the native coin of the TON blockchain, a separate network that Telegram requires Mini Apps to use for crypto.
How do I know a Telegram crypto payment is final?
Wait for a signed webhook from your gateway after the network confirms the payment. Never mark an order paid because the Mini App or the user says it was sent.
Key takeaways
- Digital goods sold inside Telegram must use Telegram Stars; a crypto gateway is for physical goods and services.
- Plain bots can send payment links or deposit addresses on any network; Mini Apps must use TON via TON Connect.
- Create invoices and addresses on your backend, keep API keys off the client and carry the chat id in metadata.
- Confirm payments only from verified webhooks, and plan for missing comments, wrong amounts and late payments.
Try it with Flexrix Pay
Flexrix Pay supports invoices, payment links and permanent deposit addresses on 12 networks, including USDT and TON on TON with comment-based matching, and sends signed webhooks for every status change. Create a free account to test a bot checkout, and find every field in the API reference.