Blog

How to take crypto payments in a Telegram bot

CoinStackUpdated 12 min read
Integrations

A Telegram bot takes crypto payments by creating a checkout on your server for each order, sending the customer the checkout link as a button, and delivering once a signed webhook confirms the payment. Under 200 lines of Python with requests and Flask cover it. Check Telegram's developer terms against your product first: they set which kinds of sales can use a third-party payment link.

Which sales can a Telegram bot take outside Telegram Stars?

Section 6 of Telegram's Bot Platform Developer Terms splits sales in two.

For physical goods and services, Telegram stays out of the money: "Telegram does not process payments for physical goods and services", and a developer "can choose a third-party payment provider at your discretion and according to their availability in your regions of interest."

For digital goods and services the rule is the opposite. Section 6.2 says "transactions for digital goods and services cannot be processed through third-party payment providers" and that "all transactions pertaining to digital goods and services must be executed exclusively through the exchange of Telegram Stars". A bot found using other payment systems for digital goods can be made "inaccessible from store versions of Telegram" or removed from the platform.

What counts as digital is not defined by Telegram itself. The terms defer to Apple's and Google's definitions of goods "that must be sold via in-app purchases", which can change. Apple's App Review Guidelines, section 3.1.3(e), describe the other side: "If your app enables people to purchase physical goods or services that will be consumed outside of the app, you must use purchase methods other than in-app purchase". Section 3.1.3(f) lets a free companion app for web hosting skip in-app purchase only "provided there is no purchasing inside the app".

So a bot that sells coffee, hardware or printed goods fits section 6.1. Read the terms against your own product and confirm with a lawyer before you build. The example below sells physical goods.

What are the ways to get paid in a Telegram bot?

There are 4 routes.

RouteWhat the buyer pays withWho holds the money
Telegram StarsStars, bought through Apple or Google in-app purchaseTelegram shows your Stars in a balance it says is not your property; you receive rewards for them
Telegram Payments for physical goodsA card, Apple Pay or Google Pay, in Telegram's payment screenThe payment provider you connect, such as Stripe
Walt Pay (formerly Wallet Pay)A balance in the Walt wallet, formerly Wallet in TelegramWalt, which holds funds for 48 hours by default
A crypto checkout linkAny wallet or exchange account, on the network the buyer choosesDepends on the gateway

Telegram's own payment screen for physical goods is card-based, and its documentation is clear that "Telegram does not process payments from users"; the connected provider handles card details. Stars are the only way the terms allow for digital goods. The Stars terms add that all sales of Stars are final, and Telegram does not refund unwanted purchases.

Walt Pay is run by TG Wallet Inc., not by Telegram, and in early December 2026 its merchant API schema described onboarding with "KYB (Know-Your-Business) or KYC (Know-Your-Customer) checks", funds that are "credited to your Assets and held for 48 hours by default", and the rule that "Only the specified 'customerTelegramUserId' can open a payment page." It is a custodial route: the money sits in Walt's system until you withdraw it.

A checkout link is the general route. The buyer opens a hosted page, picks a token and network, and sends from whatever wallet or exchange they use. With CoinStack the payment is converted to USDC and settled to a wallet you control, for 0.8% of each payment, and the USDC is in your wallet when the checkout completes, with no holds or reserves. Sign-up is instant, with no approval process or waiting list, so the bot can take its first payment the day you build it. The rest of this post builds that route.

How the bot and the payment fit together

The bot never handles money. It creates orders and sends links, and your server listens for CoinStack's webhook:

  1. A customer sends /buy beans to the bot.
  2. Your server saves an order and creates a checkout for its price, with the order ID in reference and metadata.
  3. The bot replies with a Pay with crypto button that opens the checkout's url.
  4. The customer pays on the hosted page from any wallet or exchange.
  5. CoinStack sends a signed checkout.completed event to your webhook URL.
  6. Your server checks the signature, reads the checkout's current status from the API, marks the order paid and messages the customer and your staff.

