Click Pay ApiClick Pay Api
  • en-US
  • 简体中文
  • en-US
  • 简体中文
  • Node.js Signing And Verification

Node.js Signing And Verification

Runtime

Node.js 18+; built-in crypto and fetch. Express is only needed for the callback integration example.

Shared Contract

These examples implement the default merchant API and default platform callback, not separately agreed custom signature formats. Both languages of the documentation include the same executable source files.

API request with a body, signed with the merchant private key:

path + lowercaseHex(SHA512(rawBody)) + Timestamp

API request without a body, signed with the merchant private key:

path + Timestamp

Default asynchronous callback, verified with the platform public key:

lowercaseHex(SHA512(rawBody)) + Timestamp

Synchronous API response envelope, verified with the platform public key:

lowercaseHex(SHA512(platform-serialized data bytes)) + timestamp
  • Use RSA PKCS#1 v1.5 with SHA-512 and standard Base64 signatures, not RSA-PSS or RSA encryption.
  • Timestamps are Unix seconds. Verification uses the received timestamp, not a newly generated value. Header names are case-insensitive; Base64 signature values are case-sensitive.
  • The API path excludes scheme, host and query string. Callback signing content has no URL, path or separators.
  • Serialize JSON once. Sign and transmit exactly the same UTF-8 bytes. No sorting is required, but field order, whitespace, escaping, newlines and numeric representation must match the transmitted bytes.
  • Use null / nil / None for no request body. A present zero-byte body is different. Callback verification always hashes the complete received body.
  • Supported keys: unencrypted PKCS#1 / PKCS#8 private keys and X.509 SPKI / PKCS#1 public keys, as PEM or plain Base64, including escaped newlines. Certificates, encrypted private keys, SSH keys and non-RSA keys are not supported by these samples.
  • Sign requests with your merchant private key. Verify with the configured platform public key, not your merchant public key or a key supplied in an incoming request. Never share private keys with support; rotate exposed keys.

Failure Handling

Signing failures throw an exception or return an error. Stop the request; never send an empty signature. Verification returns normally on success and throws/returns an error on failure, logging [payment-verify] FAILED. Never ignore verification failures or continue processing financial effects.

Logs contain the stage, byte lengths and diagnostic reason, not payloads, complete signatures or keys. Keep diagnostics internal, disable HTTP body logging and rate-limit failed requests and logs.

Keep HTTPS certificate and hostname verification enabled. A timeout does not prove order creation failed. Do not automatically resubmit an order; query by merchant order number or reconcile manually.

Callback Integration

Limit body size, read raw bytes and the Timestamp / Signature headers, then verify before parsing JSON. Validate order ownership, amount, currency and allowed state transitions. Apply changes transactionally and idempotently. Return the required SUCCESS acknowledgement only after durable processing. Repeated deliveries must not apply financial effects twice.

Cryptographic verification alone does not prevent replay. Choose timestamp tolerance compatible with platform redelivery rules; implement durable idempotency, replay controls and rate limits separately. An overly short freshness window can reject legitimate retries.

Synchronous Responses Are Not Callbacks

For API response envelopes, read timestamp and sign from JSON, and verify the platform-serialized data bytes, not the entire response. For callbacks, read headers and verify the entire HTTP body.

