首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >koa框架实现的刷新微信全局access_token服务

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

作者头像
薛定喵君
发布2020-05-28 09:14:50
发布2020-05-28 09:14:50
1.1K0
举报
文章被收录于专栏:薛定喵君薛定喵君

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

  • 准备工作
  • 实现思路
  • 相关代码
  • 依赖接口

# 准备工作

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

# 实现思路

使用node的request库请求微信接口,将获取的token及设定的有效期存入本地json文件 请求时判断当前时间是否在设定的有效期(这里暂定为1小时)内,有效则返回缓存在json文件的token,无效则重新请求微信接口返回token并写入本地json

# 相关代码

主程序代码

代码语言:javascript
复制
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接口

代码语言:javascript
复制
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/05/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # 准备工作
  • # 实现思路
  • # 相关代码
  • # 依赖接口
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档