Guida per sviluppatori
Accettare pagamenti in USDT nel tuo bot Telegram (Node.js)
Aggiungi un comando /buy al tuo bot Telegram: crea una fattura crypto sul tuo server, invia il link di pagamento come pulsante e consegna quando un webhook firmato dice pagato.
· 9 min di lettura
Molti bot Telegram vendono qualcosa: l'accesso a un canale, una configurazione VPN, crediti, un file digitale. I loro utenti spesso hanno già USDT, quindi un pagamento in crypto è la scelta naturale. Questa guida costruisce l'intero flusso in Node.js: un comando /buy, una fattura creata tramite l'API v2 di AywaPay, il link di pagamento inviato come pulsante inline e un gestore dei webhook che controlla la firma, scrive all'utente e consegna.
Qui si parla di pagamenti all'interno del tuo bot. Il bot Telegram di AywaPay è un'altra cosa: invia a te, il commerciante, gli avvisi di pagamento e ti permette di creare fatture e link di pagamento dalla chat. Puoi usarli entrambi.
Come funziona il flusso
- L'utente invia
/buyal tuo bot. - Il tuo server crea una fattura con
POST /api/v2/invoices, usando unorder_idche colleghi alla chat dell'utente. - Il bot risponde con un messaggio e un pulsante Paga che apre il
payment_urldella fattura. - L'utente paga in USDT su TRON (TRC-20) o BNB Smart Chain (BEP-20), oppure in un'altra criptovaluta che consenti.
- AywaPay invia un webhook firmato al tuo server. Lo verifichi, segni l'ordine come pagato e il bot scrive all'utente e consegna.
Dove stanno le chiavi
Tutto ciò che è segreto resta sul tuo server: il token del bot Telegram, la chiave API di AywaPay e il secret di firma dei webhook. Il bot è solo un'interfaccia di chat. Non mettere mai la chiave API in una Telegram Mini App, una pagina web, un'app mobile o qualsiasi altro codice lato client, perché chiunque potrebbe leggerla e creare fatture o leggere i dati del tuo negozio al posto tuo.
- Invia la chiave API solo nell'header
Authorization: Bearer. Una chiave nell'URL viene rifiutata. - Attiva IP consentiti per il negozio, così la chiave funziona solo dal tuo server.
- Carica tutti e tre i valori da variabili d'ambiente, non dal codice.
Cosa ti serve
- Un token del bot da @BotFather di Telegram.
- Un negozio AywaPay con la sua chiave API. Durante lo sviluppo usa la chiave di test del negozio (inizia con
test_). - Il secret di firma dei webhook del negozio (inizia con
whsec_), dalla sua scheda Webhook. - Node.js 18 o successivo (per il
fetchintegrato) e un indirizzo HTTPS pubblico per il webhook.
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 reachablePasso 1: crea la fattura su /buy
L'order_id deve essere unico per negozio. Qui è un nuovo id salvato accanto all'id della chat dell'utente, così il webhook sa a chi scrivere. Imposta il prezzo sul server; non prendere mai un importo dalla chat.
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;
}Passo 2: invia il link di pagamento come pulsante
Il bot risponde con un pulsante di tastiera inline il cui url è il payment_url della fattura. Toccandolo si apre la pagina di pagamento, che mostra l'importo, l'indirizzo, un codice QR e un conto alla rovescia. Questo esempio legge gli aggiornamenti con il long polling (getUpdates); un webhook di Telegram funziona allo stesso modo.
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();Passo 3: verifica il webhook e consegna
Ogni cambiamento della fattura viene inviato al tuo callback_url come POST JSON con un id dell'evento, un type e data (la fattura completa). La firma si trova in X-AywaPay-Signature: t=<unix time>,v1=<hex>, dove v1 è l'HMAC-SHA256 di <t>.<raw body> con il tuo secret di firma. Calcola l'hash sul body grezzo, confronta in tempo costante e rifiuta i timestamp vecchi. Come verificare i webhook dei pagamenti crypto spiega ogni controllo.
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);Solo il webhook ti dice che il denaro è arrivato. Non consegnare perché l'utente ha toccato il pulsante o è tornato nella chat. Per gli ordini di valore elevato puoi anche leggere la fattura con GET /api/v2/invoices/:id prima di consegnare.
Su quali eventi agire
| Evento | Cosa fa il bot |
|---|---|
invoice.confirming | Dice all'utente che il pagamento è sulla rete. |
invoice.partially_paid | Dice all'utente quanto resta da pagare. La stessa pagina di pagamento accetta il resto. |
invoice.paid | Segna l'ordine come pagato, ringrazia e consegna. |
invoice.overpaid | Come pagato. L'intero importo viene accreditato sul tuo saldo. |
invoice.underpaid | Il tempo è scaduto con solo una parte del denaro. Decidi: chiedere il resto, consegnare comunque o rimborsare. |
invoice.cancelled | Chiusa senza aver ricevuto nulla. Proponi di nuovo /buy. |
L'impostazione Accetta pagamenti insufficienti fino al (%) del negozio permette di considerare pagate le piccole differenze, utile quando un exchange trattiene la propria commissione dall'importo. I pagamenti che arrivano dopo la scadenza di una fattura vengono comunque accreditati e ricevi un webhook anche per questi. Vedi pagamenti crypto insufficienti ed eccedenti.
Idempotenza: non consegnare mai due volte
- I webhook vengono ritentati finché il tuo server non risponde 2xx, quindi lo stesso id evento può arrivare più di una volta. Salva gli id degli eventi gestiti nel database, non in memoria.
- Proteggi la consegna stessa. Controlla lo stato dell'ordine prima di consegnare, come fa l'esempio, così un evento paid e uno overpaid non possono consegnare entrambi.
- Una fattura per ordine.
order_idè unico per negozio; riutilizzarlo restituisceduplicate_order. Se una richiesta di creazione è andata in timeout e non sai se è riuscita, cercala conGET /api/v2/invoices?order_id=...invece di crearne un'altra. - Rispondi in fretta. Rispondi prima 200 ed esegui dopo il lavoro lento, così una consegna lenta non provoca un nuovo tentativo.
Provalo senza denaro reale
Con la chiave test_, ogni fattura è una fattura di test. Non ha un indirizzo di deposito e nulla tocca una blockchain. La pagina di pagamento ha i pulsanti Simula (pagato, pagamento eccedente, pagamento insufficiente, scadenza) e ognuno invia il tuo normale webhook con "test": true. Invia /buy al tuo bot, premi ogni pulsante e controlla i messaggi che il bot ti rimanda. L'esempio contrassegna quei messaggi con [Test].
Per provare il webhook dal tuo portatile, esponi la porta locale tramite un tunnel HTTPS e imposta PUBLIC_URL su di esso. Quando tutto funziona, sostituisci la chiave live e paga tu stesso una piccola fattura.
Telegram ha regole proprie per i bot che vendono beni e servizi. Leggi i termini attuali di Telegram per i bot prima del lancio e chiedi a un avvocato se non sei sicuro di cosa si applichi a ciò che vendi.
Quanto costa
Non ci sono costi di attivazione né canoni mensili. Ogni pagamento costa 0.5% più la commissione di rete della criptovaluta, pagata da te (Paga il negozio) o aggiunta al prezzo per l'utente (Paga il cliente). I prelievi sul tuo wallet costano $0.25 più la commissione di rete. Vedi i prezzi.
Domande frequenti
- Posso mettere la chiave API dentro il bot o in una Mini App?
- No. Tieni la chiave API, il token del bot e il secret dei webhook sul tuo server. Il bot e qualsiasi Mini App mostrano solo il link di pagamento creato dal tuo server.
- È lo stesso del bot Telegram di AywaPay?
- No. Il bot Telegram di AywaPay è per i commercianti: avvisi di pagamento, fatture e link di pagamento dalla chat. Questa guida riguarda l'incasso di pagamenti dentro il tuo bot.
- Con quali criptovalute possono pagare gli utenti?
- Passa una lista
coinsquando crei la fattura, per esempio["USDT-TRC20", "USDT-BEP20"], oppure omettila per offrire tutte le criptovalute che il negozio accetta. Vedi le criptovalute supportate. - Cosa succede se lo stesso webhook arriva due volte?
- È normale: i webhook vengono ritentati. Salva ogni id evento che gestisci e controlla lo stato dell'ordine prima di consegnare, e nulla succede due volte.