Integration guide
This page is for developers who connect a store or app to a Qirsh gateway. The store never talks to the blockchain. It makes one API call per order and handles one signed webhook.
You need three values from the gateway operator (or from the project's Settings page in the dashboard):
| Value | Where it comes from | Where it lives |
|---|---|---|
QIRSH_URL |
The gateway's public URL, for example https://pay.example.com |
Store config |
QIRSH_API_KEY |
Settings, API keys (tg_live_... or tg_test_...), or API_SECRET_KEY in single-store mode |
Server-side secret |
QIRSH_WEBHOOK_SECRET |
Settings, Webhook, Signing secret (whsec_...), or WEBHOOK_SECRET in single-store mode |
Server-side secret |
Each store should be its own project, with its own key and secret. Check that the gateway is up with curl https://pay.example.com/health.
The fastest path
Store backend Qirsh TRON
POST /api/v1/invoices ───────────▶ invoice + checkout_url
redirect shopper (303) ───────────▶ /pay/inv_... (QR, TronLink) ─▶ shopper pays
watches the chain ◀── transfer
POST your webhook URL ◀─────────── invoice.paid (signed)
fulfil the order sends shopper to success_urlFour steps:
- Create the invoice from your server, with the amount taken from your own order record.
- Redirect the shopper to
checkout_url. - Verify the webhook signature on the raw request body.
- Fulfil the order on
invoice.paidonly, once, after checking that the amount received covers the order.
1. Create the invoice
curl -X POST https://pay.example.com/api/v1/invoices \
-H "Authorization: Bearer $QIRSH_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"amount": "49.90",
"order_id": "ORDER-1001",
"description": "2x Hoodie",
"success_url": "https://shop.example/orders/ORDER-1001",
"cancel_url": "https://shop.example/cart",
"metadata": { "customer_id": 42 }
}'The response (201 Created, or 200 when the same order_id already has an open invoice):
{
"id": "inv_Luonp2fQ0b8rR1cS9yZ5w08",
"object": "invoice",
"status": "pending",
"order_id": "ORDER-1001",
"amount": "49.9",
"amount_due": "49.907423",
"currency": "USDT",
"network": "tron",
"pay_address": "TJ4kA5wRUM9f3xLtBTrPdT5ri7Q2kbUhAF",
"checkout_url": "https://pay.example.com/pay/inv_Luonp2fQ0b8rR1cS9yZ5w08",
"expires_at": "2026-12-04T07:30:52.554Z",
"deposit_mode": "amount"
}The full object has more fields. See the invoice object.
Store id on your order. You can also look invoices up later by your order_id.
2. Redirect the shopper
Send a 303 redirect to checkout_url. The hosted page shows the amount, a QR code, the address, a countdown, a Pay with TronLink button and live status. When the invoice is paid it sends the shopper to your success_url.
Don't build your own payment page from amount_due and pay_address unless you have to. The checkout handles both deposit modes, partial payments and expiry for you.
3. Verify the webhook
Qirsh POSTs JSON to the project's webhook URL with a Qirsh-Signature header:
Qirsh-Signature: t=1767225600,v1=eea70955f9375b77428ff23dadb317e98613176cfaf656aa182d2064230831fcv1 is the hex HMAC-SHA256 of "<t>.<raw body>" with the webhook secret. Compute it over the exact bytes you received, compare in constant time, and reject timestamps more than 300 seconds from now. Details and code for more languages are in Webhooks.
4. Fulfil on invoice.paid
if event.type == "invoice.paid":
order = find order by invoice.order_id
received = invoice.amount_paid ?? invoice.amount
if cents(received) >= cents(order.total): mark paid (only if not already paid), fulfil
else: hold for review
respond 200Compare amounts as integers (cents or base units), never as strings or floats. "49.9" and "49.90" are the same price. Compare with your own order total, not with amount_due: in forwarder mode the customer may pay a network fee on top, which is part of amount_due but not of your price. Webhooks can arrive more than once, so the update must be idempotent, for example UPDATE orders SET status='paid' WHERE id=? AND status <> 'paid'.
Complete examples
Node.js with Express
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
const app = express();
const { QIRSH_URL, QIRSH_API_KEY, QIRSH_WEBHOOK_SECRET, STORE_URL } = process.env;
// The webhook route needs the raw body, so register it before express.json().
app.post("/webhooks/qirsh", express.raw({ type: "application/json" }), async (req, res) => {
const raw = req.body.toString("utf8");
if (!verify(raw, req.get("qirsh-signature"), QIRSH_WEBHOOK_SECRET)) {
return res.status(400).send("invalid signature");
}
const event = JSON.parse(raw);
if (event.type === "invoice.paid") {
const inv = event.data.invoice;
const order = await db.orders.findById(inv.order_id);
if (order && order.status !== "paid") {
const covered = cents(inv.amount_paid ?? inv.amount) >= cents(order.total);
// Conditional update: a second delivery changes nothing.
await db.orders.updateWhere(
{ id: order.id, status: { not: "paid" } },
{ status: covered ? "paid" : "needs_review", txId: inv.tx_id },
);
}
} else if (event.type === "invoice.expired") {
await db.orders.updateWhere({ id: event.data.invoice.order_id, status: "awaiting_payment" }, { status: "expired" });
}
res.sendStatus(200);
});
app.use(express.json());
app.post("/checkout/:orderId", async (req, res, next) => {
try {
const order = await db.orders.findById(req.params.orderId); // check it belongs to the signed-in user
const r = await fetch(`${QIRSH_URL}/api/v1/invoices`, {
method: "POST",
headers: { authorization: `Bearer ${QIRSH_API_KEY}`, "content-type": "application/json" },
body: JSON.stringify({
amount: order.total, // a decimal string from your database, e.g. "49.90"
order_id: order.id,
success_url: `${STORE_URL}/orders/${order.id}`,
cancel_url: `${STORE_URL}/cart`,
}),
});
const invoice = await r.json();
if (!r.ok) throw new Error(invoice.error?.message ?? `Qirsh HTTP ${r.status}`);
await db.orders.update(order.id, { qirshInvoiceId: invoice.id, status: "awaiting_payment" });
res.redirect(303, invoice.checkout_url);
} catch (err) {
next(err);
}
});
function verify(raw, header, secret, tolerance = 300) {
if (!header) return false;
const parts = Object.fromEntries(header.split(",").map((kv) => kv.trim().split("=", 2)));
const t = Number(parts.t);
if (!Number.isInteger(t) || !parts.v1 || Math.abs(Date.now() / 1000 - t) > tolerance) return false;
const expected = createHmac("sha256", secret).update(`${t}.${raw}`).digest();
const given = Buffer.from(parts.v1, "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
}
/** "49.9" -> 4990. Extra decimals (the unique digits) are dropped. */
function cents(amount) {
const [whole, frac = ""] = String(amount).split(".");
return Number(whole) * 100 + Number(frac.padEnd(2, "0").slice(0, 2));
}
app.listen(3000);With the Node SDK the signature check is one call to constructWebhookEvent(), and coversOrderTotal() does the amount check. A runnable store in about 100 lines is in examples/node-store.
PHP
<?php
// checkout.php
function qirsh_create_invoice(array $params): array {
$ch = curl_init(rtrim(getenv('QIRSH_URL'), '/') . '/api/v1/invoices');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('QIRSH_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode($params),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($body, true);
if ($status >= 400) throw new RuntimeException($data['error']['message'] ?? "Qirsh HTTP $status");
return $data;
}
$order = load_order_for_current_user($_POST['order_id']); // your code
$invoice = qirsh_create_invoice([
'amount' => (string)$order['total'], // from the database, never from the form
'order_id' => (string)$order['id'],
'success_url' => "https://shop.example/orders/{$order['id']}",
'cancel_url' => 'https://shop.example/cart',
]);
save_invoice_id($order['id'], $invoice['id']);
header('Location: ' . $invoice['checkout_url'], true, 303);<?php
// webhook.php
function qirsh_verify(string $raw, ?string $header, string $secret, int $tolerance = 300): bool {
if (!$header) return false;
parse_str(str_replace(',', '&', $header), $p);
if (!isset($p['t'], $p['v1']) || !ctype_digit($p['t']) || abs(time() - (int)$p['t']) > $tolerance) return false;
$expected = hash_hmac('sha256', $p['t'] . '.' . $raw, $secret);
return hash_equals($expected, $p['v1']);
}
function qirsh_cents(string $amount): int {
[$whole, $frac] = array_pad(explode('.', $amount, 2), 2, '');
return (int)$whole * 100 + (int)substr(str_pad($frac, 2, '0'), 0, 2);
}
$raw = file_get_contents('php://input');
if (!qirsh_verify($raw, $_SERVER['HTTP_QIRSH_SIGNATURE'] ?? null, getenv('QIRSH_WEBHOOK_SECRET'))) {
http_response_code(400);
exit('invalid signature');
}
$event = json_decode($raw, true);
$inv = $event['data']['invoice'] ?? null;
if ($event['type'] === 'invoice.paid' && $inv['order_id'] !== null) {
$q = $pdo->prepare('SELECT total FROM orders WHERE id = ?');
$q->execute([$inv['order_id']]);
$total = $q->fetchColumn();
if ($total !== false) {
$covered = qirsh_cents($inv['amount_paid'] ?? $inv['amount']) >= qirsh_cents((string)$total);
$u = $pdo->prepare("UPDATE orders SET status = ?, tx_id = ? WHERE id = ? AND status NOT IN ('paid', 'needs_review')");
$u->execute([$covered ? 'paid' : 'needs_review', $inv['tx_id'], $inv['order_id']]);
}
}
http_response_code(200);Python with Flask
import hashlib, hmac, json, os, time
from decimal import Decimal
import requests
from flask import Flask, abort, redirect, request
app = Flask(__name__)
QIRSH_URL = os.environ["QIRSH_URL"].rstrip("/")
API_KEY = os.environ["QIRSH_API_KEY"]
WEBHOOK_SECRET = os.environ["QIRSH_WEBHOOK_SECRET"]
@app.post("/checkout/<order_id>")
def checkout(order_id):
order = load_order_for_current_user(order_id) # your code
r = requests.post(
f"{QIRSH_URL}/api/v1/invoices",
json={
"amount": str(order.total), # Decimal -> str, never float
"order_id": str(order.id),
"success_url": f"https://shop.example/orders/{order.id}",
"cancel_url": "https://shop.example/cart",
},
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=15,
)
invoice = r.json()
if r.status_code >= 400:
raise RuntimeError(invoice.get("error", {}).get("message", f"HTTP {r.status_code}"))
save_invoice_id(order.id, invoice["id"])
return redirect(invoice["checkout_url"], code=303)
def verify(raw: bytes, header: str | None, secret: str, tolerance: int = 300) -> bool:
if not header:
return False
try:
parts = dict(p.strip().split("=", 1) for p in header.split(","))
t = int(parts["t"])
except (KeyError, ValueError):
return False
if abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts.get("v1", ""))
@app.post("/webhooks/qirsh")
def webhook():
raw = request.get_data() # raw bytes, before any JSON parsing
if not verify(raw, request.headers.get("Qirsh-Signature"), WEBHOOK_SECRET):
abort(400)
event = json.loads(raw)
if event["type"] == "invoice.paid":
inv = event["data"]["invoice"]
order = find_order(inv["order_id"])
if order and order.status != "paid":
received = Decimal(inv["amount_paid"] or inv["amount"])
mark_order(order.id, "paid" if received >= order.total else "needs_review", inv["tx_id"]) # conditional update
return "", 200For FastAPI read the body with await request.body(). For Django use request.body and mark the view @csrf_exempt.
Rules you must follow
These are the same for every stack and both deposit modes.
- The amount comes from your server-side order. Never take it from the request body, a hidden form field or a query string.
- Verify the webhook on the raw body. If a framework parses and re-serializes the JSON first, the signature will not match. Reject a missing or bad signature with
400. - Fulfil only on
invoice.paid.invoice.confirmingmeans the transfer is on-chain but not final.invoice.swept(forwarder mode) is for accounting. Neither should ship anything. - Make fulfilment idempotent. The same event can arrive twice, and an
invoice.paidcan follow aninvoice.expiredfor the same invoice. - Check the amount. Compare
amount_paid ?? amountwith your own order total as integers. Not withamount_due, which can include a customer-paid network fee, and not withamount_net, which excludes a merchant-paid one. A manually settled invoice (settled_manually: true) can carry less than the order total. - Keep secrets on the server. The API key and webhook secret never go into browser code, mobile apps, git or logs.
success_urlis not proof of payment. Anyone can open it. Show the order status from your database there. If the webhook has not arrived yet, show "confirming" and, if you like, pollGET /api/v1/invoices/{id}from your server.- Use HTTPS to reach the gateway in production. The API key travels in the
Authorizationheader.
Details
order_id and retries
order_id makes creation idempotent:
- The same
order_idand amount while the invoice is open (pending,confirmingorpaid) returns the existing invoice with200. A double-clicked "Pay" button gets the same checkout. - The same
order_idwith a different amount while the invoice is open returns409 order_conflict. - Once the old invoice has
expired, the sameorder_idcreates a new invoice, at any amount. The old invoice keeps a reference to the order. If the shopper paid the old one in time, itsinvoice.paidwebhook still carries yourorder_id, and paying one closes the other.
GET /api/v1/invoices/{id} accepts either the invoice id or your order_id. With an order_id it returns the current invoice for that order.
Expiry
Invoices expire after the project's invoice lifetime (default INVOICE_TTL_MINUTES, 30 minutes), or after ttl_minutes (5 to 1440) if you pass it. On expiry you get invoice.expired. Release stock or cancel the order then.
A transfer that was sent before the deadline but detected after it still settles the invoice: the status goes from expired to paid and you get invoice.paid. Your handler must accept that order of events.
Language
Pass locale ("en" or "ar") to match the store's language. Arabic renders right to left, with the amount and address kept left to right. The checkout picks the language from ?lang= on the URL first, then the invoice's locale, then the browser's Accept-Language.
Metadata and description
description (up to 500 characters) is shown to the shopper on the checkout. metadata (a JSON object, up to 4 KB serialized) is never shown to the shopper. It comes back in API responses and webhooks, so you can carry your own ids through.
Redirect URLs
success_url and cancel_url must be http or https URLs, up to 2048 characters. The checkout sends the shopper to success_url after payment and shows a "Cancel and return to store" link to cancel_url.
Amounts
Send amount as a decimal string, for example "49.90". It may have at most as many decimals as the token (6 for USDT). Amounts in responses are normalized: "49.90" comes back as "49.9". Always compare as integers.
In unique-amount mode amount_due is amount plus a small offset (at most 0.009999 USDT) that identifies the payment. The shopper pays amount_due. Treat the offset as noise when you compare totals: the cents() helpers above drop it.
Forwarder mode, from the store's side
The gateway operator can switch a project to forwarder mode: each invoice gets its own deposit address and the shopper pays the round amount. Your integration stays the same. The differences:
deposit_modeis"forwarder"andamount_dueequalsamount, unless the customer pays a network fee (below).pay_addressis the invoice's deposit address, not the merchant wallet. Never hard-code the wallet address in your UI or emails.- The invoice has a
forwarderobject (factory,destination,salt,version, and the fee termscollector,fee_token,fee_units). Save it with the order, or at least the invoice id. With it, the funds can be recovered to the wallet even without the gateway. - A partial payment leaves the invoice
pendingand the checkout asks for the rest. Partial-at-expiry, late and duplicate payments are not settled automatically. The merchant settles them in the dashboard with Accept, which sendsinvoice.paidwithsettled_manually: trueand the realamount_paid. Your amount check handles this. - After
invoice.paidthe gateway sweeps the funds to the wallet and sendsinvoice.swept. It changes nothing for fulfilment. - Creation can fail with
400 amount_too_small(below the gateway'sSWEEP_MIN_AMOUNT, default 1 USDT, or too little left after a merchant-paid network fee),503 too_many_open_invoicesor503 forwarder_unavailable. Retry the 503s later and tell the operator if they persist.
Network fees
The operator can charge a fee per forwarder invoice to cover the TRX spent sweeping it. The fee is set per project, fixed into each invoice when it is created, and charged once per invoice. When it applies, the invoice carries:
network_fee:{ "amount": "1.5", "payer": "merchant" | "customer", "collector": "T..." }.nullwhen no fee applies.amount_net: what the project wallet receives,amount_paid(oramount_duebefore payment) minus the fee.sweep.fee_paidafter the sweep: what reached the operator's collector.
payer: "merchant" |
payer: "customer" |
|
|---|---|---|
Order of 49.90, fee 1.5: the shopper pays (amount_due) |
49.9 |
51.4, and the checkout shows the fee as a separate line |
amount_paid when paid in full |
49.9 |
51.4 |
amount_net |
48.4 |
49.9 |
What to do:
- Fulfil on
invoice.paidonly, as before.invoice.sweptis for accounting. - Check
amount_paid ?? amountagainst your own price (49.90 here). Do not check againstamount_due: withpayer: "customer"it includes the fee. Do not check againstamount_net: withpayer: "merchant"it is lower than your price by the fee, and that is not an underpayment. - Book
amount_netas what reached the wallet andnetwork_fee.amountas the operator's fee. - If a fee would surprise you, check
network_feeon the invoice you just created before redirecting the shopper.
The SDK's coversOrderTotal(invoice, order.total) already compares amount_paid ?? amount with your total. Details and edge cases: Network fees.
Go-live checklist
- The API key and webhook secret are server-side only, loaded from env or a secret store.
- The amount comes from the order in your database.
- The webhook handler reads the raw body and verifies
Qirsh-Signaturewith a constant-time compare and the 300 s window. - Fulfilment happens only on
invoice.paid, once, and checksamount_paid ?? amountagainst your own order total as integers (notamount_due). -
invoice.expiredreleases the order, and a laterinvoice.paidfor the same order is still handled. - The
success_urlpage does not mark orders paid. - The webhook route is excluded from CSRF and session middleware, and answers
2xxwithin 10 seconds. - You ran the checklist in Testing on a Nile project.
- Production uses a separate mainnet project, with its own API key and webhook secret, over HTTPS.