koa框架实现的刷新微信全局access_token服务

2020-05-27 18:10:26

记一下koa实现微信全局access_token定期刷新

准备工作

服务器IP添加至微信公众号的IP白名单

实现思路

使用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
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~