-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (61 loc) · 1.75 KB
/
index.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
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
const crypto = require('crypto');
const fs = require('fs');
const objKeySort = (obj) => {
var newKey = Object.keys(obj).sort()
var newObj = {}
for (var i = 0; i < newKey.length; i++) {
newObj[newKey[i]] = obj[newKey[i]]
}
return newObj
};
const createSign = ({
timestamp,
appSecret,
urlPath,
queryParam
}) => {
const param = {timestamp};
for (const item of queryParam) {
param[item.name] = item.value;
}
delete param["sign"];
delete param["access_token"]
const sortedObj = objKeySort(param)
var signstring = appSecret + urlPath
for (var key in sortedObj) {
signstring = signstring + key + sortedObj[key]
}
signstring = signstring + appSecret
return crypto.createHmac('sha256', appSecret).update(signstring).digest('hex');
}
const getTimestamp = () => {
return Date.parse(new Date()) / 1000
}
const encodeRequest = (context) => {
const url = context.request.getUrl();
const timestamp = getTimestamp();
const queryParam = context.request.getParameters();
const appSecret = context.request.getEnvironmentVariable('app_secret');
const urlPath = new URL(url).pathname
const sign = createSign({
timestamp,
appSecret,
queryParam,
urlPath
});
return {
sign,
timestamp,
};
}
module.exports.requestHooks = [
(context) => {
if(context.request.hasHeader('x-tts-sign') && context.request.getHeader('x-tts-sign') == 'true')
{
const {sign, timestamp} = encodeRequest(context);
context.request.addParameter('sign', sign);
context.request.addParameter('timestamp', timestamp);
context.request.removeHeader('x-tts-sign');
}
}
];