Skip to content
Private beta · Not open to the public yet. Accounts are by invitation only. Request access →
AywaPay
All articles

Developer guide

Accept USDT payments in your Telegram bot (Node.js)

Add a /buy command to your Telegram bot: create a crypto invoice on your server, send the payment link as a button, and deliver when a signed webhook says paid.

· 9 min read

Many Telegram bots sell something: access to a channel, a VPN config, credits, a digital file. Their users often hold USDT already, so a crypto payment fits. This guide builds the whole flow in Node.js: a /buy command, an invoice created through the AywaPay API v2, the payment link sent as an inline button, and a webhook handler that checks the signature, messages the user and delivers.

This is about payments inside your own bot. The AywaPay Telegram bot is a different thing: it sends you, the merchant, payment alerts and lets you create invoices and payment links from chat. You can use both.

How the flow works

  1. The user sends /buy to your bot.
  2. Your server creates an invoice with POST /api/v2/invoices, using an order_id that you link to the user's chat.
  3. The bot replies with a message and a Pay button that opens the invoice's payment_url.
  4. The user pays in USDT on TRON (TRC-20) or BNB Smart Chain (BEP-20), or another coin you allow.
  5. AywaPay sends a signed webhook to your server. You verify it, mark the order paid, and the bot messages the user and delivers.

Where the keys live

Everything secret stays on your server: the Telegram bot token, the AywaPay API key and the webhook signing secret. The bot is only a chat interface. Never put the API key in a Telegram Mini App, a web page, a mobile app or any other client code, because anyone could read it there and create invoices or read your store's data as you.

  • Send the API key only in the Authorization: Bearer header. A key in the URL is refused.
  • Turn on Allowed IPs for the store so the key only works from your server.
  • Load all three values from environment variables, not from the code.

What you need

  • A bot token from Telegram's @BotFather.
  • A AywaPay store with its API key. While you build, use the store's test key (it starts with test_).
  • The store's webhook signing secret (starts with whsec_) from its Webhooks tab.
  • Node.js 18 or newer (for the built-in fetch) and a public HTTPS address for the webhook.
Install and environment
npm install express

TELEGRAM_BOT_TOKEN=123456:ABC...        # from @BotFather
AYWAPAY_API_KEY=test_...                # test key while building
AYWAPAY_WEBHOOK_SECRET=whsec_...        # store → Webhooks
PUBLIC_URL=https://bot.example.com      # where this server is reachable

Step 1: create the invoice on /buy

The order_id must be unique per store. Here it is a new id saved next to the user's chat id, so the webhook can find who to message. Set the price on the server; never take an amount from the chat.

bot.js (part 1)
import crypto from "node:crypto";
import express from "express";

const TG = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}`;
const API = "https://api.aywapay.com/api/v2";

// Use a real database in production. Maps are lost on restart.
const orders = new Map();        // order_id -> { chatId, status }
const handledEvents = new Set(); // event ids already processed

async function tg(method, body) {
  const res = await fetch(`${TG}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  const json = await res.json();
  if (!json.ok) throw new Error(json.description);
  return json.result;
}

async function createInvoice(chatId) {
  const orderId = `tg-${chatId}-${crypto.randomUUID()}`;
  const res = await fetch(`${API}/invoices`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.AYWAPAY_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      order_id: orderId,
      description: "Premium access, 30 days",
      price_amount: "9.99",
      price_currency: "USD",
      coins: ["USDT-TRC20", "USDT-BEP20"],
      callback_url: `${process.env.PUBLIC_URL}/webhooks/aywapay`,
    }),
  });
  if (!res.ok) throw new Error(`invoice failed: ${res.status}`);
  const invoice = await res.json();
  orders.set(orderId, { chatId, status: invoice.status, invoiceId: invoice.id });
  return invoice;
}

Step 2: send the payment link as a button

The bot replies with an inline keyboard button whose url is the invoice's payment_url. Tapping it opens the payment page, which shows the amount, the address, a QR code and a countdown. This sample reads updates with long polling (getUpdates); a Telegram webhook works the same way.

bot.js (part 2)
async function onMessage(msg) {
  if (msg.text !== "/buy") return;
  try {
    const invoice = await createInvoice(msg.chat.id);
    await tg("sendMessage", {
      chat_id: msg.chat.id,
      text: "Premium access, 30 days: 9.99 USD in USDT (TRON or BNB Smart Chain).",
      reply_markup: {
        inline_keyboard: [[{ text: "Pay with USDT", url: invoice.payment_url }]],
      },
    });
  } catch (err) {
    console.error(err);
    await tg("sendMessage", { chat_id: msg.chat.id, text: "Sorry, try again in a minute." });
  }
}

async function poll(offset = 0) {
  try {
    const updates = await tg("getUpdates", { offset, timeout: 30 });
    for (const update of updates) {
      offset = update.update_id + 1;
      if (update.message) await onMessage(update.message);
    }
  } catch (err) {
    console.error(err);
  }
  setImmediate(() => poll(offset));
}
poll();

Step 3: verify the webhook and deliver

Each invoice change is sent to your callback_url as a JSON POST with an event id, a type and data (the full invoice). The signature is in X-AywaPay-Signature: t=<unix time>,v1=<hex>, where v1 is the HMAC-SHA256 of <t>.<raw body> with your signing secret. Hash the raw body, compare in constant time, and refuse old timestamps. How to verify crypto payment webhooks explains each check.

