Nice Paydocs API version 2026-12-01 OpenAPI

Authentication and signing

Every request carries a signature made with your API key. The signature covers the method, the path, the query, the body, a timestamp and a single-use nonce — so a request cannot be forged, changed on the way, moved to another endpoint or sent a second time. There are no passwords and no bearer tokens in the API. The API is plain HTTPS and JSON: one small file signs for the examples on this site, and this page tells you everything you need to choose a key type, to sign in any other language, or to debug a 401.

At a glance

TopicIn short
SchemeNP1: five NP-… headers on every request
Algorithmshmac-sha256 (a secret we both hold) or ed25519 (your own key pair; recommended) — one per key
What is signedthe method, the path, the query, the SHA-256 of the body, the timestamp and the nonce
Freshnessthe timestamp must be within 300 seconds of our clock
Replay protectiona nonce works once per key
Permissionseach key has scopes, and may be tied to your servers' IP addresses

Keys

You create and revoke keys in the merchant portal under Developers → API keys — never through the API. It takes a team member with the owner, admin or developer role, and a fresh second-factor check.

HMAC or Ed25519

Both are verified the same way and protected the same way against tampering and replay. The difference is who holds something that can sign.

HMAC-SHA256Ed25519
You holda secret, np_live_sk_…, shown once when the key is createda private key that you generate yourself
We holdthe same secret, encrypted — we need it to check your signaturesonly your public key
If our copy were ever exposedthe secret can sign requestsnothing: a public key cannot sign
You needHMAC-SHA256, which every language hasan Ed25519 library (libsodium, OpenSSL, Node's crypto)
NP-Algorithmhmac-sha256ed25519
NP-Signature32 bytes: 44 base64 characters64 bytes: 88 base64 characters

Use Ed25519 for every key that can move money (payouts:write, settlements:write), and anywhere else your platform has an Ed25519 library. The private key is made on your server and never leaves it: it is not shown in a browser, not sent to us and not stored by us. HMAC is fine for a first integration, for test mode and for read-only keys.

Note: Ed25519 is the key type of modern SSH keys (ssh-ed25519), but an SSH key file is not what the portal takes. It takes the raw 32-byte public key in base64url — 43 characters — not an ssh-ed25519 AAAA… line and not a PEM block. Make a key pair for this purpose alone: a key that signs payments should not also log in to servers.

Create an Ed25519 key

1. Generate the pair on the server that will call us. With OpenSSL:

Shell
# The private key: a PKCS#8 PEM file that only your service can read. It stays on this machine.
openssl genpkey -algorithm ed25519 -out nicepay-ed25519.key
chmod 600 nicepay-ed25519.key

# The public key as raw 32 bytes in base64url: paste this line's output into the portal.
openssl pkey -in nicepay-ed25519.key -pubout -outform DER \
  | tail -c 32 | openssl base64 -A | tr '+/' '-_' | tr -d '='

The public key in DER form is a fixed 12-byte header followed by the 32 key bytes, which is why tail -c 32 gives the raw key. If your openssl answers Algorithm ed25519 not found (an old LibreSSL does), use this program instead — it writes the same PEM file and prints the same public key:

runs in CI samples/ts/ed25519-key.ts
// Ed25519 keys (recommended for payout keys): you keep the private key, Nice Pay only
// ever sees the public key.
//   bun ed25519-key.ts generate ./nicepay-ed25519.key   → prints the public key to paste into the portal
//   bun ed25519-key.ts ping ./nicepay-ed25519.key       → NICEPAY_KEY_ID is the key id the portal gave you
import { createPublicKey, generateKeyPairSync } from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { connect } from "./nicepay.ts";

const [command, file = "./nicepay-ed25519.key"] = process.argv.slice(2);

if (command === "generate") {
  const { privateKey } = generateKeyPairSync("ed25519");
  // The private key never leaves your server: a file only your service can read (or your secret manager).
  writeFileSync(file, privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o600 });
  const publicKey = (createPublicKey(privateKey).export({ format: "jwk" }) as { x: string }).x;
  console.log(`public key (paste into the portal): ${publicKey}`);
} else if (command === "ping") {
  // The helper signs with the private key instead of a secret. (Setting
  // NICEPAY_PRIVATE_KEY_FILE does the same for every example on this site.)
  const call = connect({ keyId: process.env["NICEPAY_KEY_ID"] ?? "", privateKey: readFileSync(file, "utf8") });
  const ping = await call<{ livemode: boolean; scopes: string[] }>("GET", "/v1/ping");
  console.log(`signed with Ed25519: livemode ${String(ping.livemode)}, scopes ${ping.scopes.join(" ")}`);
} else {
  throw new Error("usage: ed25519-key.ts generate|ping <file>");
}

