?
記一下koa實(shí)現(xiàn)微信全局access_token定期刷新
?
準(zhǔn)備工作
服務(wù)器IP添加至微信公眾號(hào)的IP白名單
實(shí)現(xiàn)思路
使用node的request庫(kù)請(qǐng)求微信接口,將獲取的token及設(shè)定的有效期存入本地json文件
請(qǐng)求時(shí)判斷當(dāng)前時(shí)間是否在設(shè)定的有效期(這里暫定為1小時(shí))內(nèi),有效則返回緩存在json文件的token,無(wú)效則重新請(qǐng)求微信接口返回token并寫(xiě)入本地json
相關(guān)代碼
主程序代碼
-
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()
-
})
依賴(lài)接口
微信全局access_token接口
-
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
?
?
?
?
?
本文摘自 :https://blog.51cto.com/x