bot.js (part 3)
const app = express();

// Keep the raw body: the signature is over the exact bytes.
app.post("/webhooks/aywapay", express.raw({ type: "application/json" }), async (req, res) => {
  const header = req.get("X-AywaPay-Signature") ?? "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((part) => part.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.AYWAPAY_WEBHOOK_SECRET) // whsec_…
    .update(`${t}.${req.body}`)
    .digest("hex");
  const isFresh = Math.abs(Date.now() / 1000 - Number(t)) < 300; // refuse replays
  const isValid =
    v1?.length === expected.length && crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
  if (!isFresh || !isValid) return res.status(400).send("bad signature");

  const event = JSON.parse(req.body);
  // The same event can arrive twice: process each event.id once.
  if (handledEvents.has(event.id)) return res.sendStatus(200);
  handledEvents.add(event.id);
  res.sendStatus(200); // answer fast, then do the work

  const order = orders.get(event.data?.order_id);
  if (!order) return;
  const test = event.test ? "[Test] " : "";

  if (event.type === "invoice.paid" || event.type === "invoice.overpaid") {
    if (order.status === "paid") return; // never deliver twice
    order.status = "paid";
    await tg("sendMessage", { chat_id: order.chatId, text: `${test}Payment received, thank you.` });
    await deliver(order); // grant access, send the file, add credits...
  } else if (event.type === "invoice.confirming") {
    await tg("sendMessage", { chat_id: order.chatId, text: `${test}Payment seen, confirming on the network.` });
  } else if (event.type === "invoice.partially_paid") {
    const { amount_remaining, coin } = event.data;
    await tg("sendMessage", {
      chat_id: order.chatId,
      text: `${test}Part of the payment arrived. Still due: ${amount_remaining} ${coin ?? ""}. Use the same Pay button.`,
    });
  } else if (event.type === "invoice.underpaid" || event.type === "invoice.cancelled") {
    await tg("sendMessage", { chat_id: order.chatId, text: `${test}The invoice has closed. Send /buy to start again.` });
  }
});

async function deliver(order) {
  // Your fulfilment goes here.
}

app.listen(3000);

Only the webhook tells you the money arrived. Don't deliver because the user tapped the button or came back to the chat. For high-value orders you can also read the invoice with GET /api/v2/invoices/:id before you deliver.

Which events to act on

EventWhat the bot does
invoice.confirmingTells the user the payment is on the network.
invoice.partially_paidTells the user how much is still due. The same payment page takes the rest.
invoice.paidMarks the order paid, says thank you and delivers.
invoice.overpaidSame as paid. All of it is credited to your balance.
invoice.underpaidTime ran out with part of the money. Decide: ask for the rest, deliver anyway, or refund.
invoice.cancelledClosed with nothing received. Offer /buy again.

The store's Accept underpayment up to (%) setting lets small shortfalls count as paid, which helps when an exchange takes its fee out of the amount. Payments that arrive after an invoice expired are still credited, and you get a webhook for them. See crypto underpayments and overpayments.

Idempotency: never deliver twice

  • Webhooks are retried until your server answers 2xx, so the same event id can arrive more than once. Store handled event ids in your database, not in memory.
  • Guard the delivery itself. Check the order's own status before delivering, as the sample does, so a paid and an overpaid event can't both deliver.
  • One invoice per order. order_id is unique per store; reusing it returns duplicate_order. If a create request timed out and you're unsure whether it worked, look it up with GET /api/v2/invoices?order_id=... instead of creating another.
  • Answer fast. Reply 200 first and run slow work after, so a slow delivery doesn't cause a retry.

Test it without real money

With the test_ key, every invoice is a test invoice. It has no deposit address and nothing touches a blockchain. The payment page has Simulate buttons (paid, overpaid, underpaid, expire), and each one sends your normal webhook with "test": true. Send /buy to your bot, press each button and check the messages the bot sends back. The sample marks those messages with [Test].

To test the webhook from your laptop, expose the local port through an HTTPS tunnel and set PUBLIC_URL to it. When everything works, swap in the live key and pay one small invoice yourself.

Telegram has its own rules for bots that sell goods and services. Read Telegram's current bot terms before you launch, and ask a lawyer if you're unsure what applies to what you sell.

What it costs

There is no setup or monthly fee. Each payment costs 0.5% plus the coin's network fee, paid by you (Store pays) or added on top for the user (Customer pays). Withdrawals to your own wallet cost $0.25 plus the network fee. See pricing.

Frequently asked questions

Can I put the API key inside the bot or a Mini App?
No. Keep the API key, the bot token and the webhook secret on your server. The bot and any Mini App only show the payment link that your server created.
Is this the same as the AywaPay Telegram bot?
No. The AywaPay Telegram bot is for merchants: payment alerts, invoices and payment links from chat. This guide is about taking payments inside your own bot.
Which coins can users pay with?
Pass a coins list when you create the invoice, for example ["USDT-TRC20", "USDT-BEP20"], or leave it out to offer every coin the store accepts. See the supported coins.
What if the same webhook arrives twice?
That is normal: webhooks are retried. Store each event id you handle and check the order's status before delivering, and nothing happens twice.

Keep reading

Get started

Start accepting crypto today

  1. 01Request access
  2. 02Get your invite by email
  3. 03Add your store and get paid