2. Register the public key. In the portal, under Developers → API keys, create a key: choose Ed25519 as its signing, paste the 43 characters, and choose the scopes and the IP allowlist. You get a key id. There is no secret to copy: the portal never sees your private key.

3. Give the private key to your client.

Both signing helpers read the PEM file named by NICEPAY_PRIVATE_KEY_FILE and then sign with Ed25519 instead of a secret; PHP needs ext-sodium for it. In your own code, keep the file where only your service can read it, or hold its contents in your secret manager.

A library that wants the raw 32-byte seed instead of the PEM file (libsodium does) finds it at the end of the key:

Shell
# The 32-byte seed in base64url. This IS the private key: send it straight into your secret manager.
openssl pkey -in nicepay-ed25519.key -outform DER \
  | tail -c 32 | openssl base64 -A | tr '+/' '-_' | tr -d '='

Warning: never paste a private key or its seed into a ticket, a chat, an e-mail or the portal. We need only the public key, and we will never ask for the other half.

The headers

HeaderValue
NP-Key-Idyour key id
NP-TimestampUnix time in seconds — digits only, not milliseconds; within 300 seconds of our clock
NP-Nonce16 or more random bytes in base64url without padding: 22 to 128 characters of A–Z a–z 0–9 - _. New for every request, including retries
NP-Algorithmhmac-sha256 or ed25519 — the algorithm of this key
NP-Signaturethe signature of the canonical string, in standard base64 with padding
NP-Versionoptional API version date, e.g. 2026-12-01; without it you get the version the key was created with
Idempotency-Keyrequired on every request that creates or moves money (idempotency); not part of the signature

Every call is signed, reads included. The two exceptions are public and take no credentials: GET/v1/status and our webhook keys at GET/.well-known/webhook-keys.json.

The canonical string

The text you sign is seven lines joined by \n (one line feed), with no newline at the end:

#LineExample
1the literal NP1NP1
2NP-Timestamp, exactly as sent1794900001
3NP-Nonce, exactly as sentEBESExQVFhcYGRobHB0eHw
4the HTTP method in upper caseGET
5the path exactly as sent, without ? and the query/v1/payins
6the canonical query; an empty line when there is no querylimit=5&status=pending
7lower-case hex SHA-256 of the raw body bytes; of the empty string when there is no bodye3b0c442…7852b855

For GET/v1/payins?status=pending&limit=5 that is exactly this (the test vector get-unsorted-query below):

Text
NP1
1794900001
EBESExQVFhcYGRobHB0eHw
GET
/v1/payins
limit=5&status=pending
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Line 6: the query

  1. Split the query into name and value pairs and decode them (%XX; a + is a space).
  2. Percent-encode each name and each value with RFC 3986: A–Z a–z 0–9 - _ . ~ stay as they are, and every other byte becomes %XX in upper-case hex — including ! ' ( ) * and the brackets of types[], which is types%5B%5D.
  3. Sort the pairs by encoded name, then by encoded value, in plain byte order. A name that appears twice keeps both values.
  4. Join them as name=value with &.

We build this line the same way from the query we receive, so the order in which you send the parameters does not change the result. Sending the query exactly as you signed it is still the simplest way to be sure.

Line 7: the body

Serialise your JSON once, keep those bytes, hash those bytes and send those bytes. We hash the raw bytes that arrive, before any JSON is parsed: a different key order, a space or a trailing newline is a different hash. With no body, the line is the SHA-256 of the empty string, e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.

Sign it

Encode the signature in standard base64 with padding and send it as NP-Signature.

What we check, in order

We stop at the first check that fails; the error code says which one it was.

  1. The request came through https://api.mynicepanel.com: edge_auth_failed.
  2. All five headers are present: missing_credentials.
  3. The key id is well formed, exists and is not revoked: invalid_key.
  4. NP-Algorithm is the key's algorithm: invalid_signature.
  5. The request comes from an address on the key's IP allowlist, if it has one: ip_not_allowed.
  6. NP-Timestamp is within 300 seconds of our clock: timestamp_out_of_range.
  7. NP-Nonce has the right form: missing_credentials.
  8. The signature matches the bytes we received: invalid_signature.
  9. The nonce was not used before with this key: nonce_reused.
  10. The key has the scope of the endpoint: insufficient_scope. A /v1/test/… endpoint also needs a test key: test_mode_only.
  11. The merchant account is not closed: merchant_not_active.
  12. The requested API version is one we serve: unsupported_version.
  13. The key is within its rate limit: rate_limited.

