getPrivateKey.js
2.57 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
83
84
85
86
87
88
89
90
91
92
import config from '../../config'
import udid from './utils/udid.js'
const ClientInitConfigMethod = "resources.simple.pice"
const getPrivateKey = () => {
return new Promise((resolve, reject) => {
let app = getApp();
let globalData;
// 获取 App 中的全局变量
if (app && app.globalData) {
// 原生小程序的 globalData 获取方式
globalData = app && app.globalData;
} else {
// Taro 下 globalData 获取方式
globalData = app && app.props && app.props.globalData;
}
// 获取 p2SecretKey
let p2SecretKey = globalData && globalData.p2SecretKey;
// 如果未取到 p2SecretKey
if (!p2SecretKey) {
// 本地获取
p2SecretKey = getYHStorageSync('p2SecretKey', 'request');
}
if (!p2SecretKey) {
p2SecretKey = getYHStorageSync('verifyKey', 'request');
}
if (p2SecretKey) {
// 存在,直接返回
resolve(p2SecretKey);
} else {
// 不存在,请求数据
const data = {
"udid": udid.get(),
"method": ClientInitConfigMethod
};
const method = "GET";
const header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
wx.request({
url: config.domains.yohoApi,
data,
method,
header,
success: (res) => {
let data = res && res.data
if (data && data.data && data.data.sk) {
// 存在,获取,存储并返回
p2SecretKey = data.data.sk;
if (globalData) {
globalData.p2SecretKey = p2SecretKey;
}
wx.setStorageSync("p2SecretKey", p2SecretKey);
wx.setStorageSync("verifyKey", p2SecretKey);
resolve(p2SecretKey);
} else {
let err = new Error();
let code = err.code ? err.code : 800;
let message = err.message ? err.message : '';
let isPrivatekeyError = true
reject({ code, message, isPrivatekeyError });
}
},
fail: (err) => {
let code = err.code ? err.code : 800;
let message = err.message ? err.message : '';
let isPrivatekeyError = true
reject({ code, message, isPrivatekeyError });
}
})
}
});
}
const getYHStorageSync = (key, fromPage) => {
try {
let res = wx.getStorageSync(key);
return res;
} catch (e) {
wx.reportAnalytics('ufo_get_storage_error', {
key: key,
error: e.message,
error_code: e.code,
from_page: fromPage,
});
return null;
}
}
export default getPrivateKey;