""" 优时开放平台 · 回调验签示例(Python 3.7+,仅标准库) 签名串:METHOD + "\n" + path + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256_hex(body) 签名: lower_hex(HMAC-SHA256(sign_key, 签名串)),与请求头 X-Sign 比较(常量时间) path 是你的回调地址的路径部分,不含域名和查询参数,例如 /notify 处理建议:验签失败返回 401;按 event_id 去重;处理成功后 5 秒内返回 HTTP 200,响应体为 success。 """ import hashlib import hmac import sys import time def yours_open_verify(sign_key: str, method: str, path: str, timestamp: str, nonce: str, body: bytes, signature: str, now: int = None) -> bool: now = int(time.time()) if now is None else now if not timestamp.isdigit() or abs(now - int(timestamp)) > 300: return False # 时间戳超出 ±5 分钟 string_to_sign = "\n".join([method.upper(), path, timestamp, nonce, hashlib.sha256(body).hexdigest()]) expected = hmac.new(sign_key.encode(), string_to_sign.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(expected.encode(), signature.lower().encode()) # 命令行自检:python3 verify.py if __name__ == "__main__": key, path, ts, nonce, sign, body_file = sys.argv[1:7] with open(body_file, "rb") as f: sys.exit(0 if yours_open_verify(key, "POST", path, ts, nonce, f.read(), sign) else 1)