# Accept Telegram Stars payments in a bot: invoices and refunds

> Sell digital goods with Telegram Stars: an XTR invoice, pre_checkout_query answered in 10 seconds, delivery on successful_payment, refunds.

Published 2026-11-04. Z-API Omni team.

A Telegram bot that sells digital goods or services must charge in Telegram Stars. You send an invoice with `currency` set to `XTR` and an empty `provider_token`, approve the `pre_checkout_query` within 10 seconds, and deliver only after a `successful_payment` message arrives. Telegram's [payments page](https://core.telegram.org/bots/payments-stars) (accessed 2026-11-04) says these payments "must be carried out exclusively in Telegram Stars". Method details below come from the [Bot API reference](https://core.telegram.org/bots/api) at Bot API 10.3, August 24, 2026 (accessed 2026-11-04). Telegram publishes no request samples for these methods, so the code is assembled from the parameter tables.

## Why Stars are required for digital goods

The rule comes from the app stores. Telegram explains that the Play Store and the App Store restrict how developers sell digital goods. Because of those rules, Telegram "cannot display your bot or mini-app to mobile users" when it sells digital goods any other way. That includes sales "via other currencies or through third-party payment providers" ([payments-stars](https://core.telegram.org/bots/payments-stars)). Physical goods can still use other payment options. The pages we read give no fiat value for a Star in text, so price your goods in whole Stars and leave conversion out of your code.

## Send the invoice

`sendInvoice` posts an invoice to a private chat, group or channel and returns the sent Message ([payments-stars](https://core.telegram.org/bots/payments-stars), [sendInvoice](https://core.telegram.org/bots/api#sendinvoice)). For Stars, several parameters take fixed values or are ignored.

| Parameter | Value for Telegram Stars |
| --- | --- |
| `title` | Product name, 1 to 32 characters |
| `description` | 1 to 255 characters |
| `payload` | Your internal id, 1 to 128 bytes, never shown to the user |
| `provider_token` | Empty string |
| `currency` | `XTR` |
| `prices` | Exactly one item |

`max_tip_amount` is "not supported for payments in Telegram Stars", and the `need_*` and `send_*_to_provider` flags are ignored. `LabeledPrice.amount` is an integer in the smallest units of the currency. The reference doesn't spell out the unit for `XTR`, and our reading is that one unit is one Star. The `payload` comes back in the pre-checkout query and in the payment, so identify the product by it.

How forwarded invoices behave depends on `start_parameter`. If you leave it empty, forwarded copies show a Pay button that anyone can press and try to pay. If you set it, forwarded copies get a URL button that opens your bot instead, which [Telegram deep linking](/academy/articles/telegram-bot-deep-linking-start-parameter/) explains.

## Answer pre_checkout_query within 10 seconds

After the user confirms, Telegram sends an update with the `pre_checkout_query` field. Your bot calls `answerPreCheckoutQuery` with `ok` set to true to proceed, or false plus an `error_message` that explains the refusal ([answerPreCheckoutQuery](https://core.telegram.org/bots/api#answerprecheckoutquery)). If no answer arrives in time, the payments page says "the transaction is canceled".

The two pages word the deadline differently. The payments page counts 10 seconds "after receiving this update". The reference counts 10 seconds "after the pre-checkout query was sent". Budget against the stricter one, the moment Telegram sent the query, and keep the check to a local lookup. A slow database call or an outside API in this path risks losing the sale.

The `PreCheckoutQuery` object carries `id`, `from`, `currency`, `total_amount` and `invoice_payload`. Check that the currency is `XTR`, the payload is a product you still sell, and the amount matches your price.

## Deliver only after successful_payment

The payment ends with a message that carries a `successful_payment` field. The payments page puts it as a rule: "You must always check that you received a successful_payment update before delivering the goods" ([payments-stars](https://core.telegram.org/bots/payments-stars)). Approving the pre-checkout query isn't enough.

Store `telegram_payment_charge_id` from that message, because "it may be needed to issue a refund in the future". The reference describes it only as the "Telegram payment identifier". Use it as a unique key in your database too. If your bot ever processes the same message twice, the second insert is ignored and the goods go out once.

The reference also carries a warning for sellers. If the buyer starts a chargeback with the payment provider, "the funds may be debited from your balance. This is outside of Telegram's control" ([SuccessfulPayment](https://core.telegram.org/bots/api#successfulpayment)).

## A long-polling payment bot

This bot runs on Python 3.9 or later with only the standard library, and SQLite for storage. It shows terms on `/buy`, sends the invoice after `/agree`, validates the pre-checkout query, and records each charge before it delivers. Replace `DELIVERY_URL` with what you actually sell. The `call` helper and the polling loop are explained in [the getting-started Python bot](/academy/articles/telegram-bot-send-message-python-getting-started/).

```python
import json
import os
import sqlite3
import time
import urllib.error
import urllib.request

TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
ADMIN_ID = int(os.environ["ADMIN_USER_ID"])  # your own Telegram user id
API = f"https://api.telegram.org/bot{TOKEN}/"

PRODUCT = "guide-pdf-v1"  # invoice payload, 1-128 bytes
PRICE_STARS = 50          # example price in whole Stars
TERMS = "Terms: one PDF download, no subscription. Send /agree to accept, then pay."
SUPPORT = ("Payment problem? Describe it here and we answer from this bot. "
           "Telegram support can't help with purchases made through this bot.")

db = sqlite3.connect("payments.db")
db.executescript("""
CREATE TABLE IF NOT EXISTS agreed (user_id INTEGER PRIMARY KEY);
CREATE TABLE IF NOT EXISTS payments (
    charge_id TEXT PRIMARY KEY,
    user_id   INTEGER NOT NULL,
    payload   TEXT NOT NULL,
    amount    INTEGER NOT NULL,
    refunded  INTEGER NOT NULL DEFAULT 0
);
""")

class TelegramError(Exception):
    pass

def call(method, params=None, timeout=10):
    request = urllib.request.Request(
        API + method,
        data=json.dumps(params or {}).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            body = json.loads(response.read())
    except urllib.error.HTTPError as err:
        try:
            body = json.loads(err.read())
        except ValueError:
            raise TelegramError(f"{method}: HTTP {err.code}") from err
    if not body.get("ok"):
        raise TelegramError(f"{method}: {body.get('description')}")
    return body["result"]

def has_agreed(user_id):
    return db.execute("SELECT 1 FROM agreed WHERE user_id = ?", (user_id,)).fetchone() is not None

def send_text(chat_id, text):
    call("sendMessage", {"chat_id": chat_id, "text": text})

def send_invoice(chat_id):
    call("sendInvoice", {
        "chat_id": chat_id,
        "title": "Field guide (PDF)",
        "description": "A downloadable PDF field guide.",
        "payload": PRODUCT,
        "provider_token": "",
        "currency": "XTR",
        "prices": [{"label": "Field guide", "amount": PRICE_STARS}],
    })

def answer_pre_checkout(query):
    valid = (
        query["currency"] == "XTR"
        and query["invoice_payload"] == PRODUCT
        and query["total_amount"] == PRICE_STARS
        and has_agreed(query["from"]["id"])
    )
    params = {"pre_checkout_query_id": query["id"], "ok": valid}
    if not valid:
        params["error_message"] = "This offer changed or the terms were not accepted. Send /buy again."
    call("answerPreCheckoutQuery", params)

def record_and_deliver(message):
    payment = message["successful_payment"]
    with db:
        cursor = db.execute(
            "INSERT OR IGNORE INTO payments (charge_id, user_id, payload, amount) VALUES (?, ?, ?, ?)",
            (payment["telegram_payment_charge_id"], message["from"]["id"],
             payment["invoice_payload"], payment["total_amount"]),
        )
    if cursor.rowcount == 1:  # first time we see this charge
        send_text(message["chat"]["id"], "Payment received. Your download: DELIVERY_URL")

def refund(charge_id):
    row = db.execute(
        "SELECT user_id FROM payments WHERE charge_id = ? AND refunded = 0", (charge_id,)
    ).fetchone()
    if row is None:
        raise TelegramError("unknown or already refunded charge")
    call("refundStarPayment", {"user_id": row[0], "telegram_payment_charge_id": charge_id})
    with db:
        db.execute("UPDATE payments SET refunded = 1 WHERE charge_id = ?", (charge_id,))

def handle_message(message):
    if "successful_payment" in message:
        record_and_deliver(message)
        return
    chat_id = message["chat"]["id"]
    user_id = message.get("from", {}).get("id")
    command, _, arg = message.get("text", "").partition(" ")
    if command == "/buy":
        if has_agreed(user_id):
            send_invoice(chat_id)
        else:
            send_text(chat_id, TERMS)
    elif command == "/agree":
        with db:
            db.execute("INSERT OR IGNORE INTO agreed (user_id) VALUES (?)", (user_id,))
        send_invoice(chat_id)
    elif command == "/terms":
        send_text(chat_id, TERMS)
    elif command == "/paysupport":
        send_text(chat_id, SUPPORT)
    elif command == "/refund" and user_id == ADMIN_ID and arg:
        refund(arg.strip())
        send_text(chat_id, "Refunded.")

def main():
    offset = None
    while True:
        params = {"timeout": 30, "allowed_updates": ["message", "pre_checkout_query"]}
        if offset is not None:
            params["offset"] = offset
        try:
            updates = call("getUpdates", params, timeout=40)
        except (TelegramError, OSError) as err:
            print("getUpdates failed:", err)
            time.sleep(5)
            continue
        for update in updates:
            offset = update["update_id"] + 1
            try:
                if "pre_checkout_query" in update:
                    answer_pre_checkout(update["pre_checkout_query"])
                elif "message" in update:
                    handle_message(update["message"])
            except (TelegramError, OSError) as err:
                print("update", update["update_id"], "failed:", err)

if __name__ == "__main__":
    main()
```

Run it with `TELEGRAM_BOT_TOKEN=YOUR_TOKEN ADMIN_USER_ID=YOUR_USER_ID python3 bot.py`. The pre-checkout check reads one local SQLite row and makes no network call besides the answer. `INSERT OR IGNORE` on the charge id makes delivery happen once. Telegram also has a dedicated test environment for Stars payments, set up from a separate page ([payments-stars](https://core.telegram.org/bots/payments-stars)).

## Refunds with refundStarPayment

`refundStarPayment` takes `user_id` and `telegram_payment_charge_id` and "returns True on success" ([refundStarPayment](https://core.telegram.org/bots/api#refundstarpayment)). The `/refund CHARGE_ID` command above calls it, restricted to your own user id, and marks the row so the same charge can't be refunded twice. Neither page states a time window for refunds. A message can also carry a `refunded_payment` field, a service message with the refunded charge's details. `getStarTransactions` lists the bot's transactions in chronological order, up to 100 per call.

## Subscriptions through createInvoiceLink

Recurring payments use `createInvoiceLink`, which returns the invoice link as a string. `sendInvoice` has no `subscription_period` parameter. With `subscription_period` set, the currency must be `XTR`, the period "must always be 2592000 (30 days)", and the price can't exceed 10,000 Stars ([createInvoiceLink](https://core.telegram.org/bots/api#createinvoicelink)).

Inside the bot above, with `CHAT_ID` as the buyer's chat:

```python
link = call("createInvoiceLink", {
    "title": "Monthly pass",
    "description": "Premium commands for 30 days.",
    "payload": "pass-monthly",
    "provider_token": "",
    "currency": "XTR",
    "prices": [{"label": "Monthly pass", "amount": 100}],
    "subscription_period": 2592000,
})
send_text(CHAT_ID, link)
```

Add `pass-monthly` and its price to the pre-checkout check first, or the bot refuses it. Then change `record_and_deliver` to send the pass instead of `DELIVERY_URL` for that payload. Payments arrive as `successful_payment` with `is_recurring`, `is_first_recurring` and `subscription_expiration_date`, so gate access on that date. The reference doesn't say whether renewals trigger a new pre-checkout query or carry a new charge id. Log the first renewal before you rely on either. `editUserStarSubscription` with `is_canceled` set to true cancels the extension, and Telegram adds that the subscription must stay active up to the end of the current period.

## Paid media

For photos or videos behind a paywall, `sendPaidMedia` takes a `star_count` from 1 to 25,000 and a `payload` of 0 to 128 bytes. When a user buys media with a non-empty payload in a non-channel chat, your bot receives a `purchased_paid_media` update ([sendPaidMedia](https://core.telegram.org/bots/api#sendpaidmedia)). For selling inside a web interface instead of chat, [Telegram Mini Apps](/academy/articles/telegram-mini-apps-validate-init-data/) covers validating the user's data on your server.

## Terms, support and disputes

Telegram puts three duties on the seller. Your bot "must be able to respond to the command /paysupport" for payment issues. It must answer `/terms`, and users "must confirm that they have read and agree to your terms before they make the purchase". And you are "solely responsible for processing and rectifying legitimate user disputes" ([payments-stars](https://core.telegram.org/bots/payments-stars)). The bot above answers `/terms` and `/paysupport` and blocks payment until the user sends `/agree`.

The same page's checklist asks you to turn on 2-step verification for the account that controls the bot and to keep backups of payment data. It also asks you to tell users that Telegram support can't help with purchases made through your bot, which the `SUPPORT` reply does. Register the commands with [setMyCommands](/academy/articles/telegram-bot-commands-menu-setmycommands/) so they show in the menu.

*Z-API Omni team*
