优化签名排序逻辑

This commit is contained in:
yml2213
2026-07-20 16:34:23 +08:00
parent e4d0a71963
commit ee78b80cd3
3 changed files with 108 additions and 54 deletions
+21 -9
View File
@@ -12,10 +12,22 @@ API_KEY = "sk_source_dev_key_change_me"
API_SECRET = "sk_source_dev_secret_change_me"
BASE = "${baseUrl}"
def build_sign_string(api_key, timestamp, nonce, method, path, body=""):
params = {
"api_key": api_key,
"body": body,
"method": method.upper(),
"nonce": nonce,
"path": path,
"timestamp": timestamp,
}
# 字典序 + & 拼接,value 不 URL encode
return "&".join(f"{k}={params[k]}" for k in sorted(params.keys()))
def sign_headers(method: str, path: str, body: str = "") -> dict:
ts = str(int(time.time()))
nonce = uuid.uuid4().hex
raw = "\\n".join([API_KEY, ts, nonce, method.upper(), path, body])
raw = build_sign_string(API_KEY, ts, nonce, method, path, body)
sign = hmac.new(API_SECRET.encode(), raw.encode(), hashlib.sha256).hexdigest()
return {
"X-Api-Key": API_KEY,
@@ -79,15 +91,15 @@ export default function OpenApiDocs() {
label: '签名规则',
children: (
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<Card size="small" title="待签名字符串(6 行,\\n 分隔">
<pre style={preStyle}>{`{api_key}
{timestamp}
{nonce}
{METHOD}
{path}
{body}`}</pre>
<Card size="small" title="待签名字符串(字典序 + & 拼接">
<Paragraph type="secondary" style={{ marginBottom: 8 }}>
api_key / body / method / nonce / path / timestamp key
k=v&k=vvalue <Text strong></Text> URL encode
</Paragraph>
<pre style={preStyle}>{`api_key=sk_xxx&body=&method=GET&nonce=a1b2c3d4e5f67890&path=/api/open/v1/orders/O123&timestamp=1721450000`}</pre>
<pre style={{ ...preStyle, marginTop: 8 }}>{`api_key=sk_xxx&body={"order_no":"O123","ship_status":"success"}&method=POST&nonce=...&path=/api/open/v1/orders/ship-notify&timestamp=1721450000`}</pre>
<Descriptions size="small" column={1} bordered style={{ marginTop: 12 }}>
<Descriptions.Item label="METHOD"> GET / POST</Descriptions.Item>
<Descriptions.Item label="method"> GET / POST</Descriptions.Item>
<Descriptions.Item label="path">
URL.Path query /api/open/v1/orders/O123
</Descriptions.Item>