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
网友评论