请求签名
每个请求携带四个头:
| 头 | 说明 |
|---|---|
X-App-Id | App 编号(app_no),由平台分配 |
X-Timestamp | 当前 Unix 时间戳(秒)。与服务器相差超过 300 秒 拒绝 |
X-Nonce | 随机串,16–64 位,字符集 [A-Za-z0-9_-]。同一 App 下 15 分钟内不得重复 |
X-Signature | 签名,小写十六进制 |
算法
body_hash = hex( SHA256( 请求体原始字节 ) )
string_to_sign = METHOD + "\n" + PATH + "\n" + TIMESTAMP + "\n" + NONCE + "\n" + body_hash
signature = hex( HMAC-SHA256( app_secret, string_to_sign ) )METHOD固定POST;PATH为不含域名和 query 的路径,如/api/v1/payout/create。- 对发送的原始字节做哈希:先把请求对象序列化成字节串,对这份字节算
body_hash,再把同一份字节原样放进 HTTP body。不要序列化两次,不要让 HTTP 库改写 body(漂亮打印、重新排序字段、添加 BOM、gzip 都会导致验签失败)。嵌套 JSON、字段顺序、空格本身都不影响,因为服务端不做任何规范化,只看字节。 - 来源 IP 需在平台为该商户配置的白名单内(未配置则不限制);白名单在验签之前检查,命中失败返回
403 IP_NOT_ALLOWED。
验签失败一律 401 INVALID_SIGNATURE,不区分是时间戳、nonce 还是签名的问题。
测试向量
app_secret = sk_test_secret
method = POST
path = /api/v1/payout/create
timestamp = 1760400000
nonce = n0nce-n0nce-n0nce
body = {"reference_id":"ORD-1","amount":"50.00","currency":"BRL","payment_method":"PIX"}正确的中间结果与签名:
body_hash = b008e59b28ec5580d090a9b4c8f4523085172e060234041a810c866356ba1d63
signature = 39fc969d9678d0dba928c7a2a241e1082b431ed8e54b53232ba1621b4c170a0dbody_hash 不一致 → 检查你哈希的字节是否就是 body 本身(常见问题:多了换行、用了不同的 JSON 序列化);body_hash 一致但 signature 不一致 → 检查五段的拼接顺序与 \n 分隔、METHOD 大写、PATH 不含域名。
示例
go
func sign(secret, method, path, ts, nonce string, body []byte) string {
sum := sha256.Sum256(body)
s := strings.Join([]string{strings.ToUpper(method), path, ts, nonce, hex.EncodeToString(sum[:])}, "\n")
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(s))
return hex.EncodeToString(mac.Sum(nil))
}python
import hashlib, hmac, json, time, secrets, requests
def sign(secret, method, path, ts, nonce, body: bytes) -> str:
body_hash = hashlib.sha256(body).hexdigest()
s = "\n".join([method.upper(), path, ts, nonce, body_hash])
return hmac.new(secret.encode(), s.encode(), hashlib.sha256).hexdigest()
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8") # 只序列化一次
ts, nonce = str(int(time.time())), secrets.token_hex(16)
headers = {
"Content-Type": "application/json; charset=utf-8",
"X-App-Id": APP_ID, "X-Timestamp": ts, "X-Nonce": nonce,
"X-Signature": sign(APP_SECRET, "POST", "/api/v1/payout/create", ts, nonce, body),
}
r = requests.post(BASE + "/api/v1/payout/create", data=body, headers=headers) # data= 发送原始字节js
const crypto = require('crypto');
function sign(secret, method, path, ts, nonce, body /* Buffer */) {
const bodyHash = crypto.createHash('sha256').update(body).digest('hex');
const sts = [method.toUpperCase(), path, ts, nonce, bodyHash].join('\n');
return crypto.createHmac('sha256', secret).update(sts).digest('hex');
}
const body = Buffer.from(JSON.stringify(payload), 'utf8'); // 只序列化一次
const ts = String(Math.floor(Date.now() / 1000));
const nonce = crypto.randomBytes(16).toString('hex');
await fetch(BASE + '/api/v1/payout/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'X-App-Id': APP_ID, 'X-Timestamp': ts, 'X-Nonce': nonce,
'X-Signature': sign(APP_SECRET, 'POST', '/api/v1/payout/create', ts, nonce, body),
},
body, // 发送同一份字节
});php
function sign(string $secret, string $method, string $path, string $ts, string $nonce, string $body): string {
$sts = implode("\n", [strtoupper($method), $path, $ts, $nonce, hash('sha256', $body)]);
return hash_hmac('sha256', $sts, $secret);
}
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); // 只序列化一次
$ts = (string) time();
$nonce = bin2hex(random_bytes(16));
$headers = [
'Content-Type: application/json; charset=utf-8',
'X-App-Id: ' . $APP_ID, 'X-Timestamp: ' . $ts, 'X-Nonce: ' . $nonce,
'X-Signature: ' . sign($APP_SECRET, 'POST', '/api/v1/payout/create', $ts, $nonce, $body),
];
// curl: CURLOPT_POSTFIELDS => $body(字符串,原样发送)java
static String sign(String secret, String method, String path, String ts, String nonce, byte[] body) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
String bodyHash = HexFormat.of().formatHex(sha.digest(body));
String sts = String.join("\n", method.toUpperCase(), path, ts, nonce, bodyHash);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return HexFormat.of().formatHex(mac.doFinal(sts.getBytes(StandardCharsets.UTF_8)));
}
// byte[] body = objectMapper.writeValueAsBytes(payload); 只序列化一次,
// HttpRequest.BodyPublishers.ofByteArray(body) 发送同一份字节常见错误
| 现象 | 原因 |
|---|---|
| 本地测试向量都对,线上 401 | 服务器时钟漂移超过 300 秒;或 nonce 重复(重试时复用了 nonce) |
| 偶发 401 | HTTP 客户端在发送前改写了 body(如 Axios 对对象再次序列化、框架自动添加字段) |
| 总是 401 | PATH 带了域名或 query;METHOD 小写;\n 写成了 \r\n |
| 403 | 来源 IP 不在白名单,或 App / 商户被停用 |