| 1427 | |
| 1428 | |
| 1429 | function generateToken(apiKey) { |
| 1430 | |
| 1431 | if (!apiKey || !apiKey.includes('.')) { |
| 1432 | console.log("API Key 格式错误:", apiKey) |
| 1433 | return; |
| 1434 | } |
| 1435 | let duration = 3600000 * 24; // 生成的 token 默认24小时后过期 |
| 1436 | |
| 1437 | const [key, secret] = apiKey.split('.'); |
| 1438 | let token = generateJWT(secret, {alg: "HS256", sign_type: "SIGN", typ: "JWT"}, { |
| 1439 | api_key: key, |
| 1440 | exp: Math.floor(Date.now() / 1000) + (duration / 1000), |
| 1441 | timestamp: Math.floor(Date.now() / 1000) |
| 1442 | }); |
| 1443 | if (!token) return // 失败则提前返回 |
| 1444 | // 存储 |
| 1445 | tokenManager.setToken(transModel.zhipu, {apikey: apiKey, token: token, expiration: Date.now() + duration}); |
| 1446 | |
| 1447 | return token; |
| 1448 | } |
| 1449 | |
| 1450 | // 生成JWT(JSON Web Token) |
| 1451 | function generateJWT(secret, header, payload) { |