Replay protection and clocks

IP allowlist

A key can be tied to the public addresses your servers call us from: up to 20 IPv4 or IPv6 addresses or CIDR ranges, given when the key is created.

Scopes

Give each key only the scopes its job needs; a key without the scope of an endpoint gets 403 insufficient_scope, and the answer names the missing scope.

Rotate a key

Rotation has no downtime, because two keys of a project and mode can be active at once.

  1. Create the new key with the same scopes and IP allowlist. If the project already has two active keys in that mode, revoke the unused one first.
  2. Deploy the new key id and secret (or private key) to your servers.
  3. Watch Last used of the old key in the portal until it stops moving.
  4. Revoke the old key. Revocation is immediate: its next request gets 401 invalid_key.

Rotate on a schedule you choose, and at once when a person who could read the secret leaves your team or when the secret may have been exposed. If you suspect a leak, do not wait for step 3 — revoke first.

Authentication errors

Every refusal is a problem document with a stable code (errors).

CodeHTTPWhat it means
missing_credentials401One of the five NP-… headers is missing, or NP-Nonce is not 22 to 128 base64url characters without padding
invalid_key401The key id is malformed, unknown, revoked or expired
invalid_signature401The signature does not match what we received, or NP-Algorithm is not the key's algorithm
timestamp_out_of_range401NP-Timestamp is not a whole number of seconds, or is more than 300 seconds from our clock
nonce_reused401This key already sent this nonce in the last 10 minutes
ip_not_allowed403The request did not come from an address on the key's allowlist
edge_auth_failed403The request did not come through https://api.mynicepanel.com
insufficient_scope403The key lacks the endpoint's scope; detail names it
test_mode_only403A live key called a /v1/test/… endpoint
merchant_not_active403The merchant account is closed. A frozen account gets this code when it asks for a payout or a settlement
unsupported_version400NP-Version is not a version we serve
rate_limited429Too many requests for this key; wait Retry-After seconds

Test vectors

Check your implementation against these before you call us. They are generated by our server's own code. Each one gives the inputs and the canonical string and signature you must arrive at; the keys are test values that work nowhere. They are also a JSON file, with the exact headers, on the Tools page.

