/** * 优时开放平台 · 回调验签示例(Node.js 14+,仅内置模块) * * 签名串:METHOD + "\n" + path + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256_hex(body) * 签名: lower_hex(HMAC-SHA256(sign_key, 签名串)),与请求头 X-Sign 比较(常量时间) * path 是你的回调地址的路径部分,不含域名和查询参数,例如 /notify * body 必须使用原始请求体字节(不要先 JSON.parse 再 JSON.stringify) * * 处理建议:验签失败返回 401;按 event_id 去重;处理成功后 5 秒内返回 HTTP 200,响应体为 success。 */ const crypto = require('crypto'); function yoursOpenVerify(signKey, method, path, timestamp, nonce, body, signature, now = Math.floor(Date.now() / 1000)) { if (!/^\d+$/.test(timestamp) || Math.abs(now - Number(timestamp)) > 300) { return false; // 时间戳超出 ±5 分钟 } const bodyHash = crypto.createHash('sha256').update(body).digest('hex'); const stringToSign = [method.toUpperCase(), path, timestamp, nonce, bodyHash].join('\n'); const expected = crypto.createHmac('sha256', signKey).update(stringToSign).digest('hex'); const given = Buffer.from(String(signature).toLowerCase(), 'utf8'); const wanted = Buffer.from(expected, 'utf8'); return given.length === wanted.length && crypto.timingSafeEqual(wanted, given); } module.exports = { yoursOpenVerify }; // 命令行自检:node verify.js if (require.main === module) { const [key, path, ts, nonce, sign, bodyFile] = process.argv.slice(2); const body = require('fs').readFileSync(bodyFile); process.exit(yoursOpenVerify(key, 'POST', path, ts, nonce, body, sign) ? 0 : 1); }