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 SDKs sign for you; read this page to choose a key type, to write your own client, or to debug a 401.
At a glance
| Topic | In short |
|---|---|
| Scheme | NP1: five NP-… headers on every request |
| Algorithms | hmac-sha256 (a secret we both hold) or ed25519 (your own key pair; recommended) — one per key |
| What is signed | the method, the path, the query, the SHA-256 of the body, the timestamp and the nonce |
| Freshness | the timestamp must be within 300 seconds of our clock |
| Replay protection | a nonce works once per key |
| Permissions | each 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.
- A key belongs to one project and one mode. Its id says which:
np_test_kid_…ornp_live_kid_…. A test key sees only test objects and a live key only live ones; asking for an object of the other mode givesnot_found, never the other mode's data. - The key id is not a secret: it goes out with every request. What you protect is the HMAC secret or the Ed25519 private key.
- Live keys can be created once your account is approved. Until then you work in test mode.
- A key's algorithm, scopes and IP allowlist are fixed when it is created. To change one, create a new key and revoke the old one.
- A project can have two active keys per mode, so that you can rotate without downtime.
GET/v1/pinganswers with the project, mode, scopes and API version of the key that signed it — a quick way to check a new key.
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-SHA256 | Ed25519 | |
|---|---|---|
| You hold | a secret, np_live_sk_…, shown once when the key is created | a private key that you generate yourself |
| We hold | the same secret, encrypted — we need it to check your signatures | only your public key |
| If our copy were ever exposed | the secret can sign requests | nothing: a public key cannot sign |
| You need | HMAC-SHA256, which every language has | an Ed25519 library (libsodium, OpenSSL, Node's crypto) |
NP-Algorithm | hmac-sha256 | ed25519 |
NP-Signature | 32 bytes: 44 base64 characters | 64 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 anssh-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:
# 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:
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 { NicePay } from "@nicepay/sdk-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") {
const nicepay = new NicePay({
keyId: process.env["NICEPAY_KEY_ID"] ?? "",
privateKey: readFileSync(file, "utf8"), // PKCS#8 PEM, a KeyObject, or the 32-byte seed in base64url
...(process.env["NICEPAY_API_BASE"] ? { baseUrl: process.env["NICEPAY_API_BASE"] } : {}),
});
const ping = await nicepay.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.
- TypeScript:
new NicePay({ keyId, privateKey }), whereprivateKeyis the PEM text, a NodeKeyObject, or the 32-byte seed in base64url. - PHP:
new NicePay\Client(['key_id' => …, 'private_key' => …]), whereprivate_keyis the 32-byte seed in base64url (the 64-byte libsodium secret key in base64url also works). PHP does not take the PEM file; get the seed from it with the line below.
# 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
| Header | Value |
|---|---|
NP-Key-Id | your key id |
NP-Timestamp | Unix time in seconds — digits only, not milliseconds; within 300 seconds of our clock |
NP-Nonce | 16 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-Algorithm | hmac-sha256 or ed25519 — the algorithm of this key |
NP-Signature | the signature of the canonical string, in standard base64 with padding |
NP-Version | optional API version date, e.g. 2026-12-01; without it you get the version the key was created with |
Idempotency-Key | required 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:
| # | Line | Example |
|---|---|---|
| 1 | the literal NP1 | NP1 |
| 2 | NP-Timestamp, exactly as sent | 1794900001 |
| 3 | NP-Nonce, exactly as sent | EBESExQVFhcYGRobHB0eHw |
| 4 | the HTTP method in upper case | GET |
| 5 | the path exactly as sent, without ? and the query | /v1/payins |
| 6 | the canonical query; an empty line when there is no query | limit=5&status=pending |
| 7 | lower-case hex SHA-256 of the raw body bytes; of the empty string when there is no body | e3b0c442…7852b855 |
For GET/v1/payins?status=pending&limit=5 that is exactly this (the test vector get-unsorted-query below):
NP1
1794900001
EBESExQVFhcYGRobHB0eHw
GET
/v1/payins
limit=5&status=pending
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Line 6: the query
- Split the query into name and value pairs and decode them (
%XX; a+is a space). - 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%XXin upper-case hex — including! ' ( ) *and the brackets oftypes[], which istypes%5B%5D. - Sort the pairs by encoded name, then by encoded value, in plain byte order. A name that appears twice keeps both values.
- Join them as
name=valuewith&.
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
- HMAC-SHA256: the key is your secret exactly as the portal showed it — the whole
np_…_sk_…text, not decoded in any way; the message is the canonical string in UTF-8. - Ed25519: a plain Ed25519 signature (no pre-hashing) of the same bytes, made with your private key.
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.
- The request came through
https://api.mynicepanel.com:edge_auth_failed. - All five headers are present:
missing_credentials. - The key id is well formed, exists and is not revoked:
invalid_key. NP-Algorithmis the key's algorithm:invalid_signature.- The request comes from an address on the key's IP allowlist, if it has one:
ip_not_allowed. NP-Timestampis within 300 seconds of our clock:timestamp_out_of_range.NP-Noncehas the right form:missing_credentials.- The signature matches the bytes we received:
invalid_signature. - The nonce was not used before with this key:
nonce_reused. - The key has the scope of the endpoint:
insufficient_scope. A/v1/test/…endpoint also needs a test key:test_mode_only. - The merchant account is not closed:
merchant_not_active. - The requested API version is one we serve:
unsupported_version. - The key is within its rate limit:
rate_limited.
Replay protection and clocks
- The timestamp limits how long a signed request is good for: 300 seconds either side of our clock. Keep your servers on NTP.
- The nonce makes it good for one use. We remember every nonce of a key for 10 minutes — as long as its timestamp can stay valid — and refuse a second request with the same one. A request that fails the signature check does not use up its nonce.
- A retry is a new request: a new timestamp, a new nonce and a new signature — with the same
Idempotency-Key, which is what stops the money from moving twice (idempotency). - A copy of one of your requests is therefore useless to anyone who captures it: it cannot be sent again, and changing a single byte of it breaks the signature.
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.
- It is mandatory for a key with
payouts:writeorsettlements:write; the portal will not create one without it. - A request from any other address gets
403 ip_not_allowed, however good its signature is. - The address that counts is the one your request leaves your network from (your NAT or egress address), not a private one.
- The list cannot be edited afterwards. When your addresses change, create a key with the new list and revoke the old key.
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.
| Scope | Calls it allows |
|---|---|
payins:write | createPayin cancelPayin submitPayinReference simulatePayin |
payins:read | listPayins getPayin |
payouts:write | createPayout cancelPayout simulatePayout |
payouts:read | listPayouts getPayout |
balances:read | getBalances listBalanceTransactions listTopups listTopupAddresses |
settlements:write | createSettlement |
settlements:read | listSettlements getSettlement listSettlementDestinations |
crypto:write | createCryptoAddress |
crypto:read | listCryptoAddresses getCryptoAddress |
events:read | listEvents getEvent createStreamToken |
webhooks:write | redeliverEvent listWebhookEndpoints createWebhookEndpoint getWebhookEndpoint updateWebhookEndpoint deleteWebhookEndpoint |
reports:write | createReport getReport |
| any valid key | ping listMethods getReferenceRates |
Rotate a key
Rotation has no downtime, because two keys of a project and mode can be active at once.
- 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.
- Deploy the new key id and secret (or private key) to your servers.
- Watch Last used of the old key in the portal until it stops moving.
- 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).
| Code | HTTP | What it means |
|---|---|---|
missing_credentials | 401 | One of the five NP-… headers is missing, or NP-Nonce is not 22 to 128 base64url characters without padding |
invalid_key | 401 | The key id is malformed, unknown, revoked or expired |
invalid_signature | 401 | The signature does not match what we received, or NP-Algorithm is not the key's algorithm |
timestamp_out_of_range | 401 | NP-Timestamp is not a whole number of seconds, or is more than 300 seconds from our clock |
nonce_reused | 401 | This key already sent this nonce in the last 10 minutes |
ip_not_allowed | 403 | The request did not come from an address on the key's allowlist |
edge_auth_failed | 403 | The request did not come through https://api.mynicepanel.com |
insufficient_scope | 403 | The key lacks the endpoint's scope; detail names it |
test_mode_only | 403 | A live key called a /v1/test/… endpoint |
merchant_not_active | 403 | The merchant account is closed. A frozen account gets this code when it asks for a payout or a settlement |
unsupported_version | 400 | NP-Version is not a version we serve |
rate_limited | 429 | Too 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, and both SDKs pass all of them in CI. 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-Timestamp1794900000NP-NonceAAECAwQFBgcICQoLDA0ODw- Body
- none
- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignatureWfLo7uiGw+Hx9CVUX1kFzmQDLftdoMYxoERnm8hYZGI=
NP1
1794900000
AAECAwQFBgcICQoLDA0ODw
GET
/v1/ping
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855get-unsorted-queryhmac-sha256Parameters are sorted by name, then value.
- Request
- GET
/v1/payins?status=pending&limit=5 NP-Timestamp1794900001NP-NonceEBESExQVFhcYGRobHB0eHw- Body
- none
- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignatureBDaTMvK6o8lPjjEDNt8Wmn10js48eQ0JUewWS2mlw8Q=
NP1
1794900001
EBESExQVFhcYGRobHB0eHw
GET
/v1/payins
limit=5&status=pending
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855get-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-Timestamp1794900002NP-NonceICEiIyQlJicoKSorLC0uLw- Body
- none
- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignaturevmIxl2Fp39cM9uqVvAtZY2T+AFwb9tvwdmK4+MTlsJY=
NP1
1794900002
ICEiIyQlJicoKSorLC0uLw
GET
/v1/events
after_sequence=10&types%5B%5D=payin.created&types%5B%5D=payin.succeeded
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855get-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¬e=it's NP-Timestamp1794900003NP-NonceMDEyMzQ1Njc4OTo7PD0-Pw- Body
- none
- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-Signaturez+lrpzweQVHwUMxbpeE8bUiH8oyVB2OKK6ULwY0MGnk=
NP1
1794900003
MDEyMzQ1Njc4OTo7PD0-Pw
GET
/v1/payins
merchant_order_id=DEP%2A7%20x¬e=it%27s
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855post-json-bodyhmac-sha256The body is hashed as the exact bytes sent (UTF-8), never re-serialised.
- Request
- POST
/v1/payins NP-Timestamp1794900004NP-NonceQEFCQ0RFRkdISUpLTE1OTw- 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_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignatureQmdWsnCj1HIojhBfA/EnRA5ASKVmfkcnA8Cq8Ad1XyI=
NP1
1794900004
QEFCQ0RFRkdISUpLTE1OTw
POST
/v1/payins
845c6e10c891fc79b9df8d9562253f1658433c23fef627ba88cee19ecea94c10post-trailing-newlinehmac-sha256The same body with a trailing newline is a different body and a different signature.
- Request
- POST
/v1/payins NP-Timestamp1794900004NP-NonceQEFCQ0RFRkdISUpLTE1OTw- Body
{"merchant_order_id":"DEP-48213","amount":"10000.00","currency":"INR","method":"upi","customer":{"ref":"7591035","name":"Rāmesh Kumār"}}\n139 bytes- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignaturemXLpEWeM2po1tDBDW8xAhVVGWo8kPgfYFHLfcm7Dga8=
NP1
1794900004
QEFCQ0RFRkdISUpLTE1OTw
POST
/v1/payins
6d3a6880680131f59447d8777d390dea0d18641ab44a8bd221b20071c1ab4d39post-empty-bodyhmac-sha256A POST without a body (cancel) hashes the empty string.
- Request
- POST
/v1/payins/pi_01JD3QH2Y8ZKX4M9T6V0R1B2C3/cancel NP-Timestamp1794900005NP-NonceUFFSU1RVVldYWVpbXF1eXw- Body
- none
- Secret
np_test_sk_TESTVECTORTESTVECTORTESTVECTORTESTVECTORNOTAKEY0NP-SignatureBn0klCv+k483Mwdac9uYbJIKrRldNVwHaIbk35G3xT4=
NP1
1794900005
UFFSU1RVVldYWVpbXF1eXw
POST
/v1/payins/pi_01JD3QH2Y8ZKX4M9T6V0R1B2C3/cancel
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855ed25519-geted25519Ed25519: the same canonical string, signed with the merchant's private key.
- Request
- GET
/v1/payouts?limit=1 NP-Timestamp1794900006NP-NonceYGFiY2RlZmdoaWprbG1ubw- Body
- none
- Private key seed
AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA- Public key
ebVWLo_mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQNP-SignatureT18wiFckQtM4uv8vuri/Hsd3U3bNB0W5RgFn63pcJAh829MSkWzjoIdJtQFidWy2xgqfgem4rtgr3yGu0TGPAg==
NP1
1794900006
YGFiY2RlZmdoaWprbG1ubw
GET
/v1/payouts
limit=1
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855ed25519-posted25519Ed25519 over a payout request body.
- Request
- POST
/v1/payouts NP-Timestamp1794900007NP-NoncecHFyc3R1dnd4eXp7fH1-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_mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQNP-SignaturekvKOpiHJ0uyI2etzqd3tQ9th8hqFctB+sHJ87tZJglMlGCNXcPxYbqH6tri3BdFme79MQEJDYqkIdGQYzgbBCQ==
NP1
1794900007
cHFyc3R1dnd4eXp7fH1-fw
POST
/v1/payouts
be19511621a6f14f59227daaf1abb75411bfa01dcaaac418cda5c22fdd472490The six most common mistakes
- 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. - A query encoded differently. Sort by name then value, encode with RFC 3986, and send the query as you signed it.
types[]istypes%5B%5D. - 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. - Reusing a nonce. A retry is a new request: new timestamp, new nonce, new signature — same idempotency key.
- A trailing newline after the last line of the canonical string, or a body with a trailing newline that you did not hash.
- The wrong credential: the secret of another key, a test secret with a live key id, or
NP-Algorithmthat is not the key's algorithm.
Signing without an SDK
The complete HMAC client, in a page of code. Check yours against the test vectors above.
samples/ts/sign-request.ts samples/php/sign-request.php// NP1 by hand, without the SDK: build the canonical string, sign it, send exactly the
// bytes you signed. Check your own implementation against the test vectors first.
import { createHash, createHmac, randomBytes } from "node:crypto";
const keyId = process.env["NICEPAY_KEY_ID"] ?? "";
const secret = process.env["NICEPAY_KEY_SECRET"] ?? "";
const base = process.env["NICEPAY_API_BASE"] ?? "https://api.mynicepanel.com";
const rfc3986 = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
async function call(method: string, path: string, query: Record<string, string>, body?: unknown): Promise<unknown> {
// Sorted by name, then value; each part percent-encoded (RFC 3986). Send it in this form.
const q = Object.entries(query)
.map(([k, v]) => [rfc3986(k), rfc3986(v)])
.sort(([ak = "", av = ""], [bk = "", bv = ""]) => (ak < bk ? -1 : ak > bk ? 1 : av < bv ? -1 : av > bv ? 1 : 0))
.map(([k, v]) => `${String(k)}=${String(v)}`)
.join("&");
const raw = body === undefined ? "" : JSON.stringify(body); // serialise once; sign and send these bytes
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString("base64url"); // new for every request, including retries
const canonical = ["NP1", timestamp, nonce, method, path, q, createHash("sha256").update(raw).digest("hex")].join("\n");
const signature = createHmac("sha256", secret).update(canonical).digest("base64");
const res = await fetch(`${base}${path}${q ? `?${q}` : ""}`, {
method,
headers: {
"NP-Key-Id": keyId,
"NP-Timestamp": timestamp,
"NP-Nonce": nonce,
"NP-Algorithm": "hmac-sha256",
"NP-Signature": signature,
...(raw ? { "Content-Type": "application/json", "Idempotency-Key": `raw-${nonce}` } : {}),
},
...(raw ? { body: raw } : {}),
});
const json = (await res.json()) as Record<string, unknown>;
if (!res.ok) throw new Error(`${String(res.status)} ${String(json["code"])}`);
return json;
}
const ping = (await call("GET", "/v1/ping", {})) as { livemode: boolean };
console.log(`ping: livemode ${String(ping.livemode)}`);
const list = (await call("GET", "/v1/payins", { status: "succeeded", limit: "3" })) as { data: unknown[] };
console.log(`listed ${String(list.data.length)} succeeded pay-ins`);
const created = (await call("POST", "/v1/payins", {}, { merchant_order_id: `RAW-${String(Date.now())}`, amount: "300.00", currency: "INR", method: "upi", customer: { ref: "p1" } })) as { id: string };
console.log(`created ${created.id}`);<?php
// NP1 by hand, without the SDK (PHP 8.1+, ext-curl): build the canonical string, sign
// it, send exactly the bytes you signed.
declare(strict_types=1);
$keyId = getenv('NICEPAY_KEY_ID') ?: '';
$secret = getenv('NICEPAY_KEY_SECRET') ?: '';
$base = getenv('NICEPAY_API_BASE') ?: 'https://api.mynicepanel.com';
function nicepay_call(string $method, string $path, array $query = [], ?array $body = null): array
{
global $keyId, $secret, $base;
// Sorted by name, then value; RFC 3986 encoding (rawurlencode). Send it in this form.
$pairs = [];
foreach ($query as $k => $v) {
$pairs[] = [rawurlencode((string) $k), rawurlencode((string) $v)];
}
usort($pairs, static fn ($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));
$q = implode('&', array_map(static fn ($p) => $p[0] . '=' . $p[1], $pairs));
// Encode once; sign and send these exact bytes. Amounts are strings.
$raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$timestamp = (string) time();
$nonce = rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '='); // new for every request
$canonical = implode("\n", ['NP1', $timestamp, $nonce, $method, $path, $q, hash('sha256', $raw)]);
$signature = base64_encode(hash_hmac('sha256', $canonical, $secret, true));
$headers = ["NP-Key-Id: {$keyId}", "NP-Timestamp: {$timestamp}", "NP-Nonce: {$nonce}", 'NP-Algorithm: hmac-sha256', "NP-Signature: {$signature}"];
if ($raw !== '') {
$headers[] = 'Content-Type: application/json';
$headers[] = "Idempotency-Key: raw-{$nonce}";
}
$ch = curl_init($base . $path . ($q !== '' ? '?' . $q : ''));
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
if ($raw !== '') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw);
}
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$json = json_decode((string) $response, true);
if ($status >= 400) {
throw new RuntimeException("{$status} " . ($json['code'] ?? 'error'));
}
return $json;
}
$ping = nicepay_call('GET', '/v1/ping');
echo 'ping: livemode ' . var_export($ping['livemode'], true) . "\n";
$list = nicepay_call('GET', '/v1/payins', ['status' => 'succeeded', 'limit' => '3']);
echo 'listed ' . count($list['data']) . " succeeded pay-ins\n";
$created = nicepay_call('POST', '/v1/payins', [], ['merchant_order_id' => 'RAW-PHP-' . time(), 'amount' => '300.00', 'currency' => 'INR', 'method' => 'upi', 'customer' => ['ref' => 'p1']]);
echo "created {$created['id']}\n";With an Ed25519 key, everything is the same except the signature itself and NP-Algorithm:
samples/ts/sign-ed25519.ts// NP1 with an Ed25519 key, by hand: 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
- Keep secrets and private keys in a secret manager or your platform's secret store — never in code, a repository, a log, a ticket or a chat.
- Sign on your server only. Never put a key in a web page, a mobile app or any other code that runs on a customer's device: whoever has the app has the key.
- Use Ed25519 for keys that move money, and an IP allowlist on every live key, not only where it is mandatory.
- Give each key the fewest scopes that do its job.
- Verify the signature of every webhook on the raw body before you act on it, and fetch the object again before you give value (webhooks). Never credit a customer because of a redirect or an unsigned call.
- Rotate when someone with access leaves your team, and revoke keys that are no longer used.
- Keep your servers' clocks on NTP.
- Use test keys in Postman and other tools; a tool that holds a live secret can move your money.
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.