Do not parse and re-serialize data: large integers, 1.00, escaping and field ordering may change. Use a parser that preserves the original JSON value text (for example Go json.RawMessage or C# JsonElement.GetRawText()), then pass its UTF-8 bytes to verifyPlatform / VerifyPlatform / verify_platform. Preserve JSON quotes/escapes for string values and the literal null for null values. Do not add whitespace. Missing signatures, malformed fields and failed verification are not trusted business results.

API Paths

Use the same request helper for the paths below. Refer to the relevant currency documentation for payload fields.

MethodPathPurpose
POST/v1/merchant/payCollection order
POST/v1/merchant/pay/order/infoCollection query
POST/v1/merchant/payoutPayout order
POST/v1/merchant/payout/order/infoPayout query
GET/v1/merchant/accountBalance query, no body

Signing And Verification Source

sign.cjs

const crypto = require('node:crypto');

function fail(message) { throw new Error(message); }
function timestamp(value) {
  const text = String(value);
  if (!/^[1-9][0-9]{0,18}$/.test(text) || BigInt(text) > 9223372036854775807n) fail('invalid Timestamp: use Unix seconds');
  return text;
}
function base64(text, label) {
  if (typeof text !== 'string' || !text || text.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) fail(`${label}: invalid Base64`);
  const bytes = Buffer.from(text, 'base64');
  if (bytes.toString('base64') !== text) fail(`${label}: non-canonical Base64`);
  return bytes;
}
function key(input, privateKey) {
  if (typeof input !== 'string' || input.length > 16384) fail('key: missing or too large');
  let text = input.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n').trim();
  const labels = privateKey ? ['PRIVATE KEY', 'RSA PRIVATE KEY'] : ['PUBLIC KEY', 'RSA PUBLIC KEY'];
  if (text.startsWith('-----BEGIN')) {
    const match = /^-----BEGIN ([A-Z ]+)-----\s*([A-Za-z0-9+/=\s]+)\s*-----END \1-----$/.exec(text);
    if (!match || !labels.includes(match[1])) fail('key: expected one unencrypted RSA PEM block of the correct kind');
    text = match[2];
  }
  const der = base64(text.replace(/\s/g, ''), 'key');
  for (const type of privateKey ? ['pkcs8', 'pkcs1'] : ['spki', 'pkcs1']) {
    try {
      const result = privateKey ? crypto.createPrivateKey({ key: der, format: 'der', type })
        : crypto.createPublicKey({ key: der, format: 'der', type });
      if (result.asymmetricKeyType !== 'rsa') fail('key: not RSA');
      // createPublicKey can otherwise derive a public key from private-key input.
      if (!privateKey && !result.export({ format: 'der', type }).equals(der)) continue;
      return result;
    } catch { /* Try the other documented DER container. */ }
  }
  fail(`key: invalid/truncated or non-RSA ${privateKey ? 'private' : 'public'} key`);
}
function checked(operation, body, action) {
  try { return action(); }
  catch (error) {
    console.error(`[payment-${operation}] FAILED body_bytes=${Buffer.isBuffer(body) ? body.length : 0} error=${JSON.stringify(error.message)}`);
    throw error;
  }
}
function hash(body) {
  if (!Buffer.isBuffer(body)) fail('body: expected raw Buffer, not a parsed JSON object');
  return crypto.createHash('sha512').update(body).digest('hex');
}

// null means no request body. Buffer.alloc(0) means a present, empty body.
function signRequest(path, body, ts, merchantPrivateKey) {
  return checked('sign', body, () => {
    if (typeof path !== 'string' || !path.startsWith('/')) fail('path: expected API path');
    const origin = path + (body === null ? '' : hash(body)) + timestamp(ts);
    return crypto.sign('sha512', Buffer.from(origin, 'utf8'), {
      key: key(merchantPrivateKey, true), padding: crypto.constants.RSA_PKCS1_PADDING,
    }).toString('base64');
  });
}

// Callbacks: exact HTTP body + header Timestamp/Signature, with the PLATFORM public key.
// Signed API envelopes: pass the exact serialized data bytes, not the whole envelope.
function verifyPlatform(body, ts, signature, platformPublicKey) {
  return checked('verify', body, () => {
    const origin = hash(body) + timestamp(ts); // NO path or URL.
    const publicKey = key(platformPublicKey, false);
    const sig = base64(signature, 'Signature');
    const expected = Math.ceil(publicKey.asymmetricKeyDetails.modulusLength / 8);
    if (sig.length !== expected) fail(`Signature length: got ${sig.length}, expected ${expected} bytes`);
    if (!crypto.verify('sha512', Buffer.from(origin, 'utf8'), {
      key: publicKey, padding: crypto.constants.RSA_PKCS1_PADDING,
    }, sig)) fail('RSA SHA512 verification failed: check platform key, raw bytes, timestamp and formula');
  });
}
module.exports = { signRequest, verifyPlatform };

HTTP Helper

http.cjs

const { signRequest } = require('./sign.cjs');

// Node.js 18+. Serialize once before calling; rawBody is Buffer or null.
async function send(baseUrl, path, merchantCode, rawBody, merchantPrivateKey) {
  if (!baseUrl.startsWith('https://')) throw new Error('HTTPS is required');
  const timestamp = String(Math.floor(Date.now() / 1000));
  const signature = signRequest(path, rawBody, timestamp, merchantPrivateKey);
  const response = await fetch(baseUrl + path, {
    method: rawBody === null ? 'GET' : 'POST',
    body: rawBody,
    headers: { 'Content-Type': 'application/json', 'Merchant-Code': merchantCode,
      Timestamp: timestamp, Signature: signature },
    redirect: 'error', signal: AbortSignal.timeout(60000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}; reconcile before retrying`);
  const chunks = [];
  let size = 0;
  for await (const chunk of response.body) {
    size += chunk.length;
    if (size > 8 * 1024 * 1024) throw new Error('Response exceeds 8 MiB');
    chunks.push(chunk);
  }
  return Buffer.concat(chunks); // Preserve raw response for envelope verification.
}
module.exports = { send };

Integration Examples

The following snippets run inside your application; payload, trusted configuration and transactional business handlers must be supplied by your integration. They do not automatically submit real orders.

const { signRequest, verifyPlatform } = require('./sign.cjs');
const { send } = require('./http.cjs');
const body = Buffer.from(JSON.stringify(payload), 'utf8');
const responseBytes = await send(baseUrl, '/v1/merchant/pay', merchantCode, body, merchantPrivateKey);
// GET: await send(baseUrl, '/v1/merchant/account', merchantCode, null, merchantPrivateKey);
// Verify the signed response data before using it. Do not treat HTTP 200 as payment success.
// Express: register this raw-body route BEFORE any express.json() middleware.
app.post('/callback', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res, next) => {
  try {
    verifyPlatform(req.body, req.get('Timestamp'), req.get('Signature'), configuredPlatformPublicKey);
  } catch { return res.status(401).send('invalid signature'); }
  try {
    const event = JSON.parse(req.body.toString('utf8'));
    await validateAndApplyIdempotently(event); // Your durable business transaction.
    res.status(200).send('SUCCESS');
  } catch (error) { next(error); }
});
Last Updated: 9/22/26, 2:41 PM
Contributors: aa, aaa