sign.uts
2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { stringify as qsStringify, StringifyOptions } from "./qs.uts";
import { sha1 } from "./sha1.uts";
/**
* 参数签名方法(完全对齐 gl_tape/api/request/sign.js)
* - 先用 qs.stringify 序列化参数
* - split('&') 拆开后 decodeURIComponent 解码
* - 按 key 字典序排序
* - 拼接为 key + value 字符串,首尾加密钥后做 SHA1,再转大写
* - 最后把 sign 挂到原始参数对象上(保留原始类型)
*
* @param params 原始参数对象(会被修改,添加 sign 字段)
* @param secret 签名密钥
* @param noSignAttr 不参与签名的字段列表
*/
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {
// 1. 用 qs.stringify 序列化(encodeValuesOnly: true)
const options = {
// arrayFormat: 'indices', // UTS qs implementation doesn't support arrayFormat yet, default is indices-like
allowDots: true,
encodeValuesOnly: true
} as StringifyOptions;
const objStr = qsStringify(params, options);
// 2. split('&') 拆开
const objVal = objStr.split("&");
// 3. 解码并重建对象(用于签名计算)
const realObj: UTSJSONObject = {};
for (const item of objVal) {
const idx = item.indexOf("=");
if (idx == -1) {
continue;
}
const key = item.slice(0, Math.max(0, idx));
const val = decodeURIComponent(item.slice(Math.max(0, idx + 1)));
realObj[key] = val;
}
// 4. 获取 key 列表并排序
const sortedKeys: string[] = [];
for (const key in realObj) {
if (key === "sign") {
continue;
}
sortedKeys.push(key);
}
sortedKeys.sort();
// 5. 归一化 value:null -> "",对象 -> JSON 字符串
for (const key of sortedKeys) {
let obj: any | null = realObj[key];
if (obj === null) {
obj = "";
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
// 6. 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = [];
for (const key of sortedKeys) {
if (noSignAttr.indexOf(key) >= 0) {
continue;
}
const val = realObj[key];
segments.push(key + val);
}
// 7. 计算签名:secret + 拼接字符串 + secret
const signSrc = secret + segments.join("") + secret;
const signVal = sha1(signSrc).toUpperCase();
// 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致)
realObj.sign = signVal;
return realObj;
}