Telegram Bot API

Telegram Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions

· 9 min read

To accept Telegram Stars payments in a bot, send an invoice with sendInvoice using currency XTR and an empty provider_token, answer the pre_checkout_query update with answerPreCheckoutQuery within 10 seconds, and deliver the goods only after a message with successful_payment arrives. Telegram Stars are the required currency for digital goods and services sold in Telegram apps. This guide walks through the whole flow with a working Python and JavaScript bot, then covers refunds, transaction history, subscriptions and paid media.

How Telegram Stars payments work in a bot

Telegram Stars are an in-app virtual item. Users buy them through Apple or Google in-app purchases or via @PremiumBot and spend them in your bot; the payment form asks for no personal data. The flow:

  1. The bot sends an invoice: sendInvoice to a chat, or createInvoiceLink for a link.
  2. The user presses Pay (buying Stars first if needed).
  3. The bot receives an update with pre_checkout_query.
  4. The bot confirms or rejects the order with answerPreCheckoutQuery, within 10 seconds.
  5. Telegram sends a service message with successful_payment.
  6. The bot stores telegram_payment_charge_id and delivers the goods.

Digital goods must be sold in Stars. Telegram states that a bot or Mini App must use Telegram Stars for the sale of digital goods and services inside Telegram apps, regardless of any website or payment provider you run elsewhere; otherwise Telegram can't show your bot to mobile users. Other currencies and payment providers are only for physical goods, which use a separate flow with a provider token.

Send an invoice with sendInvoice and XTR

A minimal Stars invoice for 50 Stars:

curl -X POST "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/sendInvoice" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": 123456789,
    "title": "Pro pack",
    "description": "50 extra image generations for your account",
    "payload": "pro-pack-v1",
    "provider_token": "",
    "currency": "XTR",
    "prices": [{"label": "Pro pack", "amount": 50}]
  }'

The method returns the sent Message. Parameters that matter for Stars:

ParameterRule for Telegram Stars
titleProduct name, 1–32 characters.
descriptionProduct description, 1–255 characters.
payload1–128 bytes, not shown to the user. Put your order or product id here; it comes back in the pre-checkout query and the payment.
provider_tokenOptional; pass an empty string for Stars.
currencyXTR.
pricesArray of LabeledPrice that must contain exactly one item; amount is the price in Stars (an integer).
start_parameterEmpty: forwarded copies keep a Pay button. Non-empty: forwarded copies show a URL button with a deep link to the bot instead.
photo_urlOptional product image, with photo_size, photo_width, photo_height.

Tips (max_tip_amount) are not supported for Stars, and need_name, need_email, need_shipping_address, is_flexible and similar fields are ignored. If you add your own reply_markup, the first button must be a Pay button ("pay": true); the substrings ⭐ and XTR in its text are replaced with a Star icon. Invoices can go to private chats, groups and channels. Try it without code: open sendInvoice in the Bot API Tester, fill in the fields above and send yourself an invoice.

createInvoiceLink takes the same title, description, payload, currency and prices but returns an invoice link as a string instead of sending a message. Open it from a Mini App with Telegram.WebApp.openInvoice(url) or share it as a regular link. It is also the method for subscriptions (see below).

Answer pre_checkout_query within 10 seconds

When the user presses Pay, the bot receives a PreCheckoutQuery with id, from, currency, total_amount and invoice_payload. You must answer within 10 seconds, or the transaction is canceled:

Keep this handler fast: check the payload and stock, answer, and do everything else later. Approving the query does not mean the money arrived.

Deliver after successful_payment

A successful payment arrives as a message whose successful_payment field contains currency, total_amount, invoice_payload and telegram_payment_charge_id. Telegram's rule is explicit: always check that you received successful_payment before delivering. Save telegram_payment_charge_id together with the buyer's user id, because a refund requires both.

Complete example: a bot that sells for Telegram Stars

This long-polling bot sends an invoice on /buy, validates the pre-checkout query, records the payment and answers /paysupport. Note allowed_updates: if you restrict update types, include pre_checkout_query, otherwise payments never reach the bot.

import json
import os
import requests

TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"
PAYLOAD = "pro-pack-v1"
PRICE = 50  # in Telegram Stars


def call(method, **params):
    data = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if not data["ok"]:
        raise RuntimeError(f"{method}: {data['error_code']} {data['description']}")
    return data["result"]


