主题
快速跑通流程
这篇文档给出一套最短接入流程:
先拿初始签名,再在到期前换新,并把最新签名统一写入全局变量,供所有接口调用复用。
1. 初始化全局状态
应用启动时,维护两项全局状态:
currentToken:当前可用签名expireAt:当前签名过期时间戳
2. 首次获取签名
当 currentToken 为空时,请求:
POST /api/auth/token
使用 clientId + clientSecret 交换首个 accessToken,并写入:
currentToken = accessTokenexpireAt = now + expiresInSeconds
3. 统一提供取签名方法
业务请求不直接读写签名,统一走一个方法(例如 getApiKey()):
- 如果当前签名为空或已过期,先执行“首次获取签名”
- 如果签名还有效,直接返回当前签名
这样可以保证全软件始终从同一位置读取签名值。
4. 到期前自动换新
当剩余有效期进入 5 分钟窗口时,请求:
POST /api/auth/token/refresh
成功后,覆盖全局状态:
currentToken = newAccessTokenexpireAt = now + newExpiresInSeconds
如果刷新失败,则可重新调用 /api/auth/token 获取新签名并覆盖全局状态。
5. 业务调用统一使用全局签名
调用代理接口时,统一从 getApiKey() 取签名并写入请求头:
X-Api-Key: <currentToken>
验证请求路径示例:
GET /api/proxy/base/hello-world
验证成功后可得到类似响应:
json
{
"success": true,
"message": "helloworld",
"verify": "request_normal",
"requestId": "6ff8d966-b3f6-46a6-9fe3-24fd6553ef52"
}6. 最小伪代码
js
let currentToken = "";
let expireAt = 0;
async function exchangeToken() {
const res = await post("/api/auth/token", { clientId, clientSecret });
currentToken = res.accessToken;
expireAt = now() + res.expiresInSeconds;
}
async function refreshToken() {
const res = await post("/api/auth/token/refresh", null, {
Authorization: `Bearer ${currentToken}`,
});
currentToken = res.accessToken;
expireAt = now() + res.expiresInSeconds;
}
async function getApiKey() {
if (!currentToken || now() >= expireAt) {
await exchangeToken();
return currentToken;
}
if (expireAt - now() <= 300) {
try {
await refreshToken();
} catch {
await exchangeToken();
}
}
return currentToken;
}