Jun 22, 2026
How to Integrate Telegram Gateway API: Step-by-Step OTP Setup (2026)
Learn how to integrate the Telegram Gateway API to send cost-effective, secure OTP verification codes …
As the Telegram platform shifts rapidly toward becoming a full-fledged decentralized application (dApp) ecosystem, monetization options have fundamentally transformed. Since mid-2024, Telegram has enforced a strict policy: all digital goods, subscription content, and virtual services sold within bots and Mini Apps must be transactions processed exclusively using Telegram Stars (currency code: XTR). Designed to ensure compliance with Apple's App Store and Google's Play Store guidelines, Telegram Stars allow users to purchase a unified internal currency using standard in-app purchases. For developers, this represents both a major compliance shift and a massive business opportunity: instead of routing users through external Stripe or PayPal pages that cause high drop-off rates, developers can now implement seamless, single-tap payment dialogs directly within chat screens. This guide provides a detailed, step-by-step setup and installation walkthrough for integrating the Telegram Stars Payment API into your Python Telegram bots, utilizing the most popular developer libraries (aiogram and python-telegram-bot) and incorporating secure transactional database patterns.
To accept payments in Telegram bots, you must use **Telegram Stars** (currency code: XTR) for digital goods. Integrate it using Python libraries like aiogram or python-telegram-bot by calling send_invoice, responding to pre_checkout_query, and delivering the digital item upon receiving successful_payment. Check out Telekit's Science & Tech Bot Catalog for pre-built bot examples.
Telegram Stars serve as the universal digital token within the Telegram ecosystem. Users purchase Stars directly through Apple or Google mobile in-app payments, or via Fragment using TON cryptocurrency. Developers receive these Stars as revenue from their bots and can later swap them for Toncoin (TON) on the Fragment platform or use them to run advertising campaigns on Telegram at a subsidized rate.
When implementing the Telegram Stars Payment API, there are several key parameters that differ from traditional credit card payment processors. The most important distinction is the currency code—which is hardcoded to XTR—and the fact that prices are represented as integer amounts of Stars. There are no fractional cents or decimal places; if an item costs 15 Stars, you pass the value 15 to the API.
Before launching your developer environment, you must configure your Telegram Bot's payment options via Telegram's administrative tool. Follow these initial steps:
/mybots and select the target bot you wish to integrate.BOT_TOKEN).Ensure you have Python 3.9+ installed. Set up a virtual environment and install the required library package. Depending on which library you prefer, run the appropriate setup commands in your terminal console:
Option A: Install dependencies for aiogram (v3+):
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
# Install aiogram
pip install aiogram
Option B: Install dependencies for python-telegram-bot (v20+):
# Install python-telegram-bot
pip install python-telegram-bot
The aiogram framework is widely considered the industry standard for modern, high-concurrency Telegram bots. The following script shows how to implement the complete payment lifecycle: sending the product invoice, validating the purchase readiness during pre-checkout, and delivering the digital items once confirmation is received.
import logging
import asyncio
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.types import LabeledPrice, PreCheckoutQuery
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize Bot and Dispatcher
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
@dp.message(Command("buy"))
async def send_stars_invoice(message: types.Message):
# Sends an invoice requesting Telegram Stars (XTR)
prices = [LabeledPrice(label="Premium PDF Guide", amount=50)] # 50 Stars
await bot.send_invoice(
chat_id=message.chat.id,
title="Python Integration Premium Guide",
description="A complete PDF guide on integrating payment APIs into bots.",
payload="item_premium_pdf_guide_001",
provider_token="", # Leave blank for Telegram Stars
currency="XTR",
prices=prices,
start_parameter="buy-premium-guide",
suggested_tip_amounts=[5, 10, 20]
)
@dp.pre_checkout_query()
async def process_pre_checkout(pre_checkout_query: PreCheckoutQuery):
# Validates item availability before payment processes.
# Must respond within 10 seconds.
item_payload = pre_checkout_query.invoice_payload
logging.info(f"Processing pre-checkout for: {item_payload}")
if item_payload == "item_premium_pdf_guide_001":
await bot.answer_pre_checkout_query(
pre_checkout_query.id,
ok=True
)
else:
await bot.answer_pre_checkout_query(
pre_checkout_query.id,
ok=False,
error_message="The requested digital item is temporarily out of stock."
)
@dp.message(F.successful_payment)
async def process_successful_payment(message: types.Message):
# Triggers delivery of the digital goods upon successful transaction
payment_info = message.successful_payment
logging.info(f"Payment success: {payment_info.telegram_payment_charge_id}")
await message.reply(
f"Thank you for your purchase!\n"
f"Transaction ID: {payment_info.telegram_payment_charge_id}\n"
f"Amount Paid: {payment_info.total_amount} Stars 🌟\n\n"
f"Here is your download link: https://telekit.link/downloads/premium-guide.pdf"
)
async def main():
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
If your project relies on the classic, object-oriented python-telegram-bot framework, you can implement the identical behavior. This code sets up handlers for commands, pre-checkout queries, and transaction confirmations.
import logging
from telegram import Update, LabeledPrice
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
PreCheckoutQueryHandler,
MessageHandler,
filters
)
# Configure logging
logging.basicConfig(level=logging.INFO)
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
async def buy_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Sends the XTR invoice to the user.
chat_id = update.message.chat_id
prices = [LabeledPrice("Pro Account Access", 100)] # 100 Stars
await context.bot.send_invoice(
chat_id=chat_id,
title="Pro Bot Membership",
description="Unlock advanced AI generation limits for 30 days.",
payload="subscription_pro_30d",
provider_token="", # Must be empty for Telegram Stars
currency="XTR",
prices=prices
)
async def precheckout_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Validates the transaction request.
query = update.pre_checkout_query
if query.invoice_payload != "subscription_pro_30d":
await query.answer(ok=False, error_message="Invalid payment request.")
else:
await query.answer(ok=True)
async def successful_payment_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Grants the service access to the user.
payment = update.message.successful_payment
charge_id = payment.telegram_payment_charge_id
# Store charge_id in database to confirm transaction delivery
await update.message.reply_text(
f"Payment Approved! Access Granted.\n"
f"Reference: {charge_id}\n"
f"Stars Deducted: {payment.total_amount}"
)
def main():
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("buy", buy_command))
app.add_handler(PreCheckoutQueryHandler(precheckout_callback))
app.add_handler(MessageHandler(filters.SUCCESSFUL_PAYMENT, successful_payment_callback))
app.run_polling()
if __name__ == "__main__":
main()
A major vulnerability when setting up bot payment integration is failing to verify the transaction status asynchronously against a database. Replay attacks or network timeouts might prevent your code from executing the successful payment handler. You must implement a database table (e.g., SQLite, PostgreSQL, or MySQL) to log state changes. Below is a Python module template demonstrating database integration using sqlite3 to ensure transaction safety.
import sqlite3
import time
def init_db():
conn = sqlite3.connect("payments.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS transactions (id TEXT PRIMARY KEY, user_id INTEGER, amount INTEGER, payload TEXT, status TEXT, timestamp INTEGER)")
conn.commit()
conn.close()
def record_pre_checkout(user_id: int, amount: int, payload: str, temp_id: str):
# Logs the checkout request to verify when successful payment arrives.
conn = sqlite3.connect("payments.db")
cursor = conn.cursor()
cursor.execute("INSERT OR REPLACE INTO transactions (id, user_id, amount, payload, status, timestamp) VALUES (?, ?, ?, ?, ?, ?)", (temp_id, user_id, amount, payload, "PENDING", int(time.time())))
conn.commit()
conn.close()
def finalize_payment(charge_id: str, temp_id: str):
# Updates the database status to confirmed and links the official Charge ID.
conn = sqlite3.connect("payments.db")
cursor = conn.cursor()
# Find pending checkout record
cursor.execute("SELECT user_id, payload FROM transactions WHERE id = ?", (temp_id,))
record = cursor.fetchone()
if record:
# Mark as completed
cursor.execute("UPDATE transactions SET id = ?, status = 'COMPLETED' WHERE id = ?", (charge_id, temp_id))
conn.commit()
conn.close()
return record[0], record[1] # Returns user_id and payload
conn.close()
return None, None
Transactions made via Stars are subject to a platform fee structure. Because the initial purchase is handled as a mobile in-app purchase, Apple and Google deduct their standard 30% cut. When withdrawing Toncoin, the network and marketplace transaction fees apply. However, Telegram subsidizes advertising costs—developers who reuse their earned Stars to purchase Telegram Ads receive a significant discount, minimizing the impact of the initial 30% platform fee.
No. Telegram's terms of service and mobile app store guidelines state that Stars must be used exclusively for digital services, premium bot tiers, and virtual items. If you are selling physical goods (e.g., merchandise, food delivery, or tickets), you must use Telegram's standard payment providers (such as Stripe, Paycom, or Smart Glocal) which support normal credit card transactions.
When configuring payments through @BotFather, you can use sandbox tokens. Telegram handles test transactions for bots without deducting real assets. Always perform complete end-to-end integration tests using this sandbox configuration before switching your project code into production mode.
Telegram allows bots to programmatically refund stars to users. To execute a refund, you must call the refundStarPayment API method, providing the user_id and the unique telegram_payment_charge_id associated with the original successful transaction. Note that you can only issue refunds for purchases made within the last 90 days.
Integrating Telegram Stars is no longer optional for bots selling digital access, but it offers a massive benefit in terms of user experience and conversions. By removing payment friction and allowing one-tap checkouts directly within the conversation thread, the Stars API can significantly boost transaction rates for developers. By using either `aiogram` or `python-telegram-bot` alongside a secure transactional database log, you can implement a robust, secure, and compliant payment gateway in minutes.
To view other tools, utilities, and integrations for bot creators, visit the Telekit Science & Technology Section.
Stay updated with the latest Telegram groups and channels
Or scan the QR code
Loading community stats...
No active reviews. Be the first to add one!