Overview
This guide is for a Telegram bot built on TeleBotHost or Bots.Business (the editor where you add commands and write JavaScript). You copy 10 commands, save your API key, and your bot can take UPI payments and add money to the user’s wallet automatically. No server, no webhook.
/onQR) and change nothing else.How it works
- User sends
/topup 100. The bot callscreate-orderon https://hexupi.xyz. - The bot sends a QR photo with Open Payment Page, Verify Payment and Cancel buttons.
- The user pays the exact
payableamount in any UPI app. - The bot asks the gateway
GET /api/v1/status/<id>every 3 seconds. The gateway reads the payment mail at that moment, so the answer is instant. - When the status is PAID the bot adds the money to the wallet once and sends a success message.
Before you start
- Create your account here, open My Gateway and save your UPI ID (
@famor@yesfam) and finish the alert setup shown inside the panel. Press Test connection.
You can also connect the gateway inside our Telegram bot: it guides you step by step. - Open Keys & URL and copy your API key (it starts with
hex_live_). - Open your bot in TeleBotHost / Bots.Business and find Commands → Add new command.
/set_hexupi_key.The 10 commands
Create these commands in your bot one by one. Each has its own section below with a Copy button.
| Command name | # | What it does | Where |
|---|---|---|---|
/set_hexupi_key | 1 | Admin saves the API key once | Step 2 |
/topup | 2 | User types /topup 100. Creates the order | Step 3 |
/onQR | 3 | Gateway answer: sends the QR photo + buttons | Step 4 |
/autocheck | 4 | Every 3 sec asks "is it paid?" | Step 5 |
/onAutoCheck | 5 | Reads the answer, repeats or goes to /check | Step 5 |
/check | 6 | Verify button + auto-check land here | Step 6 |
/onCheck | 7 | Credits the wallet (only once) | Step 6 |
/onQRExpire | 8 | Removes the QR picture after 10 min | Step 7 |
/cancel_topup | 9 | Cancel button | Step 7 |
/onApiError | 10 | Shown when the gateway cannot be reached | Step 7 |
/onQR is not /onqr.The two API calls you use
Everything in this guide is just these two calls. Your bot does them with HTTP.post and HTTP.get.
1. Create order POST
POST https://hexupi.xyz/api/v1/create-order
x-api-key: hex_live_xxxxxxxx
{ "amount": 100, "order_id": "W12345-1760000000000" }
→ { "ok": true, "id": "hex_ab12c", "amount": 100, "payable": 100.03,
"pay_url": "https://hexupi.xyz/pay/hex_ab12c", "upi": "upi://pay?pa=...",
"qr": "data:image/svg+xml...", "expires_at": 1760000600000, "status": "PENDING" }amountis what goes to the wallet. Allowed: 1 to 100000.payablecan be a few paise higher thanamount(for example 100.03). The customer must pay the payable amount exactly, so the gateway can match the payment.order_idis your own reference. It is optional.
2. Check status GET
GET https://hexupi.xyz/api/v1/status/hex_ab12c
→ { "ok": true, "id": "hex_ab12c", "status": "PAID", "paid": true,
"amount": 100, "payable": 100.03, "paid_at": 1760000000000, "expires_at": 1760000600000 }No API key is needed for the gateway id. status is PENDING, PAID or EXPIRED. Always credit the amount from this answer, never a number the user typed.
Step 2 · Save the API key
Create a command named /set_hexupi_key. Replace PUT_YOUR_TELEGRAM_ID_HERE with your own Telegram numeric id (or set a bot property called owner_id).
// Only the bot owner can run this.
var adminId = String(Bot.getProperty("owner_id") || "PUT_YOUR_TELEGRAM_ID_HERE");
if (String(user.telegramid) !== adminId) { Bot.sendMessage("Not authorized."); return; }
var key = String(params || "").trim();
if (!key || /\s/.test(key)) {
Bot.sendMessage("Usage: /set_hexupi_key YOUR_API_KEY");
return;
}
Bot.setProperty("hexupi_api_key", key, "string");
Bot.sendMessage("✅ HexPay API key saved. Now test with /topup 1");Then send your bot: /set_hexupi_key hex_live_xxxxxxxx and delete that chat message afterwards.
Step 3 · Create the payment
Command /topup. The user sends /topup 100.
// Usage: /topup 100
var amount = parseInt(String(params || "").trim(), 10);
if (!amount || amount < 1 || amount > 100000) {
Bot.sendMessage("Send the amount like this: /topup 100 (₹1 to ₹1,00,000)");
return;
}
var apiKey = Bot.getProperty("hexupi_api_key");
if (!apiKey) { Bot.sendMessage("❌ API key not set. Admin: /set_hexupi_key YOUR_KEY"); return; }
var uid = String(user.telegramid);
User.setProperty("deposit_amount", String(amount), "string");
// "please wait" message - /onQR deletes it when the QR is ready
var gen = Api.sendMessage({ chat_id: chat.chatid, text: "⏳ Creating payment link for ₹" + amount + "..." });
try {
var gid = (gen && gen.result && gen.result.message_id) ? gen.result.message_id : (gen && gen.message_id ? gen.message_id : null);
if (gid) { Bot.setProperty("gen_msg_id_" + uid, gid, "string"); }
} catch (e) {}
// Create the order. The answer comes to /onQR
HTTP.post({
url: "https://hexupi.xyz/api/v1/create-order",
headers: { "x-api-key": String(apiKey), "Content-Type": "application/json" },
body: JSON.stringify({ amount: amount, order_id: "W" + uid + "-" + Date.now() }),
success: "/onQR",
error: "/onApiError"
});The gateway answer is handled by the command named in success, here /onQR. If something fails, /onApiError runs.
Step 4 · Send the QR
Command /onQR. It reads the order, saves who owns it, sends the QR photo and starts the auto-check.
var QR_LIFETIME = 605; // seconds. The order lives 10 minutes, the QR picture is removed right after
var POLL_EVERY = 3; // seconds
try {
var res = (typeof content === "object") ? content : JSON.parse(content || "{}");
var uid = String(user.telegramid);
function esc(t) { return String(t == null ? "" : t).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }
// remove the "please wait" message
var genId = Bot.getProperty("gen_msg_id_" + uid);
if (genId) { try { Api.deleteMessage({ chat_id: chat.chatid, message_id: Number(genId) }); } catch (e) {} }
Bot.setProperty("gen_msg_id_" + uid, null, "string");
var orderId = res.id; // gateway order id (hex_xxxxx)
var amount = Number(res.amount); // wallet credit
var payable = Number(res.payable); // customer must pay EXACTLY this
var upi = res.upi || "";
var payUrl = res.pay_url || "";
if (res.ok === false || !orderId || !isFinite(amount) || amount <= 0) {
Bot.sendMessage("⚠️ Payment could not be created.\n" + String(JSON.stringify(res)).slice(0, 300));
return;
}
// Telegram cannot show SVG, so make a PNG QR from the UPI link
var qrUrl = upi ? ("https://api.qrserver.com/v1/create-qr-code/?size=600x600&margin=12&data=" + encodeURIComponent(upi)) : "";
// remember who owns this order and how much it is worth
Bot.setProperty("hex_owner_" + orderId, uid, "string");
Bot.setProperty("hex_amount_" + orderId, amount, "number");
Bot.setProperty("qr_order_id_" + uid, String(orderId), "string"); // "this user has a live order"
var caption =
"<b>💳 PAYMENT</b>\n\n" +
"💰 <b>Pay exactly:</b> ₹<code>" + payable.toFixed(2) + "</code>\n" +
(Math.abs(payable - amount) > 0.001 ? "🪙 <b>Wallet credit:</b> ₹<code>" + amount.toFixed(2) + "</code>\n" : "") +
"🆔 <b>Order:</b> <code>" + esc(orderId) + "</code>\n\n" +
"<i>Scan with any UPI app and pay the exact amount. Balance is added automatically.</i>";
var rows = [];
if (payUrl) { rows.push([{ text: "Open Payment Page", url: payUrl, style: "primary" }]); }
rows.push([
{ text: "Verify Payment", callback_data: "/check " + orderId, style: "success" },
{ text: "Cancel", callback_data: "/cancel_topup", style: "danger" }
]);
var kb = JSON.stringify({ inline_keyboard: rows });
var sent = null;
if (qrUrl) {
try { sent = Api.sendPhoto({ chat_id: chat.chatid, photo: qrUrl, caption: caption, parse_mode: "HTML", reply_markup: kb }); } catch (e) { sent = null; }
}
if (!sent) { // QR picture failed: still send the details + payment link
sent = Api.sendMessage({ chat_id: chat.chatid, text: caption, parse_mode: "HTML", reply_markup: kb });
}
var mid = (sent && sent.result && sent.result.message_id) ? sent.result.message_id : (sent && sent.message_id ? sent.message_id : null);
if (mid) { Bot.setProperty("qr_msg_id_" + uid, mid, "string"); }
// 1) remove the QR picture after 10 minutes 2) start checking for payment
Bot.run({ command: "/onQRExpire", run_after: QR_LIFETIME, options: { userId: uid, chatId: chat.chatid, order_id: String(orderId) } });
Bot.run({ command: "/autocheck", run_after: POLL_EVERY, options: { userId: uid, chatId: chat.chatid, order_id: String(orderId), attempt: 1 } });
} catch (e) {
Bot.sendMessage("❌ Gateway response error: " + e.message);
}upi link. If that picture ever fails, the bot still sends the same details with the Open Payment Page button, so the user can always pay.Step 5 · Auto-check (no button needed)
Two commands that work as a pair. /autocheck asks the gateway, /onAutoCheck reads the answer and either asks again or goes to /check.
// Step 1 of 2 - ask the gateway "is this order paid?"
var MAX_ATTEMPTS = 260; // 200 fast checks (10 min) + 60 slow checks (20 min) = 30 minutes
try {
var opts = (typeof options !== "undefined" && options) ? options : {};
var uid = String(opts.userId || user.telegramid);
var orderId = String(opts.order_id || "");
var attempt = Number(opts.attempt || 1);
if (!orderId) { return; }
// stop when the order is paid / cancelled / replaced (those clear qr_order_id)
var active = Bot.getProperty("qr_order_id_" + uid);
if (!active || String(active) !== orderId) { return; }
if (attempt > MAX_ATTEMPTS) { return; }
Bot.setProperty("autochk_" + uid, JSON.stringify({ o: orderId, a: attempt }), "string");
HTTP.get({
url: "https://hexupi.xyz/api/v1/status/" + encodeURIComponent(orderId),
success: "/onAutoCheck",
error: "/onAutoCheck"
});
} catch (err) {}// Step 2 of 2 - the gateway answered
var MAX_ATTEMPTS = 260;
try {
var uid = String(user.telegramid);
var st = {};
try { st = JSON.parse(Bot.getProperty("autochk_" + uid) || "{}"); } catch (e0) { st = {}; }
var orderId = String(st.o || "");
var attempt = Number(st.a || 1);
if (!orderId) { return; }
var active = Bot.getProperty("qr_order_id_" + uid);
if (!active || String(active) !== orderId) { return; }
var res = {};
try { res = (typeof content === "object" && content) ? content : JSON.parse(content || "{}"); } catch (e1) { res = {}; }
var status = String((res && res.status) || "").toUpperCase();
if (res && (res.paid === true || status === "PAID")) {
Bot.setProperty("autochk_" + uid, null, "string");
Bot.run({ command: "/check", options: { params: orderId, order_id: orderId } }); // go and credit the wallet
return;
}
// not paid yet: check again. Fast for 10 minutes, then slow (late payments)
if (attempt < MAX_ATTEMPTS) {
var wait = (attempt < 200) ? 3 : 20;
Bot.run({ command: "/autocheck", run_after: wait, options: { userId: uid, chatId: chat.chatid, order_id: orderId, attempt: attempt + 1 } });
}
} catch (err) {}It checks every 3 seconds for 10 minutes and then every 20 seconds for another 20 minutes. The loop stops by itself when the order is paid or cancelled.
Step 6 · Verify and add the money
/check is used by the Verify Payment button and by the auto-check. /onCheck is the only place where the wallet is credited.
// Called by the "Verify Payment" button AND by /onAutoCheck
try {
var orderId = params ? String(params).trim() : "";
if (!orderId && typeof options !== "undefined" && options) { orderId = String(options.order_id || options.params || "").trim(); }
var queryId = (request && (request.id || (request.callback_query && request.callback_query.id))) || null;
if (!orderId) {
if (queryId) { Api.answerCallbackQuery({ callback_query_id: queryId, text: "❌ Order id missing", show_alert: true }); }
return;
}
// an order can only be verified by the user who created it
var owner = Bot.getProperty("hex_owner_" + orderId);
if (!owner || String(owner) !== String(user.telegramid)) {
if (queryId) { Api.answerCallbackQuery({ callback_query_id: queryId, text: "This order is not yours.", show_alert: true }); }
return;
}
User.setProperty("verify_order_id", orderId, "string"); // /onCheck reads it from here
HTTP.get({
url: "https://hexupi.xyz/api/v1/status/" + encodeURIComponent(orderId),
success: "/onCheck",
error: "/onApiError"
});
} catch (err) {
Bot.sendMessage("⚠️ Error: " + err.message);
}try {
var uid = String(user.telegramid);
var chatId = chat.chatid;
var queryId = (typeof request !== "undefined" && request && (request.id || (request.callback_query && request.callback_query.id))) || null;
var res = {};
try { res = (typeof content === "object" && content) ? content : JSON.parse(content || "{}"); } catch (e) { res = {}; }
var orderId = String(User.getProperty("verify_order_id") || "");
if (!orderId) { return; }
if (String(Bot.getProperty("hex_owner_" + orderId) || "") !== uid) { return; } // not your order
function clearState() {
Bot.setProperty("qr_order_id_" + uid, null, "string"); // this also stops /autocheck
Bot.setProperty("qr_msg_id_" + uid, null, "string");
User.setProperty("verify_order_id", null, "string");
}
function say(text) {
if (queryId) { try { Api.answerCallbackQuery({ callback_query_id: queryId, text: text, show_alert: true }); } catch (e) {} }
}
// already credited before? (stops double credit)
if (Bot.getProperty("hex_claimed_" + orderId)) { say("✅ Already added to your balance."); clearState(); return; }
var paid = (res.paid === true || String(res.status || "").toUpperCase() === "PAID");
if (!paid) {
say(String(res.status || "").toUpperCase() === "EXPIRED" ? "Order expired. Create a new payment." : "Payment not received yet. Pay, then tap Verify again.");
return;
}
// ---- PAID. Claim FIRST, credit AFTER (so it can never run twice) ----
Bot.setProperty("hex_claimed_" + orderId, true, "boolean");
// credit the amount that the SERVER says, and compare it with what we created
var amount = Number(res.amount);
var expected = Number(Bot.getProperty("hex_amount_" + orderId) || 0);
if (!isFinite(amount) || amount <= 0 || (expected > 0 && Math.abs(expected - amount) > 0.009)) {
Bot.setProperty("hex_claimed_" + orderId, null, "boolean");
Bot.sendMessage("⚠️ Amount mismatch. Contact admin with Order ID: " + orderId);
return;
}
Libs.ResourcesLib.userRes("balance").add(amount);
var newBalance = Number(Libs.ResourcesLib.userRes("balance").value()) || 0;
// remove the QR picture
var qrMsg = Bot.getProperty("qr_msg_id_" + uid);
if (qrMsg) { try { Api.deleteMessage({ chat_id: chatId, message_id: Number(qrMsg) }); } catch (e) {} }
clearState();
Api.sendMessage({
chat_id: chatId,
parse_mode: "HTML",
text: "✅ <b>PAYMENT SUCCESSFUL</b>\n\n💰 Added: ₹<b>" + amount.toFixed(2) + "</b>\n📊 New balance: ₹<b>" + newBalance.toFixed(2) + "</b>\n🆔 <code>" + orderId + "</code>",
reply_markup: JSON.stringify({ inline_keyboard: [[{ text: "Shop Now", callback_data: "/start", style: "success" }]] })
});
// tell the admin
try {
var adminId = Bot.getProperty("owner_id");
if (adminId) {
Api.sendMessage({ chat_id: adminId, parse_mode: "HTML",
text: "🔔 <b>Wallet top-up</b>\nUser: <code>" + uid + "</code>\nAmount: ₹" + amount.toFixed(2) + "\nOrder: <code>" + orderId + "</code>" });
}
} catch (e) {}
if (queryId) { try { Api.answerCallbackQuery({ callback_query_id: queryId, text: "✅ Payment verified!" }); } catch (e) {} }
} catch (err) {
Bot.sendMessage("⚠️ Verification error: " + err.message);
}hex_claimed_<id> is saved before the money is added, so tapping Verify ten times adds it once, (3) the paid amount from the gateway must match the amount the bot created.Step 7 · Expiry, cancel and errors
// Removes only the QR PICTURE after 10 minutes.
// The order stays "live" in the background, so a late payment (up to ~30 min) is still credited.
try {
var o = (typeof options !== "undefined" && options) ? options : {};
var uid = String(o.userId || user.telegramid);
var chatId = o.chatId || chat.chatid;
var active = Bot.getProperty("qr_order_id_" + uid);
if (o.order_id && String(active) !== String(o.order_id)) { return; } // already paid / cancelled / new QR made
var mid = Bot.getProperty("qr_msg_id_" + uid);
if (mid) { try { Api.deleteMessage({ chat_id: chatId, message_id: Number(mid) }); } catch (e) {} }
Bot.setProperty("qr_msg_id_" + uid, null, "string");
Api.sendMessage({
chat_id: chatId,
text: "⏰ This QR expired.\nIf you already paid, your balance will still be added automatically.\nIf not, send /topup again."
});
} catch (err) {}try {
var uid = String(user.telegramid);
var queryId = (request && (request.id || (request.callback_query && request.callback_query.id))) || null;
var mid = Bot.getProperty("qr_msg_id_" + uid) || (request && request.message ? request.message.message_id : null);
if (mid) { try { Api.deleteMessage({ chat_id: chat.chatid, message_id: Number(mid) }); } catch (e) {} }
Bot.setProperty("qr_msg_id_" + uid, null, "string");
Bot.setProperty("qr_order_id_" + uid, null, "string"); // stops the auto-check
User.setProperty("verify_order_id", null, "string");
Api.sendMessage({ chat_id: chat.chatid, text: "❌ Payment cancelled." });
if (queryId) { Api.answerCallbackQuery({ callback_query_id: queryId }); }
} catch (err) {}// Runs when the gateway cannot be reached or returns an error
try {
var uid = String(user.telegramid);
var genId = Bot.getProperty("gen_msg_id_" + uid);
if (genId) { try { Api.deleteMessage({ chat_id: chat.chatid, message_id: Number(genId) }); } catch (e) {} }
Bot.setProperty("gen_msg_id_" + uid, null, "string");
var detail = "";
try { detail = String(content || "").slice(0, 300).replace(/&/g, "&").replace(/</g, "<"); } catch (e) {}
Api.sendMessage({
chat_id: chat.chatid,
parse_mode: "HTML",
text: "⚠️ <b>Could not connect to the payment gateway.</b>\nTry again in a minute." + (detail ? "\n\n<code>" + detail + "</code>" : "")
});
} catch (e) {
Bot.sendMessage("⚠️ Gateway error: " + e.message);
}Buying a product when balance is low
Use the same /onQR, /autocheck, /check and /onCheck. Only the first command is different: create the order for the missing amount and remember what the user wanted to buy.
// Example: /pay_upi (user does not have enough balance for a product)
// 1) save what the user wants to buy 2) create an order only for the MISSING amount
var price = 250; // product price
var balance = Number(Libs.ResourcesLib.userRes("balance").value()) || 0;
var needToPay = Math.max(price - balance, 0);
if (needToPay <= 0) { /* enough balance - deliver directly */ return; }
User.setProperty("buy_prod_idx", 0, "number"); // your own product / plan ids
User.setProperty("buy_plan_idx", 1, "number");
// payAmount must be 1 - 100000 whole or 2-decimal rupees
var payAmount = Math.min(Math.max(Number(needToPay.toFixed(2)), 1), 100000);
HTTP.post({
url: "https://hexupi.xyz/api/v1/create-order",
headers: { "x-api-key": String(Bot.getProperty("hexupi_api_key")), "Content-Type": "application/json" },
body: JSON.stringify({ amount: payAmount, order_id: "P" + user.telegramid + "-" + Date.now() }),
success: "/onQR", // same /onQR as the wallet top-up
error: "/onApiError"
});Then add this small block to /onCheck after the wallet is credited. It finishes the purchase on its own, so the user does not need to press anything again.
// Put this inside /onCheck, right after: newBalance = ...value()
// The wallet was just credited. If the user was in the middle of a purchase, finish it now.
var pIdx = User.getProperty("buy_prod_idx");
var pPlan = User.getProperty("buy_plan_idx");
if (pIdx !== null && pIdx !== undefined && pPlan !== null && pPlan !== undefined) {
User.setProperty("buy_prod_idx", null);
User.setProperty("buy_plan_idx", null);
Bot.run({ command: "/confirm_buyitem", options: { params: pIdx + " " + pPlan } }); // YOUR delivery command
return; // skip the plain "payment successful" message
}Late payments
An order is valid for 10 minutes, but the gateway still accepts a payment made up to about 20 minutes after that. This guide keeps checking for 30 minutes, and only hides the QR picture after 10 minutes, so a customer who pays a little late still gets the balance.
cron.php job running every minute, otherwise only payments made while the order is still active are picked up quickly.Test checklist
- Send
/set_hexupi_key YOUR_KEY. You should see the green saved message. - Send
/topup 1. A QR with Pay exactly should arrive in a few seconds. - Pay the exact amount shown. Within about 5 seconds you should get PAYMENT SUCCESSFUL and the QR photo disappears.
- Tap Verify Payment on an old QR or send
/topup 1again: the same order must never add money twice. - Send
/topup 1and tap Cancel. The QR is removed and nothing is added.
Troubleshooting
| Problem | What to check |
|---|---|
| “API key not set” | Run /set_hexupi_key YOUR_KEY as the owner. Check that owner_id / your Telegram id is correct in that command. |
“Could not connect to the payment gateway” with Invalid API key | The key is wrong or was rolled. Copy it again from Keys & URL and save it again. |
Gateway not configured | Finish the UPI ID and alert setup in My Gateway first (or connect it inside our Telegram bot). |
Nothing happens after /topup | Is the command named exactly /onQR? Command names are case sensitive. Also look at your bot’s error log. |
| QR photo does not show but the message does | The QR picture service was busy. Use Open Payment Page, or try again. Payment still works. |
| User paid, balance not added | Open https://hexupi.xyz/api/v1/status/ORDER_ID in a browser. PAID: the bot commands are not named exactly or /onCheck has an error. PENDING: the gateway did not read the payment mail, so check the mail connection (press Test connection) and that the user paid the exact payable amount. |
| Wallet got a wrong amount | Credit amount, not payable. This guide already does that. |
| Wallet credited twice | Make sure hex_claimed_<id> is saved before .add(amount), exactly like /onCheck above. |
amount must be 1-100000 | The gateway accepts ₹1 to ₹1,00,000 per order. |
Still stuck? Contact support on Telegram @FrenzyHex and send your order id and the error text. The full reference is in the main API docs.