所有商户 API 请求都必须携带四个头。签名原文按行拼接,顺序不可变:

payload = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + path + "\n" + raw_body
signature = hex( HMAC_SHA256(app_secret, payload) )
  • timestamp:Unix 秒。偏差超过 5 分钟拒绝。
  • nonce:每次请求唯一。服务端滑动窗口去重,重复即拒绝(防重放)。
  • path:包含查询串的路径,例如 /api/v1/orders?limit=20。
  • raw_body:原始请求体字符串(GET 为空串)。不要重新序列化后再签名。
// Node.js
import { createHmac, randomUUID } from 'node:crypto';

function signedFetch(path, body) {
  const ts = Math.floor(Date.now() / 1000);
  const nonce = randomUUID();
  const raw = body ? JSON.stringify(body) : '';
  const sig = createHmac('sha256', process.env.GAAPAY_SECRET)
    .update([ts, nonce, body ? 'POST' : 'GET', path, raw].join('\n'))
    .digest('hex');
  return fetch(`https://api.gaapay.com${path}`, {
    method: body ? 'POST' : 'GET',
    headers: {
      'content-type': 'application/json',
      'x-gaapay-app': process.env.GAAPAY_APP,
      'x-gaapay-timestamp': String(ts),
      'x-gaapay-nonce': nonce,
      'x-gaapay-signature': sig,
    },
    body: raw || undefined,
  });
}
# Python
import hmac, hashlib, time, uuid, json

def sign(method, path, body: str, secret: str):
    ts, nonce = str(int(time.time())), str(uuid.uuid4())
    payload = f"{ts}\n{nonce}\n{method}\n{path}\n{body}"
    sig = hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"x-gaapay-timestamp": ts, "x-gaapay-nonce": nonce, "x-gaapay-signature": sig}
<?php
$ts = time(); $nonce = bin2hex(random_bytes(8)); $raw = json_encode($body);
$payload = $ts."\n".$nonce."\nPOST\n".$path."\n".$raw;
$sig = hash_hmac('sha256', $payload, $secret);
// headers: x-gaapay-app / x-gaapay-timestamp / x-gaapay-nonce / x-gaapay-signature