79556770

Date: 2025-04-05 09:29:20
Score: 1
Natty:
Report link

I've just finished telegram stars payment integration.

Frameworks

Firstly, I used these articles:

So, let's get started

  1. Add this code to your bot.py:
from fastapi import FastAPI
from contextlib import asynccontextmanager

from aiogram import Router, Dispatcher, Bot, types

# Bot initialization
bot = Bot("Bot_token_here")
my_router = Router()
dp = Dispatcher()

# Generate payment link for frontend
async def create_invoice_link_bot():
   payment_link = await bot.create_invoice_link(
       "Subscription",
       "100 stars",
       "{}",
       "XTR",
       prices=[LabeledPrice(label="Subscription", amount=1)]
   )
   return payment_link

# Lifespan manager for FastAPI app
@asynccontextmanager
async def lifespan(app: FastAPI):
    url_webhook = "https://your_url_here/webhook"
    await bot.set_webhook(url=url_webhook,
                          allowed_updates=dp.resolve_used_update_types(),
                          drop_pending_updates=True)
    yield
    await bot.delete_webhook()

# Accepting payments
@my_router.pre_checkout_query(lambda query: True)
async def pre_checkout_query(pre_checkout_q: types.PreCheckoutQuery):
    await bot.answer_pre_checkout_query(pre_checkout_q.id, ok=True)
  1. Track changes in webhook, including payments:
from aiogram.types import Update
from bot import bot, dp, lifespan

app = FastAPI(lifespan=lifespan)

@app.post("/webhook")
async def webhook(request: Request):
    new_update_msg = await request.json()
    successful_payment = new_update_msg.get("message", {}).get("successful_payment")
    if successful_payment:
       # your code here
    update = Update.model_validate(new_update_msg, context={"bot": bot})
    await dp.feed_update(bot, update)

I appreciate any ideas or questions

May God bless you all!

Reasons:
  • Blacklisted phrase (1): any ideas
  • Blacklisted phrase (0.5): medium.com
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Archibaldik