get-no-queryhmac-sha256No query and no body: the query line is empty and the body hash is the SHA-256 of the empty string.
Request
GET /v1/ping
NP-Timestamp
1794900000
NP-Nonce
AAECAwQFBgcICQoLDA0ODw
Body
none
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
WfLo7uiGw+Hx9CVUX1kFzmQDLftdoMYxoERnm8hYZGI=
Canonical string
NP1
1794900000
AAECAwQFBgcICQoLDA0ODw
GET
/v1/ping

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
get-unsorted-queryhmac-sha256Parameters are sorted by name, then value.
Request
GET /v1/payins?status=pending&limit=5
NP-Timestamp
1794900001
NP-Nonce
EBESExQVFhcYGRobHB0eHw
Body
none
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
BDaTMvK6o8lPjjEDNt8Wmn10js48eQ0JUewWS2mlw8Q=
Canonical string
NP1
1794900001
EBESExQVFhcYGRobHB0eHw
GET
/v1/payins
limit=5&status=pending
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
get-repeated-and-bracketedhmac-sha256A repeated name keeps every value, sorted by value; brackets are percent-encoded.
Request
GET /v1/events?types[]=payin.succeeded&after_sequence=10&types[]=payin.created
NP-Timestamp
1794900002
NP-Nonce
ICEiIyQlJicoKSorLC0uLw
Body
none
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
vmIxl2Fp39cM9uqVvAtZY2T+AFwb9tvwdmK4+MTlsJY=
Canonical string
NP1
1794900002
ICEiIyQlJicoKSorLC0uLw
GET
/v1/events
after_sequence=10&types%5B%5D=payin.created&types%5B%5D=payin.succeeded
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
get-encoded-queryhmac-sha256The query is decoded (a + is a space) and re-encoded per RFC 3986 (space → %20, * → %2A, ' → %27).
Request
GET /v1/payins?merchant_order_id=DEP%2A7+x&note=it's
NP-Timestamp
1794900003
NP-Nonce
MDEyMzQ1Njc4OTo7PD0-Pw
Body
none
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
z+lrpzweQVHwUMxbpeE8bUiH8oyVB2OKK6ULwY0MGnk=
Canonical string
NP1
1794900003
MDEyMzQ1Njc4OTo7PD0-Pw
GET
/v1/payins
merchant_order_id=DEP%2A7%20x&note=it%27s
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
post-json-bodyhmac-sha256The body is hashed as the exact bytes sent (UTF-8), never re-serialised.
Request
POST /v1/payins
NP-Timestamp
1794900004
NP-Nonce
QEFCQ0RFRkdISUpLTE1OTw
Body
{"merchant_order_id":"DEP-48213","amount":"10000.00","currency":"INR","method":"upi","customer":{"ref":"7591035","name":"Rāmesh Kumār"}} 138 bytes
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
QmdWsnCj1HIojhBfA/EnRA5ASKVmfkcnA8Cq8Ad1XyI=
Canonical string
NP1
1794900004
QEFCQ0RFRkdISUpLTE1OTw
POST
/v1/payins

845c6e10c891fc79b9df8d9562253f1658433c23fef627ba88cee19ecea94c10
post-trailing-newlinehmac-sha256The same body with a trailing newline is a different body and a different signature.
Request
POST /v1/payins
NP-Timestamp
1794900004
NP-Nonce
QEFCQ0RFRkdISUpLTE1OTw
Body
{"merchant_order_id":"DEP-48213","amount":"10000.00","currency":"INR","method":"upi","customer":{"ref":"7591035","name":"Rāmesh Kumār"}}\n 139 bytes
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
mXLpEWeM2po1tDBDW8xAhVVGWo8kPgfYFHLfcm7Dga8=
Canonical string
NP1
1794900004
QEFCQ0RFRkdISUpLTE1OTw
POST
/v1/payins

6d3a6880680131f59447d8777d390dea0d18641ab44a8bd221b20071c1ab4d39
post-empty-bodyhmac-sha256A POST without a body (cancel) hashes the empty string.
Request
POST /v1/payins/pi_01JD3QH2Y8ZKX4M9T6V0R1B2C3/cancel
NP-Timestamp
1794900005
NP-Nonce
UFFSU1RVVldYWVpbXF1eXw
Body
none
Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0
NP-Signature
Bn0klCv+k483Mwdac9uYbJIKrRldNVwHaIbk35G3xT4=
Canonical string
NP1
1794900005
UFFSU1RVVldYWVpbXF1eXw
POST
/v1/payins/pi_01JD3QH2Y8ZKX4M9T6V0R1B2C3/cancel

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
ed25519-geted25519Ed25519: the same canonical string, signed with the merchant's private key.
Request
GET /v1/payouts?limit=1
NP-Timestamp
1794900006
NP-Nonce
YGFiY2RlZmdoaWprbG1ubw
Body
none
Private key seed
AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA
Public key
ebVWLo_mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ
NP-Signature
T18wiFckQtM4uv8vuri/Hsd3U3bNB0W5RgFn63pcJAh829MSkWzjoIdJtQFidWy2xgqfgem4rtgr3yGu0TGPAg==
Canonical string
NP1
1794900006
YGFiY2RlZmdoaWprbG1ubw
GET
/v1/payouts
limit=1
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
ed25519-posted25519Ed25519 over a payout request body.
Request
POST /v1/payouts
NP-Timestamp
1794900007
NP-Nonce
cHFyc3R1dnd4eXp7fH1-fw
Body
{"merchant_payout_id":"WD-99120","amount":"5000.00","currency":"INR","method":"upi","destination":{"vpa":"ramesh@okhdfc","holder_name":"Ramesh Kumar"}} 151 bytes
Private key seed
AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA
Public key
ebVWLo_mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ
NP-Signature
kvKOpiHJ0uyI2etzqd3tQ9th8hqFctB+sHJ87tZJglMlGCNXcPxYbqH6tri3BdFme79MQEJDYqkIdGQYzgbBCQ==
Canonical string
NP1
1794900007
cHFyc3R1dnd4eXp7fH1-fw
POST
/v1/payouts

be19511621a6f14f59227daaf1abb75411bfa01dcaaac418cda5c22fdd472490

The six most common mistakes

  1. Signing a re-serialised body. You sign JSON.stringify(obj) but your HTTP library sends its own serialisation (different spacing, key order or escaping). Serialise once; sign and send the same bytes.
  2. A query encoded differently. Sort by name then value, encode with RFC 3986, and send the query as you signed it. types[] is types%5B%5D.
  3. Clock skew, or milliseconds. More than 300 seconds off — or a timestamp in milliseconds — gives timestamp_out_of_range. Run NTP and send whole seconds.
  4. Reusing a nonce. A retry is a new request: new timestamp, new nonce, new signature — same idempotency key.
  5. A trailing newline after the last line of the canonical string, or a body with a trailing newline that you did not hash.
  6. The wrong credential: the secret of another key, a test secret with a live key id, or NP-Algorithm that is not the key's algorithm.

The signing helper

The complete client, in one file per language: it builds the canonical string, signs it (HMAC, or Ed25519 when NICEPAY_PRIVATE_KEY_FILE is set), sends exactly the bytes it signed, and retries only where a retry cannot do something twice. Copy it next to your code — nicepay.ts or nicepay.php — or write the same thing in your own language and check it against the test vectors above.

runs in CI samples/ts/nicepay.ts samples/php/nicepay.php
// 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<Record<string, string | number | boolean | readonly string[] | undefined>>;
  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<Record<string, unknown>>;

  constructor(status: number, problem: Readonly<Record<string, unknown>>, 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<T = Record<string, unknown>>(method: string, path: string, options: CallOptions = {}): Promise<T> {
    // 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<string, string> = {
        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<string, unknown> = {};
      try {
        problem = JSON.parse(text) as Record<string, unknown>;
      } 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<void> {
  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"] ?? "" }),
});

Using it — a read, a list with a query, and a write with an idempotency key:

runs in CI samples/ts/sign-request.ts samples/php/sign-request.php
// Using the helper: a read, a list with a query, and a write with an idempotency key.
//   NICEPAY_KEY_ID=np_test_kid_… NICEPAY_KEY_SECRET=np_test_sk_… bun sign-request.ts
import { nicepay } from "./nicepay.ts";

const ping = await nicepay<{ livemode: boolean }>("GET", "/v1/ping");
console.log(`ping: livemode ${String(ping.livemode)}`);

// The query is sorted, encoded and signed by the helper, and sent exactly as signed.
const list = await nicepay<{ data: unknown[] }>("GET", "/v1/payins", { query: { status: "succeeded", limit: 3 } });
console.log(`listed ${String(list.data.length)} succeeded pay-ins`);

// A request that creates money carries an idempotency key: your own order id.
const orderId = `RAW-${String(Date.now())}`;
const created = await nicepay<{ id: string }>("POST", "/v1/payins", {
  body: { merchant_order_id: orderId, amount: "300.00", currency: "INR", method: "upi", customer: { ref: "p1" } },
  idempotencyKey: orderId,
});
console.log(`created ${created.id}`);

With an Ed25519 key, everything is the same except the signature itself and NP-Algorithm. Step by step, without the helper:

runs in CI samples/ts/sign-ed25519.ts
// NP1 with an Ed25519 key, step by step: the canonical string is the same as for HMAC; only
// the signature and NP-Algorithm differ. The private key is the PKCS#8 PEM file made by
// ed25519-key.ts (or by openssl genpkey).
//   bun sign-ed25519.ts ./nicepay-ed25519.key
import { createHash, createPrivateKey, randomBytes, sign } from "node:crypto";
import { readFileSync } from "node:fs";

const keyId = process.env["NICEPAY_KEY_ID"] ?? "";
const base = process.env["NICEPAY_API_BASE"] ?? "https://api.mynicepanel.com";
const privateKey = createPrivateKey(readFileSync(process.argv[2] ?? "./nicepay-ed25519.key", "utf8"));

const method = "GET";
const path = "/v1/ping";
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString("base64url"); // new for every request, including retries
const bodyHash = createHash("sha256").update("").digest("hex"); // no body: the hash of the empty string
const canonical = ["NP1", timestamp, nonce, method, path, "", bodyHash].join("\n");
// Plain Ed25519 over the bytes of the canonical string (no pre-hash): 64 bytes, sent as base64.
const signature = sign(null, Buffer.from(canonical), privateKey).toString("base64");

const res = await fetch(`${base}${path}`, {
  method,
  headers: { "NP-Key-Id": keyId, "NP-Timestamp": timestamp, "NP-Nonce": nonce, "NP-Algorithm": "ed25519", "NP-Signature": signature },
});
const json = (await res.json()) as { livemode?: boolean; code?: string };
if (!res.ok) throw new Error(`${String(res.status)} ${String(json.code)}`);
console.log(`ping with Ed25519: livemode ${String(json.livemode)}`);

Security checklist

What we will never ask you for

We never ask for your secret or your private key — not by e-mail, chat or phone, and not in the portal after the key was created. Anyone who asks is not us. If a secret may have leaked, revoke the key in the portal at once; revocation is immediate.