Telegram Bot Payments with grammY: Invoice, Pre-Checkout and Success

After configuring a payment provider for the bot, use grammY to send an invoice and handle the payment lifecycle.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Bot } from "https://deno.land/x/grammy@v1.25.0/mod.ts";

const bot = new Bot('BOT_TOKEN');

bot.command('start', async ctx => {
  try {
    await ctx.replyWithInvoice(
      'Product title',
      'Product description',
      'unique-payload',
      'PROVIDER_TOKEN',
      'USD',
      [{ label: 'Product', amount: 1000 }]
    );
  } catch (error) {
    console.error(error);
    await ctx.reply('Could not create the invoice. Please try again.');
  }
});

bot.on('pre_checkout_query', ctx => ctx.answerPreCheckoutQuery(true));

bot.on('message:successful_payment', async ctx => {
  console.log('Payment succeeded:', ctx.message.successful_payment);
  await ctx.reply('Payment successful. Thank you!');
});

bot.start();

Run with deno run --allow-net your-script.ts, then send /start to the bot.

Invoice message

Verify the payload, amount, currency, and payment result on a trusted backend before granting a purchased item.