MCPcopy Create free account
hub / github.com/Bistutu/FluentRead / getYiyanToken

Function getYiyanToken

userscripts.js:1320–1351  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

1318// req: API Key、Secret Key
1319// resp: access_token,有效期默认 30 天
1320function getYiyanToken() {
1321 return new Promise((resolve, reject) => {
1322 // 1、尝试从 GM 中获取 token,并检测是否有效
1323 let v = tokenManager.getToken(transModel.yiyan)
1324 if (v && v.token && v.ak && v.sk && v.expiration > Date.now()) {
1325 resolve(v.token); // 返回有效的 token
1326 return
1327 }
1328 // 2、发起网络请求
1329 GM_xmlhttpRequest({
1330 method: POST,
1331 url: 'https://aip.baidubce.com/oauth/2.0/token',
1332 data: 'grant_type=client_credentials&client_id=' + v.ak + '&client_secret=' + v.sk,
1333 onload: resp => {
1334 try {
1335 let res = JSON.parse(resp.responseText);
1336 if (res.access_token) {
1337 // 获取有效时间范围,有效期30天(单位秒),需 x1000 转换为毫秒
1338 let expiration = new Date().getTime() + res.expires_in * 1000;
1339 tokenManager.setToken(transModel.yiyan, {
1340 ak: v.ak, sk: v.sk, token: res.access_token, expiration: expiration
1341 });
1342 resolve(res.access_token);
1343 } else reject(new Error(res.error_description));
1344 } catch (e) {
1345 reject(e);
1346 }
1347 },
1348 onerror: error => reject(error)
1349 });
1350 })
1351}
1352
1353// endregion
1354

Callers 1

yiyanFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected