Node SDK
The repo ships a small client for Node.js in sdk/. It is one TypeScript file with no dependencies and runs on Node 18 or later. It wraps the invoice endpoints and the webhook signature check.
It is not published to npm yet. Use it in one of two ways:
- Vendor it. Copy
sdk/src/index.tsinto your project (for examplesrc/lib/qirsh.ts). It is about 200 lines. - Build it from a checkout of the repo and install it by path:
npm run build --prefix sdk # writes sdk/dist/index.js and index.d.ts
npm install /path/to/qirsh/sdk # the package name is qirsh-sdkThe examples below import from qirsh-sdk. Adjust the path if you vendored the file.
Client
import { Qirsh } from "qirsh-sdk";
const tg = new Qirsh({
baseUrl: process.env.QIRSH_URL!, // e.g. "https://pay.example.com"
apiKey: process.env.QIRSH_API_KEY!, // the project's API key; server-side only
timeoutMs: 15_000, // optional, default 15 s
// fetch: customFetch, // optional, defaults to the global fetch
});The constructor throws if baseUrl or apiKey is empty.
Methods
| Method | Calls | Returns |
|---|---|---|
createInvoice(params) |
POST /api/v1/invoices |
Promise<Invoice> |
getInvoice(idOrOrderId) |
GET /api/v1/invoices/:id |
Promise<Invoice> |
listInvoices({ status?, limit? }) |
GET /api/v1/invoices |
Promise<{ data: Invoice[] }> |
createInvoice takes the same fields as the API: amount (a decimal string is safest), order_id, description, metadata, success_url, cancel_url, ttl_minutes and locale ("en" or "ar"). See Create an invoice.
For other endpoints (transfers, sweeps, exports) call the API with fetch directly.
Errors
Any non-2xx response throws a QirshError with:
message: the API's error message, orHTTP <status>status: the HTTP statuscode: the API's error code, for exampleorder_conflict,invalid_amountorunauthorized(http_errorwhen the body had none)
import { QirshError } from "qirsh-sdk";
try {
await tg.createInvoice({ amount: order.total, order_id: order.id });
} catch (err) {
if (err instanceof QirshError && err.code === "order_conflict") {
// the order changed price while its invoice is still open
}
throw err;
}Timeouts reject with the AbortSignal timeout error, not a QirshError.
Webhook helpers
| Export | What it does |
|---|---|
constructWebhookEvent(rawBody, header, secret, toleranceSeconds = 300) |
Verifies the signature and returns the parsed WebhookEvent. Throws QirshError with code invalid_signature (status 400) on a bad or stale signature. rawBody is a string or Buffer; header may be a string, an array (the first value is used) or undefined |
verifyWebhookSignature(rawBody, header, secret, toleranceSeconds = 300) |
The same check, returning true or false |
coversOrderTotal(invoice, orderTotal) |
true when invoice.amount_paid ?? invoice.amount is at least orderTotal (a decimal string such as "49.90"). Compares integer units, never floats. Pass your own order total, never amount_due: with a customer-paid network fee, amount_due includes the fee |
SIGNATURE_HEADER |
"qirsh-signature", the lower-case header name as Node exposes it |
Pass the raw body exactly as received. Re-serialized JSON will not verify.
Types
The file exports TypeScript types for everything it returns: Invoice, InvoiceStatus, CreateInvoiceParams, WebhookEvent, WebhookEventType, Locale and QirshOptions. Invoice includes the forwarder fields (deposit_mode, amount_received, sweep, forwarder) and the network fee fields:
| Field | Type |
|---|---|
network_fee |
{ amount: string; payer: "merchant" | "customer"; collector: string } | null |
amount_net |
string: what the project wallet receives, amount_paid (or amount_due) minus the fee |
sweep.amount_swept, sweep.fee_paid |
string: what reached the wallet, and what reached the operator's fee collector |
forwarder.version |
number: 2 for current deposit addresses, 1 for addresses from before sweep fees |
forwarder.collector, forwarder.fee_token |
string | null: the fee terms bound into the address |
forwarder.fee_units |
string: the bound fee in base units, "0" without a fee |
Fulfil on invoice.paid only, with coversOrderTotal(invoice, order.total). Use amount_net for your books. See Network fees.
Express example
import express from "express";
import { Qirsh, constructWebhookEvent, coversOrderTotal, SIGNATURE_HEADER } from "qirsh-sdk";
const app = express();
const tg = new Qirsh({ baseUrl: process.env.QIRSH_URL!, apiKey: process.env.QIRSH_API_KEY! });
// Raw body for the webhook, registered before express.json().
app.post("/webhooks/qirsh", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = constructWebhookEvent(req.body, req.headers[SIGNATURE_HEADER], process.env.QIRSH_WEBHOOK_SECRET!);
} catch {
return res.status(400).send("invalid signature");
}
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 status = coversOrderTotal(inv, order.total) ? "paid" : "needs_review";
await db.orders.updateWhere({ id: order.id, status: { not: "paid" } }, { status, txId: inv.tx_id });
}
}
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);
const invoice = await tg.createInvoice({
amount: order.total,
order_id: order.id,
success_url: `https://shop.example/orders/${order.id}`,
cancel_url: "https://shop.example/cart",
});
await db.orders.update(order.id, { qirshInvoiceId: invoice.id });
res.redirect(303, invoice.checkout_url);
} catch (err) {
next(err);
}
});Next.js route handlers (App Router)
// app/api/checkout/route.ts
import { NextResponse } from "next/server";
import { Qirsh } from "qirsh-sdk";
const tg = new Qirsh({ baseUrl: process.env.QIRSH_URL!, apiKey: process.env.QIRSH_API_KEY! });
export async function POST(req: Request) {
const { orderId } = await req.json();
const order = await getOrderForCurrentUser(orderId); // your code; the price comes from here
const invoice = await tg.createInvoice({
amount: order.total,
order_id: order.id,
success_url: `https://shop.example/orders/${order.id}`,
cancel_url: "https://shop.example/cart",
});
return NextResponse.json({ url: invoice.checkout_url });
}// app/api/webhooks/qirsh/route.ts
import { constructWebhookEvent, coversOrderTotal } from "qirsh-sdk";
export const runtime = "nodejs"; // node:crypto is needed
export async function POST(req: Request) {
const raw = await req.text(); // raw body; don't call req.json() first
let event;
try {
event = constructWebhookEvent(raw, req.headers.get("qirsh-signature"), process.env.QIRSH_WEBHOOK_SECRET!);
} catch {
return new Response("invalid signature", { status: 400 });
}
if (event.type === "invoice.paid") {
const inv = event.data.invoice;
const order = await findOrder(inv.order_id);
if (order && order.status !== "paid") {
await markOrder(order.id, coversOrderTotal(inv, order.total) ? "paid" : "needs_review", inv.tx_id);
}
}
return new Response("ok");
}The browser calls /api/checkout and then sets window.location to the returned URL. The API key never leaves the server.
A complete store
examples/node-store/server.mjs is a one-product shop in about 100 lines with no dependencies besides the built SDK. It creates invoices, verifies webhooks and shows the order page.
npm run build --prefix sdk
cd examples/node-store
QIRSH_URL=http://localhost:8080 QIRSH_API_KEY=... QIRSH_WEBHOOK_SECRET=... node server.mjs