Documentation menu

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_url

Four steps:

  1. Create the invoice from your server, with the amount taken from your own order record.
  2. Redirect the shopper to checkout_url.
  3. Verify the webhook signature on the raw request body.
  4. Fulfil the order on invoice.paid only, 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=eea70955f9375b77428ff23dadb317e98613176cfaf656aa182d2064230831fc

v1 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 200

Compare 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 "", 200

For 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.

Details

order_id and retries

order_id makes creation idempotent:

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:

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:

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:

The SDK's coversOrderTotal(invoice, order.total) already compares amount_paid ?? amount with your total. Details and edge cases: Network fees.

Go-live checklist

Edit this page on GitHub