def handle(update):
    query = update.get("pre_checkout_query")
    if query:
        ok = (query["invoice_payload"] == PAYLOAD and query["currency"] == "XTR"
              and query["total_amount"] == PRICE)
        answer = {"pre_checkout_query_id": query["id"], "ok": ok}
        if not ok:
            answer["error_message"] = "This offer has expired. Send /buy for a new invoice."
        call("answerPreCheckoutQuery", **answer)  # within 10 seconds
        return

    msg = update.get("message")
    if not msg:
        return
    chat_id = msg["chat"]["id"]
    if "successful_payment" in msg:
        payment = msg["successful_payment"]
        with open("payments.jsonl", "a") as f:  # keep the charge id for refunds
            f.write(json.dumps({"user_id": msg["from"]["id"],
                                "charge_id": payment["telegram_payment_charge_id"],
                                "payload": payment["invoice_payload"],
                                "amount": payment["total_amount"]}) + "\n")
        call("sendMessage", chat_id=chat_id, text="Thank you! Your Pro pack is active.")
    elif msg.get("text") == "/buy":
        call("sendInvoice", chat_id=chat_id, title="Pro pack",
             description="50 extra image generations for your account",
             payload=PAYLOAD, provider_token="", currency="XTR",
             prices=[{"label": "Pro pack", "amount": PRICE}])
    elif msg.get("text") == "/paysupport":
        call("sendMessage", chat_id=chat_id,
             text="Payment problem? Describe it in one message and we will reply within 24 hours.")


offset = 0
while True:
    updates = call("getUpdates", offset=offset, timeout=30,
                   allowed_updates=["message", "pre_checkout_query"])
    for update in updates:
        offset = update["update_id"] + 1
        handle(update)
import { appendFile } from "node:fs/promises";

const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;
const PAYLOAD = "pro-pack-v1";
const PRICE = 50; // in Telegram Stars

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const data = await res.json();
  if (!data.ok) throw new Error(`${method}: ${data.error_code} ${data.description}`);
  return data.result;
}

async function handle(update) {
  const query = update.pre_checkout_query;
  if (query) {
    const ok = query.invoice_payload === PAYLOAD && query.currency === "XTR"
      && query.total_amount === PRICE;
    const answer = { pre_checkout_query_id: query.id, ok };
    if (!ok) answer.error_message = "This offer has expired. Send /buy for a new invoice.";
    await call("answerPreCheckoutQuery", answer); // within 10 seconds
    return;
  }

  const msg = update.message;
  if (!msg) return;
  const chatId = msg.chat.id;
  if (msg.successful_payment) {
    const payment = msg.successful_payment;
    await appendFile("payments.jsonl", JSON.stringify({ // keep the charge id for refunds
      user_id: msg.from.id,
      charge_id: payment.telegram_payment_charge_id,
      payload: payment.invoice_payload,
      amount: payment.total_amount,
    }) + "\n");
    await call("sendMessage", { chat_id: chatId, text: "Thank you! Your Pro pack is active." });
  } else if (msg.text === "/buy") {
    await call("sendInvoice", {
      chat_id: chatId, title: "Pro pack",
      description: "50 extra image generations for your account",
      payload: PAYLOAD, provider_token: "", currency: "XTR",
      prices: [{ label: "Pro pack", amount: PRICE }],
    });
  } else if (msg.text === "/paysupport") {
    await call("sendMessage", {
      chat_id: chatId,
      text: "Payment problem? Describe it in one message and we will reply within 24 hours.",
    });
  }
}

let offset = 0;
while (true) {
  const updates = await call("getUpdates", {
    offset, timeout: 30, allowed_updates: ["message", "pre_checkout_query"],
  });
  for (const update of updates) {
    offset = update.update_id + 1;
    await handle(update);
  }
}

Save the JavaScript version as bot.mjs (Node.js 18+). In production, use a real database and make delivery idempotent per telegram_payment_charge_id. With a webhook the handler is the same; see Telegram bot webhook for the setup and its allowed_updates.

Refund a payment with refundStarPayment

curl -X POST "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/refundStarPayment" \
  -H "Content-Type: application/json" \
  -d '{"user_id": 123456789, "telegram_payment_charge_id": "CHARGE_ID_FROM_SUCCESSFUL_PAYMENT"}'

It returns true on success, the Stars go back to the user, and the chat gets a service message with refunded_payment. Revoke whatever you delivered. Note that if a buyer initiates a chargeback with Apple or Google, the refunded Stars are deducted from the bot's balance; Telegram says this is outside its control.

