-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestToken.ts
128 lines (116 loc) · 3.47 KB
/
testToken.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import 'dotenv/config';
// import * as qs from 'qs';
import * as crypto from 'crypto';
import { default as axios } from 'axios';
let token = '';
const config = {
/* openapi host */
host: 'https://openapi.tuyacn.com',
/* fetch from openapi platform */
accessKey: process.env.CLIENTID as string,
/* fetch from openapi platform */
secretKey: process.env.CLIENTSECRET as string,
/* Interface example device_ID */
deviceId: process.env.DEVICE_ID as string,
};
const httpClient = axios.create({
baseURL: config.host,
timeout: 5 * 1e3,
});
async function main() {
await getToken();
// const data = await getDeviceInfo(config.deviceId);
// console.log('fetch success: ', JSON.stringify(data));
}
/**
* fetch highway login token
*/
async function getToken() {
const method = 'GET';
const timestamp = Date.now().toString();
const signUrl = '/v1.0/token?grant_type=1';
const contentHash = crypto.createHash('sha256').update('').digest('hex');
const stringToSign = [method, contentHash, '', signUrl].join('\n');
const signStr = config.accessKey + timestamp + stringToSign;
const headers = {
t: timestamp,
sign_method: 'HMAC-SHA256',
client_id: config.accessKey,
sign: await encryptStr(signStr, config.secretKey),
};
const { data: login } = await httpClient.get('/v1.0/token?grant_type=1', {
headers,
});
if (!login || !login.success) {
throw Error(`fetch failed: ${login.msg}`);
}
token = login.result.access_token;
}
/**
* fetch highway business data
*/
// async function getDeviceInfo(deviceId: string) {
// const query = {};
// const method = 'POST';
// const url = `/v1.0/devices/${deviceId}/commands`;
// const reqHeaders: { [k: string]: string } = await getRequestSign(url, method, {}, query);
// const { data } = await httpClient.request({
// method,
// data: {},
// params: {},
// headers: reqHeaders,
// url: reqHeaders.path,
// });
// if (!data || !data.success) {
// throw Error(`request api failed: ${data.msg}`);
// }
// }
/**
* HMAC-SHA256 crypto function
*/
async function encryptStr(str: string, secret: string): Promise<string> {
return crypto
.createHmac('sha256', secret)
.update(str, 'utf8')
.digest('hex')
.toUpperCase();
}
/**
* request sign, save headers
* @param path
* @param method
* @param headers
* @param query
* @param body
*/
// async function getRequestSign(
// path: string,
// method: string,
// headers: { [k: string]: string } = {},
// query: { [k: string]: any } = {},
// body: { [k: string]: any } = {},
// ) {
// const t = Date.now().toString();
// const [uri, pathQuery] = path.split('?');
// const queryMerged = Object.assign(query, qs.parse(pathQuery));
// const sortedQuery: { [k: string]: string } = {};
// Object.keys(queryMerged)
// .sort()
// .forEach((i) => (sortedQuery[i] = query[i]));
// const querystring = decodeURIComponent(qs.stringify(sortedQuery));
// const url = querystring ? `${uri}?${querystring}` : uri;
// const contentHash = crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
// const stringToSign = [method, contentHash, '', url].join('\n');
// const signStr = config.accessKey + token + t + stringToSign;
// return {
// t,
// path: url,
// client_id: config.accessKey,
// sign: await encryptStr(signStr, config.secretKey),
// sign_method: 'HMAC-SHA256',
// access_token: token,
// };
// }
main().catch((err) => {
throw Error(`error: ${err}`);
});