This uses 2 processes that share one SQLite file. One long-polls Telegram for messages with getUpdates, so the bot needs no public URL of its own. The other is a small Flask app that receives CoinStack's webhooks over HTTPS. Telegram's Bot API notes that getUpdates "will not work if an outgoing webhook is set up", so do not also call setWebhook for the same bot.

What do you need to set it up?

  1. A bot token. Create the bot with @BotFather and copy the token.
  2. A staff chat ID: the chat or group where paid orders should be announced.
  3. A CoinStack API key. In the dashboard, under Developers, select New API key with Read and write access. It starts with sk_ and is shown once.
  4. A webhook. Under Developers, select Add webhook and enter https://your-domain/webhooks/coinstack. Copy the signing secret, which starts with whsec_ and is shown once.
  5. Python 3 with two packages: pip install requests flask.

Set TELEGRAM_BOT_TOKEN, STAFF_CHAT_ID, COINSTACK_API_KEY and COINSTACK_WEBHOOK_SECRET as environment variables. The code calls the Telegram Bot API directly over HTTPS, so there is no bot library to keep up to date; swapping in python-telegram-bot or aiogram changes only the Telegram side.

The first part of bot.py holds the configuration, the database and two small HTTP helpers. Both APIs wrap their answers in an envelope: Telegram's has ok and result, CoinStack's has success and response.

import hashlib
import hmac
import json
import os
import sqlite3
import time

import requests
from flask import Flask, request

TELEGRAM = f"https://api.telegram.org/bot{os.environ['TELEGRAM_BOT_TOKEN']}"
COINSTACK = "https://coinstack.net/api/v1"
API_KEY = os.environ["COINSTACK_API_KEY"]
SECRET = os.environ["COINSTACK_WEBHOOK_SECRET"]
STAFF_CHAT_ID = int(os.environ["STAFF_CHAT_ID"])

PRODUCTS = {
    "beans": ("Single-origin coffee beans, 1 kg", "24.00"),
    "grinder": ("Hand coffee grinder", "89.00"),
}


def db():
    conn = sqlite3.connect("shop.db")
    conn.execute(
        "CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, chat_id INTEGER,"
        " sku TEXT, status TEXT DEFAULT 'unpaid', checkout_id TEXT UNIQUE)"
    )
    return conn


def telegram(method, http_timeout=10, **params):
    response = requests.post(f"{TELEGRAM}/{method}", json=params, timeout=http_timeout)
    body = response.json()

    if not body["ok"]:
        raise RuntimeError(body.get("description", "Telegram error"))

    return body["result"]


def coinstack(method, path, payload=None):
    response = requests.request(
        method,
        COINSTACK + path,
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=payload,
        timeout=10,
    )
    body = response.json()

    if not body["success"]:
        raise RuntimeError(body["response"])

    return body["response"]

The second part answers messages. /buy with a known product creates the order, then the checkout, then sends the button; anything else gets the menu.

def handle_message(message):
    chat_id = message["chat"]["id"]
    words = message.get("text", "").split()

    if len(words) < 2 or words[0] != "/buy" or words[1] not in PRODUCTS:
        menu = "\n".join(f"/buy {sku}: {name}, ${price}" for sku, (name, price) in PRODUCTS.items())
        telegram("sendMessage", chat_id=chat_id, text=f"What would you like?\n{menu}")
        return

    sku = words[1]
    name, price = PRODUCTS[sku]

    with db() as conn:
        order_id = conn.execute(
            "INSERT INTO orders (chat_id, sku) VALUES (?, ?)", (chat_id, sku)
        ).lastrowid

    checkout = coinstack("POST", "/checkouts", {
        "amount": price,
        "currency": "USD",
        "reference": f"tg-{order_id}",
        "description": name,
        "metadata": {"order_id": str(order_id)},
    })["checkout"]

    with db() as conn:
        conn.execute(
            "UPDATE orders SET checkout_id = ? WHERE id = ?",
            (checkout["checkout_id"], order_id),
        )

    telegram(
        "sendMessage",
        chat_id=chat_id,
        text=f"Order #{order_id}: {name}, ${price}.\n"
        "Pay with the token and network you prefer. The link is valid for 24 hours.",
        reply_markup={"inline_keyboard": [[{"text": "Pay with crypto", "url": checkout["url"]}]]},
    )


