-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
37 lines (30 loc) · 1.04 KB
/
utils.js
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
const crypto = require('crypto');
/**
* 获取签名
* @param {string} apiUrl - 要请求的接口地址(相对网站域名的相对路径)
* @param {Object} data - 请求参数(不包含 signature)
* @return string - 加密后的签名串
*/
module.exports.getSignature = function(apiUrl, data) {
const obj = {}
// 1 将请求参数按key值从小到大排序
Object.keys(data).sort().forEach(key => {
if (key !== 'signature')
obj[key] = data[key]
})
// 2 将排序后的keyvalue拼接起来
const keyvalue = Object.entries(obj).map(([key, value]) => key + value).join('')
// 3 将上面得到的字符串前面再拼接API的URL
const parameterStr = apiUrl + keyvalue
// 4, 将拼接好的字符串用 UTF-8 编码后做 HMAC-SHA256摘要
let result = crypto.createHmac('sha256', this.token)
.update(parameterStr, 'utf8')
// 5, 将得到的摘要做 HEXDECIMAL 编码, 得到签名值
.digest('hex')
.toUpperCase()
console.log({
parameterStr,
result
});
return result
}