// HoltPay client for Node.js 18+. No dependencies: copy this one file into your project. // // import { HoltPay } from "./holtpay.mjs"; // const holtpay = new HoltPay({ apiKey: process.env.HOLTPAY_API_KEY, baseUrl: "https://pay.example.com" }); // const invoice = await holtpay.createInvoice({ amount: "25.00", currency: "USDT", network: "tron", order_id: "1042" }); // // send the customer to invoice.checkout_url // // In your webhook handler, verify the signature on the raw request body before trusting it: // // const event = HoltPay.verifyWebhook(rawBody, req.headers["x-holtpay-signature"], process.env.HOLTPAY_WEBHOOK_SECRET); // if (event.event === "invoice.paid") { /* mark order event.data.order_id as paid */ } import { createHmac, timingSafeEqual } from "node:crypto"; export class HoltPayError extends Error { constructor(status, code, message, details) { super(message); this.name = "HoltPayError"; this.status = status; this.code = code; this.details = details; } } export class HoltPay { /** * @param {{ apiKey: string, baseUrl: string, timeoutMs?: number }} options */ constructor({ apiKey, baseUrl, timeoutMs = 15000 }) { if (!apiKey) throw new Error("HoltPay: apiKey is required"); if (!baseUrl) throw new Error("HoltPay: baseUrl is required, for example https://pay.example.com"); this.apiKey = apiKey; this.baseUrl = baseUrl.replace(/\/+$/, ""); this.timeoutMs = timeoutMs; } async request(method, path, body) { const res = await fetch(this.baseUrl + path, { method, headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json", ...(body ? { "content-type": "application/json" } : {}), }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(this.timeoutMs), }); const json = await res.json().catch(() => ({})); if (!res.ok) { const { code = "http_error", message = `HTTP ${res.status}`, ...details } = json.error ?? {}; throw new HoltPayError(res.status, code, message, details); } return json; } /** The networks and currencies this HoltPay site accepts. */ networks() { return this.request("GET", "/v1/networks").then((r) => r.data); } /** * Create an invoice. * @param {{ amount: string|number, currency: string, network: string, order_id?: string, description?: string, * metadata?: object, redirect_url?: string, expires_in_minutes?: number }} input */ createInvoice(input) { return this.request("POST", "/v1/invoices", input); } getInvoice(id) { return this.request("GET", `/v1/invoices/${encodeURIComponent(id)}`); } /** @param {{ status?: string, order_id?: string, test?: boolean, limit?: number, before?: string }} [filters] */ listInvoices(filters = {}) { const q = new URLSearchParams(); for (const [k, v] of Object.entries(filters)) { if (v === undefined || v === null) continue; q.set(k, k === "test" ? (v ? "1" : "0") : String(v)); } return this.request("GET", `/v1/invoices${q.size ? `?${q}` : ""}`).then((r) => r.data); } /** Test network only: settle an invoice as if the customer had paid. */ simulatePayment(id) { return this.request("POST", `/v1/invoices/${encodeURIComponent(id)}/simulate-payment`); } /** * Check a webhook's X-HoltPay-Signature header and return the parsed event. * Throws when the signature is wrong or older than `toleranceSeconds`. * @param {string|Buffer} rawBody the request body exactly as received (not re-serialised JSON) * @param {string} header the X-HoltPay-Signature header * @param {string} secret your webhook signing secret (whsec_...) */ static verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) { const body = Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : String(rawBody); const parts = Object.fromEntries( String(header ?? "") .split(",") .map((p) => p.trim().split("=")) .filter((kv) => kv.length === 2), ); const t = Number(parts.t); if (!Number.isFinite(t) || !/^[0-9a-f]{64}$/.test(parts.v1 ?? "")) throw new Error("HoltPay webhook: malformed signature header"); if (Math.abs(Date.now() / 1000 - t) > toleranceSeconds) throw new Error("HoltPay webhook: signature is too old"); const expected = createHmac("sha256", secret).update(`${t}.${body}`).digest(); const given = Buffer.from(parts.v1, "hex"); if (given.length !== expected.length || !timingSafeEqual(given, expected)) throw new Error("HoltPay webhook: signature does not match"); return JSON.parse(body); } } export default HoltPay;