def poll():
    offset = 0

    while True:
        try:
            updates = telegram(
                "getUpdates", http_timeout=40, offset=offset, timeout=30, allowed_updates=["message"]
            )
        except requests.RequestException:
            time.sleep(5)
            continue

        for update in updates:
            offset = update["update_id"] + 1

            try:
                handle_message(update["message"])
            except Exception as error:
                print(f"Update {update['update_id']} failed: {error}")

A few details are worth knowing. The amount is a string, as the API requires, and the price lives on the server, never in the message text the customer could edit. description appears on the checkout page so the customer sees what they are paying for. The timeout=30 passed to getUpdates is Telegram's long-poll wait; the HTTP timeout of 40 seconds is longer so the request is not cut off first. Each getUpdates call with a higher offset confirms the earlier updates, so Telegram does not send them again.

A checkout stays open for 24 hours by default. For a flash sale you can pass expires_at (anything from 10 minutes to 365 days ahead) when creating it. If you price in another currency, change currency: checkouts accept 146 of them.

The webhook: confirm, then deliver

The third part is the Flask app. It verifies the signature with the code from the webhooks guide, ignores checkouts it did not create, reads the checkout's current status, and delivers once.

app = Flask(__name__)


def verify(header, body):
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    timestamp = parts.get("t", "")
    signed = timestamp.encode() + b"." + body
    expected = hmac.new(SECRET.encode(), signed, hashlib.sha256).hexdigest()

    return (
        hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
        and timestamp.isdigit()
        and abs(time.time() - int(timestamp)) <= 300
    )


def fulfil(checkout_id):
    with db() as conn:
        conn.execute(
            "UPDATE orders SET status = 'paid' WHERE checkout_id = ? AND status = 'unpaid'",
            (checkout_id,),
        )
        order = conn.execute(
            "SELECT id, chat_id, sku, status FROM orders WHERE checkout_id = ?",
            (checkout_id,),
        ).fetchone()

    if order is None or order[3] != "paid":
        return

    order_id, chat_id, sku, _ = order
    name = PRODUCTS[sku][0]
    telegram("sendMessage", chat_id=STAFF_CHAT_ID, text=f"Paid: order #{order_id}, {name}. Please ship.")
    telegram("sendMessage", chat_id=chat_id, text=f"Payment received for order #{order_id}. We will message you here about delivery.")

    with db() as conn:
        conn.execute("UPDATE orders SET status = 'delivered' WHERE id = ?", (order_id,))


@app.post("/webhooks/coinstack")
def coinstack_webhook():
    body = request.get_data()

    if not verify(request.headers.get("CoinStack-Signature", ""), body):
        return "Invalid signature", 400

    event = json.loads(body)

    if event["kind"] not in ("checkout.completed", "checkout.resolved"):
        return "", 200

    checkout_id = event["data"]["checkout"]["checkout_id"]

    with db() as conn:
        known = conn.execute("SELECT 1 FROM orders WHERE checkout_id = ?", (checkout_id,)).fetchone()

    if known is None:  # not one of ours, such as the dashboard test event
        return "", 200

    checkout = coinstack("GET", f"/checkouts/{checkout_id}")["checkout"]

    if checkout["status"] in ("completed", "resolved"):
        fulfil(checkout_id)

    return "", 200


if __name__ == "__main__":
    poll()

