signCore.js
1.1 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
const qs = require("qs");
const md5 = require("md5");
const sha1 = require("sha1");
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* ROP 请求签名(与 src/api/sign.js 逻辑一致)
*/
function sign(params, noSignAttr = [], secret, way = "sha1") {
const payload = { ...params };
delete payload.sign;
const objStr = qs.stringify(deepClone(payload), {
arrayFormat: "indices",
allowDots: true,
encodeValuesOnly: true,
});
const realObj = {};
objStr.split("&").forEach((item) => {
const idx = item.indexOf("=");
realObj[item.slice(0, idx)] = decodeURIComponent(item.slice(idx + 1));
});
const keys = Object.keys(realObj).sort();
const str = [];
for (const key in realObj) {
let obj = realObj[key];
if (obj === null) {
obj = "";
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
keys.forEach((e) => {
if (!noSignAttr.includes(e)) {
str.push(e + realObj[e]);
}
});
const signObj = { sha1, md5 };
realObj.sign = signObj[way](secret + str.join("") + secret).toUpperCase();
return realObj;
}
module.exports = sign;