跳到正文
内测中 · 暂未向公众开放,仅限受邀用户注册。 申请访问 →
AywaPay
全部文章

开发者指南

在您的 Telegram 机器人中接受 USDT 付款(Node.js)

为您的 Telegram 机器人添加 /buy 命令:在服务器上创建加密货币账单,以按钮形式发送付款链接,并在签名 webhook 确认已付后交付。

· 阅读约 9 分钟

许多 Telegram 机器人都在卖东西:频道访问权限、VPN 配置、点数、数字文件。它们的用户往往已经持有 USDT,因此加密货币付款很合适。本指南用 Node.js 搭建完整流程:一个 /buy 命令、通过 AywaPay API v2 创建的账单、以内联按钮发送的付款链接,以及一个验证签名、给用户发消息并完成交付的 webhook 处理程序。

本文讲的是在您自己的机器人中收款。AywaPay Telegram 机器人 是另一回事:它向您(商户)发送付款提醒,并让您在聊天中创建账单和支付链接。两者可以同时使用。

流程如何运作

  1. 用户向您的机器人发送 /buy。
  2. 您的服务器用 POST /api/v2/invoices 创建账单,并使用一个与用户聊天关联的 order_id。
  3. 机器人回复一条消息和一个 Pay 按钮,点击即可打开账单的 payment_url。
  4. 用户用 TRON(TRC-20)或 BNB Smart Chain(BEP-20)上的 USDT,或您允许的其他币付款。
  5. AywaPay 向您的服务器发送签名的 webhook。您验证后将订单标记为已付,机器人给用户发消息并完成交付。

密钥存放在哪里

所有机密都留在您的服务器上:Telegram 机器人令牌、AywaPay API 密钥和 webhook 签名密钥。机器人只是一个聊天界面。切勿把 API 密钥放进 Telegram Mini App、网页、移动应用或任何其他客户端代码中,因为任何人都能在那里读取它,并以您的身份创建账单或读取您商店的数据。

  • 只在 Authorization: Bearer 请求头中发送 API 密钥。放在 URL 中的密钥会被拒绝。
  • 为商店开启 Allowed IPs,让密钥只能从您的服务器使用。
  • 从环境变量中加载这三个值,而不是写在代码里。

您需要准备什么

  • 从 Telegram 的 @BotFather 获取的机器人令牌。
  • 一个 AywaPay 商店及其 API 密钥。开发期间请使用商店的测试密钥(以 test_ 开头)。
  • 商店 Webhooks 标签页中的 webhook 签名密钥(以 whsec_ 开头)。
  • Node.js 18 或更高版本(使用内置的 fetch),以及一个用于 webhook 的公网 HTTPS 地址。
安装和环境变量
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

第 1 步:在 /buy 时创建账单

order_id 在每个商店内必须唯一。这里它是一个新生成的 ID,与用户的 chat id 一起保存,这样 webhook 就能找到该给谁发消息。价格在服务器上设定;绝不要从聊天中获取金额。

bot.js(第 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;
}

第 2 步:以按钮形式发送付款链接

机器人回复一个内联键盘按钮,其 url 为账单的 payment_url。点击后打开付款页面,页面显示金额、地址、二维码和倒计时。本示例通过长轮询(getUpdates)读取更新;使用 Telegram webhook 的方式也一样。

bot.js(第 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();

第 3 步:验证 webhook 并交付

账单的每次变化都会以 JSON POST 发送到您的 callback_url,其中包含事件 id、type 和 data(完整账单)。签名位于 X-AywaPay-Signature: t=<unix time>,v1=<hex> 中,v1 是用您的签名密钥对 <t>.<raw body> 计算的 HMAC-SHA256。请对原始请求体计算哈希,用常数时间比较,并拒绝过旧的时间戳。如何验证加密货币付款 webhook 解释了每一项检查。

bot.js(第 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);

只有 webhook 才能告诉您钱已到账。不要因为用户点了按钮或回到了聊天就交付。对于高价值订单,您还可以在交付前用 GET /api/v2/invoices/:id 读取账单。

需要处理哪些事件

事件机器人做什么
invoice.confirming告诉用户付款已在链上。
invoice.partially_paid告诉用户还欠多少。同一付款页面可以接收余款。
invoice.paid将订单标记为已付,表示感谢并交付。
invoice.overpaid与已付相同。全部金额计入您的余额。
invoice.underpaid时间到期,只收到部分款项。由您决定:请用户补齐、照常交付或退款。
invoice.cancelled关闭且未收到任何款项。再次提供 /buy。

商店的 Accept underpayment up to (%) 设置可让小额差额视为已付,这在交易所从金额中扣除手续费时很有帮助。账单过期后才到账的付款仍会入账,您也会收到相应的 webhook。请参阅 加密货币少付与多付。

幂等性:绝不重复交付

  • Webhook 会重试,直到您的服务器返回 2xx,因此同一事件 ID 可能到达多次。请把已处理的事件 ID 存入数据库,而不是内存。
  • 保护交付本身。 像示例那样,在交付前检查订单自身的状态,这样 paid 和 overpaid 事件就不会都触发交付。
  • 每个订单一张账单。 order_id 在每个商店内唯一;重复使用会返回 duplicate_order。如果创建请求超时而您不确定是否成功,请用 GET /api/v2/invoices?order_id=... 查询,而不是再创建一张。
  • 快速响应。 先返回 200,再执行耗时的工作,这样缓慢的交付不会导致重试。

不用真钱进行测试

使用 test_ 密钥时,每张账单都是测试账单。它没有充值地址,也不会接触任何区块链。付款页面有 Simulate 按钮(paid、overpaid、underpaid、expire),每个按钮都会发送您常规的 webhook,并带有 "test": true。向您的机器人发送 /buy,逐个点击按钮,检查机器人回复的消息。示例会在这些消息前加上 [Test]。

要在笔记本电脑上测试 webhook,请通过 HTTPS 隧道暴露本地端口,并把 PUBLIC_URL 设为该地址。一切正常后,换上正式密钥,自己支付一张小额账单。

Telegram 对销售商品和服务的机器人有自己的规定。上线前请阅读 Telegram 当前的机器人条款;如果不确定您所售内容适用哪些规定,请咨询律师。

费用

无开户费和月费。每笔付款收取 0.5% 加上该币种的网络费,由您承担(商店承担),或加在用户应付金额之上(客户承担)。提现到您自己的钱包收费 $0.25 加网络费。详见 价格。

常见问题

可以把 API 密钥放在机器人或 Mini App 里吗?
不可以。请把 API 密钥、机器人令牌和 webhook 密钥都留在您的服务器上。机器人和任何 Mini App 只显示由您的服务器创建的付款链接。
这和 AywaPay Telegram 机器人是一回事吗?
不是。AywaPay Telegram 机器人 面向商户:付款提醒,以及在聊天中创建账单和支付链接。本指南讲的是在您自己的机器人中收款。
用户可以用哪些币付款?
创建账单时传入 coins 列表,例如 ["USDT-TRC20", "USDT-BEP20"],或者不传,以提供商店接受的所有币种。请查看 支持的币种。
如果同一个 webhook 到达两次怎么办?
这很正常:webhook 会重试。保存您处理过的每个事件 ID,并在交付前检查订单状态,就不会有任何事情发生两次。

延伸阅读

立即开始

今天就开始接受加密货币支付

  1. 01申请访问
  2. 02通过邮件获取邀请
  3. 03添加商店,开始收款