Skip to content

Lesson 6 of 9 · 29m

Telegram Payments in Production: Invoices, Checkout, and Fulfillment

Implement invoices, provider tokens, shipping and pre-checkout validation, successful payment handling, and fulfillment without double-charging or double-delivering.

Payments expose every weak point in a bot implementation at once: user interaction, third-party credentials, retries, asynchronous state, and money. Telegram is the checkout surface, not the payment processor. Your bot constructs invoices and receives payment events; a provider such as Stripe or another supported processor actually charges the customer. If you blur that boundary, reconciliation becomes painful fast.

Model the money flow first

A simplified sequence is:

bot sends invoice -> user pays in Telegram -> Telegram validates with provider
pre_checkout_query -> bot accepts or rejects -> successful_payment update
bot fulfills -> finance reconciliation and support tooling

The important security decision happens at pre_checkout_query. That is your last controlled chance to verify product, price, availability, user eligibility, shipping constraints, and order state before accepting the payment flow.

Invoices are structured commerce objects

Use provider data or your own order reference carefully. The invoice payload should reference a server-side order, not encode prices that the user can manipulate:

await bot.send_invoice(
    chat_id=chat_id,
    title="SudoSecurity Collab — Team plan",
    description="One month, 10 seats",
    payload="order_01J9XQ6K7M",
    currency="USD",
    prices=[LabeledPrice("Team plan", 4900)],
    provider_token=settings.telegram_payment_provider_token,
)

Amounts are in minor units: 4900 means 49.00 USD. Never derive the payable amount from callback data or client-supplied cart state. Reload the order server-side and calculate from trusted product records.

Pre-checkout is not a formality

Answer pre_checkout_query quickly and deterministically:

async def pre_checkout(query):
    order = await orders.get_by_payment_payload(query.invoice_payload)
    if not order or order.status != "open":
        await query.answer(ok=False, error_message="This order is no longer available.")
        return
    if order.total_minor_units != query.total_amount or order.currency != query.currency:
        await query.answer(ok=False, error_message="The price changed. Please request a new invoice.")
        return
    await query.answer(ok=True)

Rejecting here is not a failure; it is correct risk control. Prices change, inventory disappears, subscriptions expire, and users reopen old invoices. Checkout validation must use current truth.

Successful payment is a fulfillment trigger, not fulfillment

A successful_payment object contains provider charge identifiers and payment metadata. Persist it before side effects:

create unique index payments_telegram_charge_uidx
on payments ((provider_data->>'telegram_payment_charge_id'));

Then perform fulfillment idempotently. If a duplicate worker attempt occurs, the unique constraint prevents double-crediting or double-provisioning. Telegram does not owe you a exactly-once delivery model, and neither does your infrastructure.

Shipping and receipts need operational care

If need_shipping_address or flexible pricing is involved, you must implement shipping query handling and validate destinations. Digital goods often do not need shipping, but physical fulfillment adds fraud, address validation, tax, and customer-support complexity. Do not enable fields because the API exposes them. Provider tokens are environment-specific. A test provider token in production or a live token in staging creates reconciliation and incident-response confusion. Name them explicitly in configuration:

TELEGRAM_PAYMENTS_PROVIDER=stripe
TELEGRAM_PAYMENTS_PROVIDER_TOKEN='live-or-test-provider-token'
TELEGRAM_PAYMENTS_CURRENCY=USD

Failure cases are normal

Users close checkout midway. Cards decline. Providers time out. Telegram retries pre-checkout. Your service restarts after payment but before provisioning. Design support tooling that can look up Telegram charge IDs, provider charge IDs, order IDs, chat IDs, and fulfillment status without asking engineering to read logs.

Field notes

  • Validate total_amount and currency against server-side order truth at pre-checkout.
  • Test successful payment and duplicate webhook delivery separately; payment success does not prove idempotency.
  • Keep provider charge IDs immutable and indexed. They are reconciliation anchors.
  • Do not expose raw payment provider responses to users; convert failures into actionable order states.
  • Check Telegram's current supported provider list before committing a product to a processor.

Was this lesson helpful?

Sign in to rate