Skip to Content
StagePayDocs v2

Request Signing (Optional)

The optional X-StagePay-Signature request signing specification for preventing REST API body tampering and replay attacks, with Node.js, PHP, and Python examples.

In addition to API key authentication, you can attach an HMAC signature to each request to prevent body tampering and replay. The signature specification is the same HMAC-SHA256 scheme as callback signatures, just in the opposite direction (merchant → StagePay).

Optional feature

Request signing is optional. Requests without signature headers are still processed with the API key alone. We recommend it for requests that send sensitive fields, such as a price override (price). To make signatures mandatory, discuss the key settings with the operations team.

Specification

signed_payload = X-StagePay-Timestamp + "." + rawBody
X-StagePay-Signature = "v1=" + hex( HMAC-SHA256( key = API key secret, message = signed_payload ) )
ItemValue
KeyThe API key's secret (the part after : in the Bearer token), UTF-8
rawBodyThe body bytes actually sent. An empty string if there is no body, as with GET
X-StagePay-TimestampUnix seconds. Must be within 300 seconds of the server time
Result64 lowercase hexadecimal characters, with the v1= prefix

You must send exactly the same bytes as the string you signed. Send the JSON as a string so that your HTTP client does not re-serialize it after signing.

Examples

import crypto from 'node:crypto';

const keyId = process.env.STAGEPAY_KEY_ID;
const secret = process.env.STAGEPAY_KEY_SECRET;

export async function stagepayPost(path, payload) {
  const body = JSON.stringify(payload);
  const ts = Math.floor(Date.now() / 1000).toString();
  const sig = 'v1=' + crypto.createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex');
  const res = await fetch(`https://api.stagepay.io${path}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${keyId}:${secret}`,
      'Content-Type': 'application/json',
      'X-StagePay-Timestamp': ts,
      'X-StagePay-Signature': sig,
    },
    body, // Exactly the string that was signed
  });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  return res.json();
}

Errors

HTTPCause
401Signature mismatch, missing or malformed timestamp, outside the allowed window (300 seconds)

If your server clock drifts, all signed requests will be rejected. Synchronize the clock with NTP.

On this page