Balance and transactions: getMyStarBalance, getStarTransactions

Telegram Stars subscriptions

Pass subscription_period to createInvoiceLink to charge the user every 30 days:

For paid access to a channel there is createChatSubscriptionInviteLink with subscription_period 2592000 and subscription_price of 1–10000 Stars; the bot needs the can_invite_users admin right.

sendPaidMedia sends up to 10 photos or videos hidden behind a price: star_count 1–25000 and an optional payload of 0–128 bytes. In a channel, proceeds go to the channel's balance; elsewhere, to the bot's. If the payload is non-empty and the chat isn't a channel, the bot gets a purchased_paid_media update with the buyer and the payload, so add it to allowed_updates if you filter updates.

Test Stars payments in the test environment

Telegram allows free testing of Stars payments in its dedicated test environment: create a test account and a bot there, then send API requests to https://api.telegram.org/bot<token>/test/METHOD_NAME. Our tester has a TEST switch for the same purpose. Step-by-step instructions are in Telegram test server. To go live, switch the bot to the production environment.

Go-live checklist and troubleshooting

New to bots? Start with how to create a Telegram bot. The official reference is in the Telegram Stars payments documentation and the Payments section of the Bot API.

Frequently asked questions

How do I accept Telegram Stars payments in a bot?

Send an invoice with sendInvoice (or createInvoiceLink) using currency XTR, an empty provider_token and exactly one item in prices. Answer the pre_checkout_query update with answerPreCheckoutQuery within 10 seconds, then deliver the goods when a message with successful_payment arrives.

Do I need a provider token for Telegram Stars?

No. provider_token is only needed for physical goods and services. For payments in Telegram Stars pass an empty string or leave the parameter out.

Can I sell digital goods in a Telegram bot for dollars, cards or crypto?

No. According to Telegram, digital goods and services sold inside Telegram apps must be paid exclusively in Telegram Stars, because of App Store and Google Play rules. Other currencies and payment providers are allowed only for physical goods and services.

How do I refund a Telegram Stars payment?

Call refundStarPayment with the buyer's user_id and the telegram_payment_charge_id from the successful_payment message. Store that id for every payment, or you won't be able to refund it later.

How do Telegram Stars subscriptions work in bots?

Create an invoice link with createInvoiceLink and subscription_period = 2592000 (30 days, currently the only allowed value); the price can't exceed 10000 Stars. Renewals arrive as successful_payment with is_recurring, and editUserStarSubscription cancels or re-enables the extension.

How can I test Telegram Stars payments for free?

Use Telegram's dedicated test environment: create a test account and a bot there and call the API via /bot<token>/test/METHOD_NAME. Telegram says Stars payments can be tested there freely.

How to Create a Telegram Bot: Step by Step with BotFather and Python

How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.

How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting

How to deploy a Telegram bot: polling vs webhook, a systemd service on a VPS, Docker, Cloudflare Workers with secret_token, plus a launch checklist.

Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More

What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.

Telegram Bot API Errors: What Each Error Means and How to Fix It

Telegram Bot API errors explained: 400 chat not found, 403 bot was blocked by the user, 409 Conflict, 429 retry_after. Causes, fixes and handling code.

Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length

Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.

Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links

Set up Telegram bot commands: @BotFather /setcommands, setMyCommands with scopes and languages, /start deep link parameters and /cmd@bot in groups.

Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard

Add Telegram bot buttons: inline keyboard with callback_data, answerCallbackQuery, editing the message after a press, reply keyboard and ForceReply.

n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages

Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.

How to Send a Message with the Telegram Bot API (sendMessage)

Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.

Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe

Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.

How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting

Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.

How to Get a Telegram Chat ID for a User, Group, Channel or Topic

How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.

Telegram Inline Bot: How to Enable Inline Mode and Answer Inline Queries

Build a Telegram inline bot: enable inline mode with @BotFather or setMySettings, handle inline_query updates and reply with answerInlineQuery.

Telegram Test Server: How to Test a Bot in the Telegram Test Environment

Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.

Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button

Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.

TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits

TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.

Telegram Widget Examples: Complete HTML and Python Bot Code

Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.

Telegram Widgets: Interactive HTML Inside Bot Messages

Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.

How to Test a Telegram Mini App: From Browser Mock to Real Telegram

Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.