當前位置:首頁 > IT技術 > 微信平臺 > 正文

koa框架實現的刷新微信全局access_token服務
2021-07-25 18:57:02

?

記一下koa實現微信全局access_token定期刷新

?

準備工作

服務器IP添加至微信公眾號的IP白名單

koa框架實現的刷新微信全局access_token服務_學習

實現思路

使用node的request庫請求微信接口,將獲取的token及設定的有效期存入本地json文件
請求時判斷當前時間是否在設定的有效期(這里暫定為1小時)內,有效則返回緩存在json文件的token,無效則重新請求微信接口返回token并寫入本地json

相關代碼

主程序代碼

  1. const Koa = require('koa')

  2. const app = new Koa()

  3. const Router = require('koa-router')

  4. const router = new Router()

  5. const request = require('request')

  6. const fs = require('fs')

  7. let config = require('./config.js')

  8. const tokenUrl = config.tokenUrl,

  9. appid = config.appid,

  10. appsecret = config.appsecret,

  11. ?

  12. router.get('/getToken', async (ctx, next) => {

  13. let tokenInfo = fs.existsSync('token_info.json')

  14. ? JSON.parse(fs.readFileSync('token_info.json', 'utf-8'))

  15. : null

  16. let expires_time = tokenInfo ? tokenInfo.expires_time : ''

  17. let cache_access_token =

  18. tokenInfo && tokenInfo.access_token ? tokenInfo.access_token : ''

  19. if (

  20. parseInt(Date.now() / 1000) > expires_time + 3600 ||

  21. tokenInfo == null ||

  22. cache_access_token == ''

  23. ) {

  24. let tokenInfoNew = await new Promise(function (resolve, reject) {

  25. request.get(

  26. `${tokenUrl}?grant_type=client_credential&appid=${appid}&secret=${appsecret}`,

  27. function (error, response, body) {

  28. if (!error && response.statusCode == 200) {

  29. resolve(body)

  30. }

  31. reject(error)

  32. }

  33. )

  34. })

  35. tokenInfoNew = JSON.parse(tokenInfoNew)

  36. cache_access_token = tokenInfoNew.access_token

  37. expires_time = parseInt(Date.now() / 1000)

  38. fs.writeFileSync(

  39. 'token_info.json',

  40. JSON.stringify({

  41. access_token: cache_access_token,

  42. expires_time: expires_time,

  43. })

  44. )

  45. ctx.data = { token: cache_access_token, expires_time: expires_time }

  46. } else {

  47. ctx.data = tokenInfo

  48. }

  49. await next()

  50. })

依賴接口

微信全局access_token接口

  1. https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

?

?

?

?

koa框架實現的刷新微信全局access_token服務_學習_02

?

本文摘自 :https://blog.51cto.com/x

開通會員,享受整站包年服務立即開通 >