// The client every TypeScript example on this site uses: this one file. Copy it next to // your code — there is nothing to install. It uses only what Bun and Node 22.18+ // already have, signs each request (NP1), sends exactly the bytes it signed, and retries // only where a retry cannot do something twice. // // import { nicepay } from "./nicepay.ts"; // const payin = await nicepay("POST", "/v1/payins", { body: { … }, idempotencyKey: orderId }); import { createHash, createHmac, createPrivateKey, randomBytes, sign, type KeyObject } from "node:crypto"; import { readFileSync } from "node:fs"; /** Test and live use the same host; your key decides the mode. Leave NICEPAY_API_BASE unset. */ export const baseUrl = (process.env["NICEPAY_API_BASE"] ?? "https://api.mynicepanel.com").replace(/\/+$/, ""); export interface Credentials { /** `np_test_kid_…` or `np_live_kid_…`. */ readonly keyId: string; /** An HMAC key's secret (`np_…_sk_…`), or … */ readonly secret?: string; /** … an Ed25519 key's private key, as PKCS#8 PEM text. Give one of the two. */ readonly privateKey?: string; } export interface CallOptions { readonly query?: Readonly>; readonly body?: unknown; /** Required where money is created (pay-ins, payouts, settlements): your own order or withdrawal id. */ readonly idempotencyKey?: string; } /** Codes after which the same request, sent again with the same idempotency key, may succeed. */ const RETRYABLE = new Set(["request_in_progress", "rate_limited", "internal_error", "service_unavailable", "address_pool_empty", "rail_unavailable"]); /** The API answered with an error. Switch on `code`; quote `requestId` when you contact us. */ export class NicePayError extends Error { readonly status: number; readonly code: string; readonly requestId: string | null; readonly retryable: boolean; /** Field problems of an `invalid_request`. */ readonly errors: readonly { readonly field: string; readonly message: string }[]; /** The whole problem body, e.g. `existing_id` on `duplicate_merchant_reference`. */ readonly problem: Readonly>; constructor(status: number, problem: Readonly>, requestId: string | null) { const code = typeof problem["code"] === "string" ? problem["code"] : `http_${String(status)}`; super(`${String(status)} ${code}${typeof problem["detail"] === "string" ? `: ${problem["detail"]}` : ""}`); this.status = status; this.code = code; this.requestId = typeof problem["request_id"] === "string" ? problem["request_id"] : requestId; this.retryable = status >= 500 || RETRYABLE.has(code); this.errors = Array.isArray(problem["errors"]) ? (problem["errors"] as { field: string; message: string }[]) : []; this.problem = problem; } } /** * No answer at all (network failure or timeout), after every allowed retry. When * `outcomeUnknown` is true the request may have been carried out: do not treat it as * failed, do not refund, do not pay another way. Send the same call again later with the * same idempotency key, or look the object up by your own reference. */ export class NoAnswerError extends Error { readonly outcomeUnknown: boolean; readonly idempotencyKey: string | null; constructor(message: string, outcomeUnknown: boolean, idempotencyKey: string | null, cause: unknown) { super(message, { cause }); this.outcomeUnknown = outcomeUnknown; this.idempotencyKey = idempotencyKey; } } const rfc3986 = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); /** No field of the API takes a fractional number: money is a decimal string such as "100.50". */ function refuseFloats(value: unknown, at: string): void { if (typeof value === "number" && !Number.isInteger(value)) throw new TypeError(`${at}: a fractional number; send money as a decimal string`); if (value !== null && typeof value === "object") for (const [k, v] of Object.entries(value)) refuseFloats(v, `${at}.${k}`); } /** A client for one key: `call(method, path, { query, body, idempotencyKey })`. */ export function connect(credentials: Credentials) { const privateKey: KeyObject | null = credentials.privateKey ? createPrivateKey(credentials.privateKey) : null; return async function call>(method: string, path: string, options: CallOptions = {}): Promise { // The query: sorted by name, then value; each part percent-encoded (RFC 3986). It is sent in this form. const pairs: [string, string][] = []; for (const [name, value] of Object.entries(options.query ?? {})) { for (const item of Array.isArray(value) ? (value as readonly string[]) : [value]) if (item !== undefined) pairs.push([rfc3986(name), rfc3986(String(item))]); } pairs.sort(([ak, av], [bk, bv]) => (ak < bk ? -1 : ak > bk ? 1 : av < bv ? -1 : av > bv ? 1 : 0)); const query = pairs.map(([k, v]) => `${k}=${v}`).join("&"); refuseFloats(options.body, "body"); const raw = options.body === undefined ? "" : JSON.stringify(options.body); // serialised once: these bytes are signed and sent const idempotencyKey = options.idempotencyKey ?? null; // Sending again is safe for a GET, and for a write that carries an idempotency key. const safeToRepeat = method === "GET" || idempotencyKey !== null; for (let attempt = 0; ; attempt += 1) { // Signed again on every attempt: a new timestamp and a new nonce — and the same idempotency key. const timestamp = String(Math.floor(Date.now() / 1000)); const nonce = randomBytes(16).toString("base64url"); const canonical = ["NP1", timestamp, nonce, method, path, query, createHash("sha256").update(raw).digest("hex")].join("\n"); const signature = privateKey ? sign(null, Buffer.from(canonical), privateKey).toString("base64") // plain Ed25519 over the canonical string : createHmac("sha256", credentials.secret ?? "").update(canonical).digest("base64"); const headers: Record = { Accept: "application/json", "NP-Key-Id": credentials.keyId, "NP-Timestamp": timestamp, "NP-Nonce": nonce, "NP-Algorithm": privateKey ? "ed25519" : "hmac-sha256", "NP-Signature": signature, }; if (raw !== "") headers["Content-Type"] = "application/json"; if (idempotencyKey !== null) headers["Idempotency-Key"] = idempotencyKey; let response: Response; try { response = await fetch(`${baseUrl}${path}${query === "" ? "" : `?${query}`}`, { method, headers, ...(raw === "" ? {} : { body: raw }), signal: AbortSignal.timeout(30_000), redirect: "error" }); } catch (cause) { if (safeToRepeat && attempt < 3) { await pause(attempt, null); continue; } throw new NoAnswerError(`${method} ${path}: no answer from the API`, method !== "GET", idempotencyKey, cause); } const text = await response.text(); if (response.ok) return (text === "" ? {} : JSON.parse(text)) as T; let problem: Record = {}; try { problem = JSON.parse(text) as Record; } catch { // not JSON: the status alone is the error } const error = new NicePayError(response.status, problem, response.headers.get("np-request-id")); // 429 was refused before anything ran: always safe. 5xx and "in progress": only where a repeat is safe. const again = response.status === 429 || (safeToRepeat && (response.status >= 500 || error.code === "request_in_progress")); if (!again || attempt >= 3) throw error; await pause(attempt, response.headers.get("retry-after")); } }; } /** Exponential back-off with jitter, never shorter than the server's Retry-After. */ function pause(attempt: number, retryAfter: string | null): Promise { const hinted = retryAfter !== null && /^[0-9]{1,4}$/.test(retryAfter) ? Number(retryAfter) * 1000 : 0; const wait = Math.max(hinted, Math.floor(Math.random() * Math.min(8000, 500 * 2 ** attempt))); return new Promise((resolve) => setTimeout(resolve, wait)); } // The key comes from the environment (your secret manager), never from the code. const privateKeyFile = process.env["NICEPAY_PRIVATE_KEY_FILE"]; export const nicepay = connect({ keyId: process.env["NICEPAY_KEY_ID"] ?? "", ...(privateKeyFile ? { privateKey: readFileSync(privateKeyFile, "utf8") } : { secret: process.env["NICEPAY_KEY_SECRET"] ?? "" }), });