Overview
Everything is plain HTTPS + JSON. You need two things from your side: a server that calls the API (never the browser or the app itself) and, optionally, a public URL that receives the payment webhook.
https://hexupi.xyz
Set up once (2 minutes)
- Sign up / log in, open My Gateway and save your UPI ID (
@fam/@yesfam) and finish the alert setup shown inside the panel. Press Test connection. - Open Keys & URL and copy your API key.
- Use any code below. That is the whole setup.
How a payment works
- Your server calls
POST /api/v1/create-orderand getspay_url,upiandqr. - You show the customer the QR code or send them the
pay_urllink. - The customer pays the exact
payableamount from any UPI app. - The gateway reads your bank / FamPay alert mail, matches it to the order and marks it PAID.
- The gateway sends a signed webhook to your server. You verify the signature and deliver the product / credit the wallet.
Where you can integrate
- Websites - plain PHP, Node.js, Python, Ruby, Go, .NET, Java, any framework.
- Bots - Telegram, Discord, WhatsApp, Slack, Messenger.
- Mobile apps - Android (Kotlin/Java), iOS (Swift), Flutter, React Native.
- E-commerce - WooCommerce, Shopify (via custom app), custom carts.
- Scripts - cURL, Postman, shell automation, cron jobs.
Popup checkout Recommended
The payment page opens as a popup on your own website, like Razorpay. The customer never leaves your site. When the payment is detected, a success tick is shown and the popup closes by itself. If you are building a new website integration, start here.
- Add
checkout.jsto your payment page (one script tag). - Your server calls create-order and returns the
pay_urlto the browser. - Your page calls
HexPay.open({ pay_url }). The popup opens. - After payment the popup closes. The customer lands on your
redirectpage, or youronSuccessfunction runs. - Your webhook (or the signed redirect) confirms the payment on your server. Only then deliver the product.
Step 1: add the script
<script src="https://hexupi.xyz/checkout.js"></script>
Step 2: create the order on your server
<?php
$apiKey = "YOUR_API_KEY"; // from Keys & URL
$orderId = "ORD-" . time(); // must be unique for every order
$amount = 25; // rupees
$ch = curl_init("https://hexupi.xyz/api/v1/create-order");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["x-api-key: $apiKey", "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode([
"amount" => $amount,
"order_id" => $orderId,
"redirect" => "https://yoursite.com/payment-success.php"
]),
]);
$res = curl_exec($ch);
curl_close($ch);
header("Content-Type: application/json");
echo $res; // contains pay_url
Node.js and Python versions of the same call are in Create order.
Step 3: open the popup from your button
<button id="payBtn">Pay ₹25</button>
<script>
document.getElementById('payBtn').onclick = async function () {
const r = await fetch('create_order.php');
const data = await r.json();
if (!data.pay_url) { alert(data.error || 'Order failed'); return; }
HexPay.open({
pay_url: data.pay_url,
onClose: function () { alert('Payment cancelled'); }
});
};
</script>
After payment the popup closes and the customer is sent to your redirect URL with the signed parameters, exactly like the normal checkout.
Step 4: verify the payment
Your redirect page receives order_id, id, status, amount and sig. Always check sig, otherwise anyone can type status=PAID in the address bar.
<?php
$apiKey = "YOUR_API_KEY";
$id = $_GET['id'] ?? '';
$orderId = $_GET['order_id'] ?? '';
$amount = $_GET['amount'] ?? '';
$sig = $_GET['sig'] ?? '';
$expected = hash_hmac('sha256', "$id|$orderId|$amount|PAID", $apiKey);
if (hash_equals($expected, $sig)) {
// genuine payment: mark the order paid, give access / download
echo "Payment successful";
} else {
echo "Invalid payment";
}
Stay on the same page (no redirect)
Pass onSuccess and the customer stays on your page:
HexPay.open({
pay_url: data.pay_url,
onSuccess: function (r) {
// r = { order_id, id, amount, payable, status: 'PAID', redirect }
showThankYou();
}
});
onSuccess runs in the browser, so it can be faked. Before you deliver anything, confirm the payment on your server with the webhook or the status API.Options
| Option | What it does |
|---|---|
pay_url | The pay_url from create-order (the plain order id also works). |
onSuccess(r) | Runs when the payment is done, after the popup closes. |
onClose() | Runs when the customer closes the popup without paying. |
onExpire() | Runs when the 10-minute order window ends. |
redirect: true | Use together with onSuccess if you also want the redirect. |
HexPay.close() | Closes the popup from your code. |
No JavaScript needed for a simple link or button. Any element with data-hexpay opens the popup on click:
<a href="#" data-hexpay="https://hexupi.xyz/pay/ORDER_ID">Pay now</a>
Good to know
- The popup works on any website (HTTP or HTTPS), on desktop and on mobile. On a phone it slides up from the bottom.
- Customers can close it with the × button or Esc. They are asked to confirm before a pending payment is cancelled.
- If the payment page does not load within 9 seconds, the popup shows an "Open in a new tab" link, so the customer is never stuck.
- Your existing integrations keep working. The old way (redirecting to
pay_url) is still supported, see Website checkout.
Quick start
Three calls are all you need: create an order, show the pay link, verify the webhook.
POST /api/v1/create-order with your key.
Send the customer to pay_url or show the QR.
Check the x-signature on the webhook, then deliver.
curl -X POST https://hexupi.xyz/api/v1/create-order \
-H "x-api-key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"amount":199,"order_id":"ORD1001",
"webhook":"https://yoursite.com/hook",
"redirect":"https://yoursite.com/thanks"}'
GET /api/v1/status/<order_id> status: PENDING | PAID | EXPIRED
{
"event": "payment.success",
"id": "hex_...",
"order_id": "ORD1001",
"status": "PAID",
"amount": 199.00,
"payable": 199.03,
"paid_at": "2026-10-07T07:00:00Z"
}
Header x-signature = HMAC-SHA256(raw_body, your_api_key)
Credit your user once per order_id, then reply HTTP 200.
After payment the customer returns to your redirect URL with
?order_id=..&id=..&status=PAID
Full examples in PHP, Node.js and Python are in Create order and Webhooks.
Authentication
Send your API key in the x-api-key header on every /api/v1/ call.
x-api-key: YOUR_API_KEY Content-Type: application/json
API key & rolls
Your key lives in Keys & URL. Rolling creates a new key and the old one stops working immediately.
| Rule | Detail |
|---|---|
| Free rolls | Every account can roll its key a fixed number of times (10 by default). |
| After the limit | The next roll needs a roll pack. Pay once and the rolls are added back automatically. |
| Chart | Keys & URL shows how many orders were created with your key, per day. |
401.Payment lifecycle
| Status | Meaning |
|---|---|
| PENDING | Order created, waiting for the customer to pay. |
| PAID | Payment alert matched. Safe to deliver the product. |
| EXPIRED | Not paid within 10 minutes. Create a new order. |
- Order window: 10 minutes after creation. A payment that lands a little after expiry (up to about 20 minutes) is still matched and marked
PAID. - Exact amount: the customer must pay
payable, notamount. If two orders for the same amount are open at the same time, the gateway adds a few paise (for example 199.00 to 199.01) so each payment matches only one order. Always showpayableto the customer. - Speed: a payment is normally confirmed within seconds to a minute after the bank / FamPay alert mail reaches your inbox.
Create order POST
/api/v1/create-order
| Field | Type | Required | Description |
|---|---|---|---|
amount | number | Yes | Amount in INR, from 1 to 100000. Example 199 or 499.50. |
order_id | string | Recommended | Your own reference (user id, cart id, wallet top-up id). Make it unique per order. It is returned in the webhook and shown in the UPI note. |
webhook | string | No | Public https URL that receives the payment webhook. Private / local addresses (localhost, 192.168.x.x) are rejected. If omitted, your account's default webhook (if you set one) is used. |
redirect | string | No | Optional. A page on your site (https) for this one order. If you leave it out, the customer is sent back to the same website they started the payment from automatically, so one API key can run on any number of websites without a redirect URL for each. After paying they see "Payment Successful", then a 5 second countdown, then your page with the order info and a signature appended. Use redirect only when you want an exact page (for example /thanks) or when the order is created from a bot (bots have no website to return to). |
<?php
$apiKey = "YOUR_API_KEY"; // server-side only
$ch = curl_init("https://hexupi.xyz/api/v1/create-order");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["x-api-key: $apiKey", "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 199,
"order_id" => "ORD-" . time(), // unique per order
"webhook" => "https://yoursite.com/hexpay-webhook.php",
"redirect" => "https://yoursite.com/thanks",
]),
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
if (empty($res["ok"])) die($res["error"] ?? "Gateway error");
// Save $res["id"] with your order, then redirect to checkout
header("Location: " . $res["pay_url"]);
const r = await fetch("https://hexupi.xyz/api/v1/create-order", {
method: "POST",
headers: {
"x-api-key": process.env.HEX_API_KEY,
"Content-Type": "application/json"
},
body: JSON.stringify({
amount: 199,
order_id: "ORD-" + Date.now(),
webhook: "https://yoursite.com/hexpay-webhook",
redirect: "https://yoursite.com/thanks"
})
});
const o = await r.json();
if (!r.ok || !o.ok) throw new Error(o.error || "Gateway error");
console.log(o.pay_url, o.payable);
import os, time, requests
r = requests.post(
"https://hexupi.xyz/api/v1/create-order",
headers={"x-api-key": os.environ["HEX_API_KEY"]},
json={
"amount": 199,
"order_id": f"ORD-{int(time.time())}",
"webhook": "https://yoursite.com/hexpay-webhook",
"redirect": "https://yoursite.com/thanks",
},
timeout=20,
)
o = r.json()
if not r.ok or not o.get("ok"):
raise Exception(o.get("error", "Gateway error"))
print(o["pay_url"], o["payable"])
curl -X POST https://hexupi.xyz/api/v1/create-order \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"amount":199,"order_id":"ORD-1001","webhook":"https://yoursite.com/hexpay-webhook"}'
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body, _ := json.Marshal(map[string]any{
"amount": 199,
"order_id": "ORD-1001",
"webhook": "https://yoursite.com/hexpay-webhook",
})
req, _ := http.NewRequest("POST",
"https://hexupi.xyz/api/v1/create-order",
bytes.NewBuffer(body))
req.Header.Set("x-api-key", os.Getenv("HEX_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
fmt.Println(string(raw))
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
var json = """
{"amount":199,"order_id":"ORD-1001","webhook":"https://yoursite.com/hexpay-webhook"}
""";
var req = HttpRequest.newBuilder()
.uri(URI.create("https://hexupi.xyz/api/v1/create-order"))
.header("x-api-key", System.getenv("HEX_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
var res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body());
using System.Net.Http.Json;
var http = new HttpClient();
http.DefaultRequestHeaders.Add("x-api-key",
Environment.GetEnvironmentVariable("HEX_API_KEY"));
var res = await http.PostAsJsonAsync(
"https://hexupi.xyz/api/v1/create-order",
new {
amount = 199,
order_id = "ORD-1001",
webhook = "https://yoursite.com/hexpay-webhook"
});
var json = await res.Content.ReadAsStringAsync();
Console.WriteLine(json);
require "net/http"
require "json"
uri = URI("https://hexupi.xyz/api/v1/create-order")
req = Net::HTTP::Post.new(uri)
req["x-api-key"] = ENV["HEX_API_KEY"]
req["Content-Type"] = "application/json"
req.body = {
amount: 199,
order_id: "ORD-1001",
webhook: "https://yoursite.com/hexpay-webhook"
}.to_json
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |h|
h.request(req)
end
puts res.body
Response
{
"ok": true,
"id": "hex_ghr1f",
"order_id": "ORD-1001",
"amount": 199,
"payable": 199.01,
"pay_url": "https://hexupi.xyz/pay/hex_ghr1f",
"upi": "upi://pay?pa=yourname@fam&pn=HexStore&am=199.01&cu=INR&tn=ORD-1001",
"qr": "data:image/png;base64,iVBORw0KGgo...",
"qr_url": "https://hexupi.xyz/qr.php?id=hex_ghr1f",
"expires_at": 1728189400000,
"status": "PENDING"
}
| Field | Use it for |
|---|---|
id | The gateway order id (hex_...). Store it with your order. Used for status checks and it is the idempotency key in the webhook. |
payable | The exact amount the customer must pay. Show this one. |
pay_url | Hosted checkout page with QR, UPI buttons and live status. Easiest option: just send this link. |
upi | The upi://pay?... deep link. Open it on mobile, or turn it into your own QR image. |
qr | Ready QR code as a PNG data-URI. Works in an <img> tag, and bots can decode the base64 part and send it as a photo (see QR codes). The old SVG version is in qr_svg. |
qr_url | Link to the QR as a normal PNG image. Use this for Telegram bots (sendPhoto with this URL), WhatsApp and emails. No QR library needed. |
expires_at | Unix time in milliseconds when the 10-minute window ends. |
Check status GET
/api/v1/status/{id}
{id} is either the gateway id (hex_..., no key needed) or your own order_id (needs your x-api-key, and only your orders are searched). If you reused the same order_id twice, the newest order is returned, so keep them unique.
curl https://hexupi.xyz/api/v1/status/hex_ghr1f # or with your own order_id (needs your key): curl -H "x-api-key: YOUR_API_KEY" https://hexupi.xyz/api/v1/status/ORD-1001
{
"ok": true,
"id": "hex_ghr1f",
"order_id": "ORD-1001",
"status": "PAID",
"paid": true,
"amount": 199,
"payable": 199.01,
"paid_at": 1728189400000,
"expires_at": 1728189400000
}
PENDING) as a backup. The Telegram bot example below uses both.
Webhooks
When an order is paid, the gateway sends POST to the webhook URL you gave in create-order.
{
"event": "payment.success",
"id": "hex_ghr1f",
"order_id": "ORD-1001",
"status": "PAID",
"amount": 199,
"payable": 199.01,
"paid_at": 1728189400000
}
| Item | Details |
|---|---|
| Headers | x-signature (same value also in x-paygate-signature), Content-Type: application/json |
| Signature | Lower-case hex of HMAC-SHA256(raw request body, your API key) |
| Query string | For simple PHP/GET scripts the URL also gets ?order_id=&id=&status=PAID&amount= added. Do not trust these; trust only the signed body. |
| Success | Reply with any HTTP 2xx status. Anything else counts as a failure. |
| Retries | After a failure the gateway retries after 1 min, 5 min, 15 min, 1 hour and 6 hours, then marks it failed. You can also resend from Webhook logs. |
id.
<?php
$apiKey = "YOUR_API_KEY";
$raw = file_get_contents("php://input"); // RAW body, do not re-encode
$sig = $_SERVER["HTTP_X_SIGNATURE"] ?? "";
if (!hash_equals(hash_hmac("sha256", $raw, $apiKey), $sig)) {
http_response_code(401);
exit("bad signature");
}
$ev = json_decode($raw, true);
if (($ev["event"] ?? "") === "payment.success") {
// $ev["id"] = gateway order id
// $ev["order_id"] = YOUR reference
// $ev["amount"] = amount
// Retries / manual resends can deliver the same event again
// -> mark paid ONCE per $ev["id"]
}
http_response_code(200);
echo "ok";
const express = require("express");
const crypto = require("crypto");
const app = express();
const API_KEY = process.env.HEX_API_KEY;
// IMPORTANT: express.raw gives the untouched body.
// JSON.stringify(req.body) will NOT match the signature.
app.post("/hexpay-webhook", express.raw({ type: "*/*" }), (req, res) => {
const sig = String(req.headers["x-signature"] || "");
const calc = crypto.createHmac("sha256", API_KEY)
.update(req.body)
.digest("hex");
const ok = sig.length === calc.length
&& crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(calc));
if (!ok) return res.status(401).send("bad signature");
const ev = JSON.parse(req.body.toString());
if (ev.event === "payment.success") {
// ev.id = gateway order id, ev.order_id = YOUR reference
// The same event can arrive more than once
// -> mark paid ONCE per ev.id
}
res.send("ok");
});
app.listen(3000);
import os, hmac, hashlib, json
from flask import Flask, request, abort
app = Flask(__name__)
API_KEY = os.environ["HEX_API_KEY"]
@app.post("/hexpay-webhook")
def hexpay_webhook():
raw = request.get_data() # RAW body
calc = hmac.new(API_KEY.encode(), raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(calc, request.headers.get("x-signature", "")):
abort(401)
ev = json.loads(raw)
if ev.get("event") == "payment.success":
# ev["id"] = gateway order id, ev["order_id"] = YOUR reference
# The same event can arrive more than once
# -> mark paid ONCE per ev["id"]
pass
return "ok"
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"log"
"net/http"
"os"
)
func webhook(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
mac := hmac.New(sha256.New, []byte(os.Getenv("HEX_API_KEY")))
mac.Write(raw)
if !hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))),
[]byte(r.Header.Get("x-signature"))) {
http.Error(w, "bad signature", 401)
return
}
log.Println("payment ok:", string(raw))
w.WriteHeader(200)
w.Write([]byte("ok"))
}
func main() {
http.HandleFunc("/hexpay-webhook", webhook)
http.ListenAndServe(":3000", nil)
}
using System.Security.Cryptography;
using System.Text;
app.MapPost("/hexpay-webhook", async (HttpRequest req) =>
{
using var reader = new StreamReader(req.Body);
var raw = await reader.ReadToEndAsync();
var sig = req.Headers["x-signature"].ToString();
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(
Environment.GetEnvironmentVariable("HEX_API_KEY")));
var calc = Convert.ToHexString(
hmac.ComputeHash(Encoding.UTF8.GetBytes(raw))).ToLower();
if (calc != sig) return Results.Unauthorized();
// process raw JSON here...
return Results.Text("ok");
});
Test your receiver without paying
Create a signed fake event from your terminal:
BODY='{"event":"payment.success","id":"hex_test1","order_id":"ORD-1","status":"PAID","amount":199,"payable":199.01,"paid_at":1728189400000}'
SIG=$(printf %s "$BODY" | openssl dgst -sha256 -hmac "YOUR_API_KEY" | sed 's/^.* //')
curl -X POST https://yoursite.com/hexpay-webhook \
-H "Content-Type: application/json" \
-H "x-signature: $SIG" \
-d "$BODY"
Errors & limits
Errors return JSON like {"error": "message"} with an HTTP status.
| HTTP | Message / cause | Fix |
|---|---|---|
| 400 | amount must be 1-100000 | Send a number between 1 and 100000. |
| 400 | webhook must point to a public server | Use a public https URL, not localhost / a private IP. For local testing use ngrok or cloudflared. |
| 400 | Gateway not configured | Finish My Gateway (UPI ID and alert setup) first. |
| 401 | Invalid API key | Wrong or regenerated key, or the x-api-key header is missing. |
| 403 | Account / network blocked | Contact support. |
| 404 | Not found (status) | Wrong id, or an order_id looked up without your key. |
| 429 | Too many requests | Slow down and wait for the Retry-After seconds. |
| 503 | Maintenance / storage busy | Retry after a few seconds. |
Plan for retries: if create-order fails with 429 / 503 or a network error, retry with a short delay. Do not retry a 4xx other than 429, fix the request.
Guide: website checkout
- On "Pay" click, your server calls
create-orderand savesidwith your order. - Redirect the customer to
pay_url(or render theqryourself). - Your webhook marks the order paid and delivers the product.
- The customer sees "Payment Successful", then "Redirecting to your-site.com in 5s", then lands on your
redirectpage (never on the HexPay site). Show a "thank you" / current wallet balance there, but never deliver the product based on that page alone (anyone can open the URL). Deliver only from the webhook or a server-side status check.
What your redirect page receives
HexPay appends these to your redirect URL (an existing query string and #fragment are kept):
https://shop.example.com/thanks?order_id=INV-1001&id=hex_a1b2c&status=PAID&amount=100.00&sig=9f2c...
sig = HMAC-SHA256 of id|order_id|amount|PAID with your API key. Check it (or call the status API with id) before showing "payment received":
$id = $_GET['id'] ?? '';
$oid = $_GET['order_id'] ?? '';
$amt = $_GET['amount'] ?? '';
$ok = hash_equals(hash_hmac('sha256', "$id|$oid|$amt|PAID", $apiKey), $_GET['sig'] ?? '');
const crypto = require('crypto');
const { id, order_id, amount, sig } = req.query;
const exp = crypto.createHmac('sha256', API_KEY)
.update(`${id}|${order_id}|${amount}|PAID`).digest('hex');
const ok = sig && sig.length === exp.length &&
crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(exp));
The webhook is sent the moment the payment is detected, before the customer is redirected, so the product / wallet credit is normally already done when they land on your page. Payments made through a payment link never redirect: the customer just stays on the animated "Payment Successful" page.
The code for step 1 is in Create order and for step 3 in Webhooks.
Guide: Telegram bot wallet
Complete flow for a bot where users add money to a wallet and then buy with the balance:
- User sends
/add 100. The bot callscreate-orderwithorder_id = "W<telegram id>-<time>"and savesid -> {user, amount}. - The bot sends a QR photo plus buttons Open payment page (
pay_url) and I have paid. - The user pays
payable. The gateway calls your/hexpay-webhook. - The bot verifies the signature and credits the wallet with
amount(notpayable) once, then messages the user. - Backup: the bot also polls the status every 5 seconds for 11 minutes and when the user taps I have paid.
ngrok http 3000 or cloudflared tunnel.
const { Telegraf, Markup } = require('telegraf');
const express = require('express');
const crypto = require('crypto');
const GW = 'https://hexupi.xyz';
const API_KEY = process.env.HEX_API_KEY;
const PUBLIC_URL = process.env.PUBLIC_URL;
const bot = new Telegraf(process.env.BOT_TOKEN);
const wallet = {}; // DEMO - use a real database
const orders = {}; // gateway id -> { tgId, amount, credited }
async function gw(path, body) {
const r = await fetch(GW + path, {
method: body ? 'POST' : 'GET',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
const d = await r.json();
if (!r.ok || d.error) throw new Error(d.error || 'Gateway error ' + r.status);
return d;
}
function creditOnce(orderId) {
const o = orders[orderId];
if (!o || o.credited) return false;
o.credited = true;
wallet[o.tgId] = (wallet[o.tgId] || 0) + o.amount;
bot.telegram
.sendMessage(o.tgId, `Added Rs.${o.amount}.\nBalance: Rs.${wallet[o.tgId]}`)
.catch(() => {});
return true;
}
bot.command('balance', ctx =>
ctx.reply(`Wallet: Rs.${wallet[ctx.from.id] || 0}`)
);
// /add 100
bot.command('add', async ctx => {
const amount = Number((ctx.message.text.split(/\s+/)[1] || '').trim());
if (!(amount >= 1 && amount <= 100000)) {
return ctx.reply('Usage: /add 100');
}
try {
const o = await gw('/api/v1/create-order', {
amount,
order_id: `W${ctx.from.id}-${Date.now()}`,
webhook: PUBLIC_URL + '/hexpay-webhook',
});
orders[o.id] = { tgId: ctx.from.id, amount, credited: false };
// o.qr is SVG and Telegram cannot show it. o.qr_url is a ready PNG: download it, then send it
const png = Buffer.from(await (await fetch(o.qr_url)).arrayBuffer());
await ctx.replyWithPhoto({ source: png }, {
caption:
`Pay exactly Rs.${o.payable} (valid 10 min)\n` +
`Scan this QR with any UPI app.`,
...Markup.inlineKeyboard([
[Markup.button.url('Open payment page', o.pay_url)],
[Markup.button.callback('I have paid', 'chk:' + o.id)],
]),
});
// backup poll every 5s for 11 min
let n = 0;
const t = setInterval(async () => {
if (orders[o.id].credited || ++n > 132) return clearInterval(t);
try {
const s = await gw('/api/v1/status/' + o.id);
if (s.paid) { creditOnce(o.id); clearInterval(t); }
else if (s.status === 'EXPIRED') clearInterval(t);
} catch (e) {}
}, 5000);
} catch (e) {
ctx.reply('Error: ' + e.message);
}
});
bot.action(/^chk:(.+)$/, async ctx => {
try {
const s = await gw('/api/v1/status/' + ctx.match[1]);
if (s.paid) {
creditOnce(ctx.match[1]);
return ctx.answerCbQuery('Paid');
}
ctx.answerCbQuery('Status: ' + s.status);
} catch (e) {
ctx.answerCbQuery('Try again');
}
});
// Webhook
const app = express();
app.post('/hexpay-webhook', express.raw({ type: '*/*' }), (req, res) => {
const sig = String(req.headers['x-signature'] || '');
const calc = crypto.createHmac('sha256', API_KEY).update(req.body).digest('hex');
const ok = sig.length === calc.length
&& crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(calc));
if (!ok) return res.status(401).send('bad signature');
const ev = JSON.parse(req.body.toString());
if (ev.event === 'payment.success') creditOnce(ev.id);
res.send('ok');
});
app.listen(process.env.PORT || 3000);
bot.launch();
import os, io, time, hmac, hashlib, json, threading
import requests, telebot
from telebot import types
from flask import Flask, request, abort
GW = "https://hexupi.xyz"
API_KEY = os.environ["HEX_API_KEY"]
PUBLIC_URL = os.environ["PUBLIC_URL"]
bot = telebot.TeleBot(os.environ["BOT_TOKEN"])
app = Flask(__name__)
wallet, orders, lock = {}, {}, threading.Lock()
def gw(path, body=None):
r = requests.request("POST" if body else "GET", GW + path, json=body,
headers={"x-api-key": API_KEY}, timeout=20)
d = r.json()
if not r.ok or d.get("error"):
raise Exception(d.get("error") or f"Gateway error {r.status_code}")
return d
def credit_once(order_id):
with lock:
o = orders.get(order_id)
if not o or o["credited"]:
return
o["credited"] = True
wallet[o["tg"]] = wallet.get(o["tg"], 0) + o["amount"]
bal = wallet[o["tg"]]
bot.send_message(o["tg"], f"Added Rs.{o['amount']}.\nBalance: Rs.{bal}")
@bot.message_handler(commands=["balance"])
def balance(m):
bot.reply_to(m, f"Wallet: Rs.{wallet.get(m.from_user.id, 0)}")
@bot.message_handler(commands=["add"])
def add(m):
try:
amount = float(m.text.split()[1])
assert 1 <= amount <= 100000
except Exception:
return bot.reply_to(m, "Usage: /add 100")
try:
o = gw("/api/v1/create-order", {
"amount": amount,
"order_id": f"W{m.from_user.id}-{int(time.time())}",
"webhook": PUBLIC_URL + "/hexpay-webhook",
})
orders[o["id"]] = {"tg": m.from_user.id, "amount": amount, "credited": False}
buf = io.BytesIO(requests.get(o["qr_url"], timeout=15).content) # ready PNG from the gateway
kb = types.InlineKeyboardMarkup()
kb.add(types.InlineKeyboardButton("Open payment page", url=o["pay_url"]))
kb.add(types.InlineKeyboardButton("I have paid", callback_data="chk:" + o["id"]))
bot.send_photo(m.chat.id, buf, reply_markup=kb,
caption=f"Pay exactly Rs.{o['payable']} (valid 10 min)")
threading.Thread(target=poll, args=(o["id"],), daemon=True).start()
except Exception as e:
bot.reply_to(m, "Error: " + str(e))
def poll(oid):
for _ in range(132):
time.sleep(5)
if orders[oid]["credited"]:
return
try:
s = gw("/api/v1/status/" + oid)
if s["paid"]:
return credit_once(oid)
if s["status"] == "EXPIRED":
return
except Exception:
pass
@bot.callback_query_handler(func=lambda c: c.data.startswith("chk:"))
def check(c):
oid = c.data[4:]
try:
s = gw("/api/v1/status/" + oid)
if s["paid"]:
credit_once(oid)
bot.answer_callback_query(c.id, "Paid" if s["paid"] else "Status: " + s["status"])
except Exception:
bot.answer_callback_query(c.id, "Try again")
@app.post("/hexpay-webhook")
def hook():
raw = request.get_data()
calc = hmac.new(API_KEY.encode(), raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(calc, request.headers.get("x-signature", "")):
abort(401)
ev = json.loads(raw)
if ev.get("event") == "payment.success":
credit_once(ev["id"])
return "ok"
if __name__ == "__main__":
threading.Thread(target=bot.infinity_polling, daemon=True).start()
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 3000)))
<?php
const HEX_GW = 'https://hexupi.xyz';
const HEX_KEY = 'hex_live_xxxxxxxx';
function hex_call($path, $body = null) {
$ch = curl_init(HEX_GW . $path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'x-api-key: ' . HEX_KEY,
'Content-Type: application/json',
],
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
$d = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$d || !empty($d['error'])) {
throw new Exception($d['error'] ?? 'Gateway error');
}
return $d;
}
function hex_create($tgId, $amount, $webhookUrl) {
return hex_call('/api/v1/create-order', [
'amount' => $amount,
'order_id' => "W{$tgId}-" . time(),
'webhook' => $webhookUrl,
]);
}
// The create-order reply already has a ready PNG link: $order['qr_url']. Pass it straight to sendPhoto.
function hex_qr_png_url($order) {
return $order['qr_url'];
}
function hex_status($gatewayOrderId) {
return hex_call('/api/v1/status/' . rawurlencode($gatewayOrderId));
}
function hex_handle_webhook(callable $creditOnce) {
$raw = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!hash_equals(hash_hmac('sha256', $raw, HEX_KEY), $sig)) {
http_response_code(401);
exit('bad signature');
}
$ev = json_decode($raw, true);
if (($ev['event'] ?? '') === 'payment.success') {
$creditOnce($ev['id'], (float)$ev['amount']);
}
echo 'ok';
}
Buying with the wallet
Deduct and check in one atomic step so two quick taps can never spend the same balance twice.
function buy(tgId, price) {
if ((wallet[tgId] || 0) < price) return false;
wallet[tgId] -= price;
return true;
}
def buy(tg_id, price):
with lock:
if wallet.get(tg_id, 0) < price:
return False
wallet[tg_id] -= price
return True
<?php
$st = $pdo->prepare(
"UPDATE users SET bal = bal - ? WHERE tg_id = ? AND bal >= ?"
);
$st->execute([$price, $tgId, $price]);
if ($st->rowCount() === 1) {
// deliver product
}
id as a unique column and add the wallet credit in the same transaction that marks the order credited.
Guide: Discord bot
Discord bots work exactly like Telegram bots. Use slash commands. Below is a minimal discord.js v14 example.
// npm i discord.js express (Node 18+)
const { Client, GatewayIntentBits, SlashCommandBuilder,
REST, Routes, AttachmentBuilder } = require('discord.js');
const express = require('express');
const crypto = require('crypto');
const GW = 'https://hexupi.xyz';
const API_KEY = process.env.HEX_API_KEY;
const PUBLIC_URL = process.env.PUBLIC_URL;
const wallet = {}; // demo
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
async function gw(path, body) {
const r = await fetch(GW + path, {
method: body ? 'POST' : 'GET',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : undefined,
});
const d = await r.json();
if (!r.ok || d.error) throw new Error(d.error || 'Gateway error');
return d;
}
client.once('ready', async () => {
const cmds = [
new SlashCommandBuilder()
.setName('balance')
.setDescription('Show wallet balance'),
new SlashCommandBuilder()
.setName('add')
.setDescription('Add money to wallet')
.addIntegerOption(o =>
o.setName('amount').setDescription('INR').setRequired(true)),
].map(c => c.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
await rest.put(Routes.applicationCommands(client.user.id), { body: cmds });
console.log('Ready');
});
client.on('interactionCreate', async it => {
if (!it.isChatInputCommand()) return;
const uid = it.user.id;
if (it.commandName === 'balance')
return it.reply(`Wallet: Rs.${wallet[uid] || 0}`);
if (it.commandName === 'add') {
const amount = it.options.getInteger('amount');
if (amount < 1 || amount > 100000) return it.reply('Invalid amount');
await it.deferReply();
try {
const o = await gw('/api/v1/create-order', {
amount,
order_id: `D${uid}-${Date.now()}`,
webhook: PUBLIC_URL + '/hexpay-webhook',
});
const png = Buffer.from(await (await fetch(o.qr_url)).arrayBuffer()); // ready PNG from the gateway
const file = new AttachmentBuilder(png, { name: 'qr.png' });
await it.editReply({
content: `Pay Rs.${o.payable} within 10 min\n${o.pay_url}`,
files: [file],
});
} catch (e) {
it.editReply('Error: ' + e.message);
}
}
});
// Webhook
const app = express();
app.post('/hexpay-webhook', express.raw({ type: '*/*' }), (req, res) => {
const sig = String(req.headers['x-signature'] || '');
const calc = crypto.createHmac('sha256', API_KEY).update(req.body).digest('hex');
if (sig.length !== calc.length ||
!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(calc))) {
return res.status(401).send('bad');
}
const ev = JSON.parse(req.body.toString());
if (ev.event === 'payment.success') {
const uid = ev.order_id.split('-')[0].slice(1);
wallet[uid] = (wallet[uid] || 0) + ev.amount;
}
res.send('ok');
});
app.listen(3000);
client.login(process.env.DISCORD_TOKEN);
Guide: WhatsApp bot (Twilio)
WhatsApp bots receive a message, call the API, and reply with the QR (as an image URL) plus the payment link.
// npm i express twilio axios
const express = require('express');
const twilio = require('twilio');
const axios = require('axios');
const GW = 'https://hexupi.xyz';
const API_KEY = process.env.HEX_API_KEY;
const PUBLIC_URL = process.env.PUBLIC_URL;
const { MessagingResponse } = twilio.twiml;
const app = express();
app.use(express.urlencoded({ extended: false }));
app.post('/whatsapp', async (req, res) => {
const text = (req.body.Body || '').trim();
const from = req.body.From;
const tw = new MessagingResponse();
// user sends: "add 100"
const m = text.match(/add\s+(\d+(\.\d+)?)/i);
if (m) {
const amount = parseFloat(m[1]);
try {
const r = await axios.post(
GW + '/api/v1/create-order',
{
amount,
order_id: `WA${from}-${Date.now()}`,
webhook: PUBLIC_URL + '/hexpay-webhook',
},
{ headers: { 'x-api-key': API_KEY } }
);
const o = r.data;
// WhatsApp shows images by URL
const qrUrl = o.qr_url; // ready PNG link from the gateway
const msg = tw.message();
msg.body(`Pay Rs.${o.payable} within 10 min:\n${o.pay_url}`);
msg.media(qrUrl);
} catch (e) {
tw.message('Error: ' + (e.response?.data?.error || e.message));
}
} else {
tw.message('Send: add 100');
}
res.type('text/xml').send(tw.toString());
});
app.listen(3000);
Guide: mobile app
pay_url in a webview or browser.
// Your backend: /api/create-order (calls HexPay with the secret key)
// Android just gets back the pay_url and opens it.
val url = URL("https://yoursite.com/api/create-order")
val conn = url.openConnection() as HttpURLConnection
conn.requestMethod = "POST"
conn.doOutput = true
conn.setRequestProperty("Content-Type", "application/json")
conn.outputStream.write("""{"amount":199}""".toByteArray())
val payUrl = JSONObject(
conn.inputStream.bufferedReader().readText()
).getString("pay_url")
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(payUrl)))
var req = URLRequest(
url: URL(string: "https://yoursite.com/api/create-order")!
)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = #"{"amount":199}"#.data(using: .utf8)
URLSession.shared.dataTask(with: req) { data, _, _ in
guard let data = data,
let json = try? JSONSerialization
.jsonObject(with: data) as? [String: Any],
let payUrl = json["pay_url"] as? String,
let url = URL(string: payUrl) else { return }
DispatchQueue.main.async { UIApplication.shared.open(url) }
}.resume()
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'dart:convert';
Future<void> pay() async {
final r = await http.post(
Uri.parse('https://yoursite.com/api/create-order'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'amount': 199}),
);
final o = jsonDecode(r.body);
await launchUrl(Uri.parse(o['pay_url']));
}
import { Linking } from 'react-native';
const res = await fetch('https://yoursite.com/api/create-order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: 199 }),
});
const o = await res.json();
Linking.openURL(o.pay_url);
Your backend /api/create-order does the real gateway call:
app.post('/api/create-order', async (req, res) => {
const r = await fetch(
'https://hexupi.xyz/api/v1/create-order',
{
method: 'POST',
headers: {
'x-api-key': process.env.HEX_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: req.body.amount,
order_id: 'APP-' + Date.now(),
webhook: 'https://yoursite.com/hexpay-webhook',
}),
}
);
const o = await r.json();
res.json({ pay_url: o.pay_url, id: o.id });
});
Guide: WordPress / WooCommerce
Two ways: a tiny custom plugin, or paste the PHP snippet into a page template.
Simple: custom plugin
<?php
/*
Plugin Name: HexPay Gateway
Description: Adds a "Pay with UPI" button via shortcode
[hexpay amount="199"]
*/
add_shortcode('hexpay', function ($atts) {
$a = shortcode_atts(
['amount' => 1, 'label' => 'Pay with UPI'],
$atts
);
$nonce = wp_create_nonce('hexpay');
return "<form method='post'>
<input type='hidden' name='hexpay_nonce' value='$nonce'>
<input type='hidden' name='hexpay_amount' value='{$a['amount']}'>
<button type='submit'>{$a['label']}</button>
</form>";
});
add_action('init', function () {
if (empty($_POST['hexpay_nonce'])
|| !wp_verify_nonce($_POST['hexpay_nonce'], 'hexpay')) return;
$amount = (float)$_POST['hexpay_amount'];
$r = wp_remote_post(
'https://hexupi.xyz/api/v1/create-order',
[
'headers' => [
'x-api-key' => get_option('hexpay_key'),
'Content-Type' => 'application/json',
],
'body' => wp_json_encode([
'amount' => $amount,
'order_id' => 'WP-' . time(),
'webhook' => home_url('/?hexpay_webhook=1'),
'redirect' => home_url('/thank-you'),
]),
]
);
$o = json_decode(wp_remote_retrieve_body($r), true);
if (!empty($o['pay_url'])) {
wp_redirect($o['pay_url']);
exit;
}
});
// Webhook
add_action('init', function () {
if (empty($_GET['hexpay_webhook'])) return;
$raw = file_get_contents('php://input');
$key = get_option('hexpay_key');
$sig = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!hash_equals(hash_hmac('sha256', $raw, $key), $sig)) {
status_header(401);
exit('bad');
}
$ev = json_decode($raw, true);
if (($ev['event'] ?? '') === 'payment.success') {
// mark order paid, deliver product
}
status_header(200);
echo 'ok';
exit;
});
WooCommerce: hook into the built-in checkout
<?php
add_action('woocommerce_thankyou', function ($order_id) {
$order = wc_get_order($order_id);
if ($order->get_payment_method() !== 'hexpay') return;
$r = wp_remote_post(
'https://hexupi.xyz/api/v1/create-order',
[
'headers' => [
'x-api-key' => get_option('hexpay_key'),
'Content-Type' => 'application/json',
],
'body' => wp_json_encode([
'amount' => (float)$order->get_total(),
'order_id' => 'WC-' . $order_id,
'webhook' => home_url('/?hexpay_webhook=1'),
'redirect' => $order->get_checkout_order_received_url(),
]),
]
);
$o = json_decode(wp_remote_retrieve_body($r), true);
if (!empty($o['pay_url'])) wp_redirect($o['pay_url']);
});
Guide: Shopify / custom cart
Shopify does not allow arbitrary redirects to third-party gateways on checkout. Usual approach: build a Buy Button or Custom App that calls your server, or use the Draft Order flow. Simplest: on your own landing page before Shopify checkout, call the gateway, collect the payment, then create the Shopify order via Admin API.
// 1. Customer clicks "Pay" on your page
app.post('/buy', async (req, res) => {
const r = await fetch(
'https://hexupi.xyz/api/v1/create-order',
{
method: 'POST',
headers: {
'x-api-key': process.env.HEX_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
amount: req.body.total,
order_id: 'SHOP-' + Date.now(),
webhook: 'https://yoursite.com/hexpay-webhook',
}),
}
);
const o = await r.json();
res.json({ pay_url: o.pay_url });
});
// 2. In /hexpay-webhook, after payment.success:
// create a Shopify order via Admin API and fulfil it.
async function createShopifyOrder(ev) {
await fetch(
`https://${process.env.SHOP}/admin/api/2024-10/orders.json`,
{
method: 'POST',
headers: {
'X-Shopify-Access-Token': process.env.SHOPIFY_TOKEN,
'Content-Type': 'application/json',
},
body: JSON.stringify({
order: {
line_items: [],
financial_status: 'paid',
note: ev.order_id,
},
}),
}
);
}
QR codes
The easiest option is to send the customer the pay_url: that page already shows a QR code, UPI app buttons and live status. If you want to show the QR yourself:
- Website / app screen: the
qrfield is a PNG data-URI. Put it straight into an<img src>. - Telegram, WhatsApp, Discord uploads: they need a PNG/JPG, not SVG. Use the
qr_urlfield: it is a ready PNG link (download it, or give the URL tosendPhoto). No QR library is needed.
<!-- the "qr" field is an SVG data-URI, it works directly in an <img> --> <img src="DATA_URI_FROM_qr_FIELD" width="260" alt="Scan to pay">
// order.qr_url is a ready PNG, no QR library needed (Node 18+) const png = Buffer.from(await (await fetch(order.qr_url)).arrayBuffer()); // send png to Telegram / Discord / WhatsApp
import io, requests # order["qr_url"] is a ready PNG buf = io.BytesIO(requests.get(order["qr_url"], timeout=15).content)
<?php
// composer require endroid/qr-code
use Endroid\QrCode\Builder\Builder;
$png = Builder::create()
->data($order["upi"])
->size(512)
->margin(10)
->build()
->getString();
payable in the message too. If a customer types the amount by hand, it must match exactly.
Testing & go-live checklist
- In My Gateway press Test connection (it must say Connected) and then Create test order (a real Rs.1 order). Pay it from a different UPI account and watch it turn PAID.
- Run the fake webhook command against your receiver: wrong signature must give 401, correct one 200.
- Create an order with your code, pay it, and check that the webhook fired once and your product / wallet credit happened once.
- Open Webhook logs to see every delivery attempt and its HTTP result.
Before real customers
- API key only on the server, loaded from an environment variable.
- Webhook signature verified on the raw body, product delivered only from the webhook / status API.
- Idempotent: the same
idnever credits or delivers twice. - Unique
order_idfor every order. - Real database instead of in-memory data; logs for failed gateway calls.
- Payment alert mails stay in your Inbox (not Spam) and the mail connection stays enabled.
Troubleshooting
| Problem | Check |
|---|---|
| Customer paid but order stays PENDING | Did the customer pay the exact payable? Is the alert mail in your Inbox (not Spam)? Is the mail connection still valid? Press Test connection in My Gateway. |
| Webhook never arrives | URL must be public https and answer 2xx. Open Webhook logs. |
| Signature does not match | Use the raw body (express.raw, request.get_data(), php://input). Use the same API key that created the order. |
| Wallet credited twice | Make the credit idempotent by gateway id (unique column / "already credited" flag). |
Gateway not configured | Finish the UPI ID and alert setup in My Gateway. |
| QR does not show in Telegram | Telegram does not accept SVG. Build a PNG from the upi link, see QR codes. |
| Order expired while paying | Orders live 10 minutes. Create a new order; late payments within about 20 minutes are still matched. |
Still stuck? Contact support on Telegram @FrenzyHex with your order id.