request.get_data() returns the raw bytes, which is what the signature covers; how to verify payment webhooks explains why re-encoding the JSON breaks the check. resolved is treated as paid because it means you accepted an underpayment in the dashboard.

The order moves from unpaid to paid to delivered. The first update only changes a row once, so a duplicate checkout.completed does not announce the order twice. If a Telegram message fails, the handler raises, Flask answers 500, and CoinStack retries the event after 1 minute; the order is still paid, so the retry sends the messages again. Two copies of the same event processed at the same instant could still both send, which reliable payment webhooks solves with an event table and a queue.

How do you run and test it?

Start the poller with python bot.py, and serve the webhook with a production server such as gunicorn bot:app behind a reverse proxy that terminates HTTPS. CoinStack expects a 2xx within 10 seconds, which this handler meets comfortably: one API call and two messages.

Then test in this order:

  1. Message the bot and check the menu and the button.
  2. Use Send test on the webhook in the dashboard. It sends a signed sample checkout.completed for a checkout that is not in your database, so the handler should answer 200 and send nothing.
  3. Open the demo checkout to see what your customers will see.
  4. Buy something real. The smallest checkout is worth 1 US dollar, so add a $1 test product and pay it with a stablecoin on a low-cost network.

What goes wrong in a bot that sells for crypto?

Customers sometimes send less than the total, for example when an exchange deducts its withdrawal fee from the amount sent. A small shortfall within your underpayment allowance (0.5% of the total by default) still completes the checkout. A bigger one leaves it partial, and the customer can send the rest to the same address; handle checkout.partial if you want the bot to tell them. Underpaid crypto payments covers the options when a partly paid checkout expires.

Customers also abandon orders. Subscribe to checkout.expired and have the bot say the link has closed and that /buy starts again. Check underpaid on that event first: if it is false, nothing was paid and there is nothing to undo; if it is true, part of the money already reached your wallet, and you either resolve the checkout and ship or refund the customer.

You send refunds from your own wallet, on your own timing: for a cancelled order, send USDC or another token to the address the customer gives you. How to refund a crypto payment walks through doing it safely.

Finally, guard the bot token like the API key. Anyone with the token can read your bot's messages and send as it, so keep it in the environment and revoke it in @BotFather if it leaks.

Frequently asked questions

Which Telegram bot sales can use a crypto payment link?

Physical goods and services, which fall under section 6.1 of Telegram's developer terms, where you choose your own provider. Section 6.2 requires digital goods and services sold inside a bot to be paid in Telegram Stars and bars third-party payment providers for them, and the terms tie "digital" to Apple's and Google's in-app purchase definitions. Check your product against both sections before you build.

Which coins can customers use to pay through the bot?

Whatever you enable on the checkout page under Settings, then Payment methods, in the dashboard, chosen from 10 tokens across 11 networks. Four are stablecoins (USDC, USDT, PYUSD and USDG); the others are BTC, ETH, SOL, BNB, TRX and HYPE. The customer picks one on the checkout page. Whatever they choose, the payment settles to you as USDC, on the network and at the address you set for your account.

Does the customer need a particular wallet?

No. The checkout page shows an address, the exact amount and a QR code, so the customer can pay from any wallet app or straight from an exchange account, with no wallet to connect. That is the main difference from Walt Pay, where the customer pays from a Walt balance.

Do I need to set a Telegram webhook for this bot?

No. The bot receives messages by long polling with getUpdates, which needs no public URL. The only public URL is the one CoinStack posts payment events to. If you prefer a Telegram webhook for messages, remove the polling loop, because Telegram does not deliver updates through getUpdates while a webhook is set.

Can the same setup sell to Telegram channel or group members?

The payment side is the same: one checkout per order, confirmed by webhook. What changes is the product. Paid channel or group membership is a digital service, which section 6.2 of Telegram's terms covers, so read it before charging for access. Crypto payments for paid communities and creators discusses the options for that kind of seller.

More posts