美文网首页
NodeJs调用微信AccessToken

NodeJs调用微信AccessToken

作者: ruiange | 来源:发表于2020-03-08 13:33 被阅读0次
    const rp = require('request-promise')
    const fs = require('fs')
    const path = require('path')
    const fileName = path.resolve(__dirname, './access_token.json')
    const APPID = '小程序的appid'
    const APPSECRET = '小程序的密钥'
    const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`
    
    const updateAccessToken = async () => {
      const resStr = await rp(URL)//发送请求
      const res = JSON.parse(resStr)
      if (res.access_token) {
        //写入
        fs.writeFileSync(//在当前目录把acesstoken写入json文件
          fileName,
          JSON.stringify({
            access_token: res.access_token,
            createtime: new Date()
          })
        )
      } else {
        await updateAccessToken()
      }
    }
    
    const getAccessToken = async () => {
      try {
        const readRes = fs.readFileSync(fileName, 'utf8')
        const readObj = JSON.parse(readRes)
        const createTime = new Date(readObj.createtime).getTime()
        const nowTime = new Date().getTime()
        if ((nowTime - createTime) / 1000 / 60 / 60 >= 2) {
          await updateAccessToken()
          await getAccessToken()
        }
        return readObj.access_token
      } catch (error) {
        await updateAccessToken()
        await getAccessToken()
      }
    }
    setInterval(async () => {
      await updateAccessToken()
    }, (7200 - 300) * 1000)
    
    module.exports = getAccessToken
    

    相关文章

      网友评论

          本文标题:NodeJs调用微信AccessToken

          本文链接:https://www.haomeiwen.com/subject/qyuddhtx.html