记一下koa实现微信全局access_token定期刷新
# 准备工作
# 实现思路
使用node的request库请求微信接口,将获取的token及设定的有效期存入本地json文件
请求时判断当前时间是否在设定的有效期(这里暂定为1小时)内,有效则返回缓存在json文件的token,无效则重新请求微信接口返回token并写入本地json
# 相关代码
主程序代码
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
const request = require('request')
const fs = require('fs')
let config = require('./config.js')
const tokenUrl = config.tokenUrl,
appid = config.appid,
appsecret = config.appsecret,
router.get('/getToken', async (ctx, next) => {
let tokenInfo = fs.existsSync('token_info.json')
? JSON.parse(fs.readFileSync('token_info.json', 'utf-8'))
: null
let expires_time = tokenInfo ? tokenInfo.expires_time : ''
let cache_access_token =
tokenInfo && tokenInfo.access_token ? tokenInfo.access_token : ''
if (
parseInt(Date.now() / 1000) > expires_time + 3600 ||
tokenInfo == null ||
cache_access_token == ''
) {
let tokenInfoNew = await new Promise(function (resolve, reject) {
request.get(
`${tokenUrl}?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,
function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body)
}
reject(error)
}
)
})
tokenInfoNew = JSON.parse(tokenInfoNew)
cache_access_token = tokenInfoNew.access_token
expires_time = parseInt(Date.now() / 1000)
fs.writeFileSync(
'token_info.json',
JSON.stringify({
access_token: cache_access_token,
expires_time: expires_time,
})
)
ctx.data = { token: cache_access_token, expires_time: expires_time }
} else {
ctx.data = tokenInfo
}
await next()
})
# 依赖接口
微信全局access_token接口
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET