**
**
const rp = require(‘request-promise’)
const APPID = ‘wxac3efb6ed3c63dd0’
const APPSECRET =’*****‘
const URL=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}
const fs= require(‘fs’)
const path = require(‘path’)
const fileName=path.resolve(__dirname,’./access_token.json’)
const updateAccessToken = async () => {
const resStr = await rp(URL)
const res =JSON.parse(resStr)
console.log(res)
//写文件
if (res.access_token) {
fs.writeFileSync(fileName,JSON.stringify({
access_token: res.access_token,
createTime:new Date()
}))
} else {
await updateAccessToken()
}
}
const getAccessToken = async () => {
try {
const readRes = fs.readFileSync(fileName, ‘utf-8’)
const readObj = JSON.parse(readRes).access_token
const createTime = new Date(readObj.createTime).getTime()
const nowTime =new Date().getTime()
if ((nowTime-createTime)/1000/60/60>=2) {
await updateAccessToken()
return await getAccessToken()
}
return readObj.access_token
} catch (error) {
await updateAccessToken()
return await getAccessToken()
}
}
setInterval(async() => {
await updateAccessToken()
}, (7200-300)*1000);
module.exports =getAccessToken
{“access_token”:“44_EQpW9d6eTiQyNMOE1hZB-sjkgku3equVYvPilRfrwkDB0SqwExikyhVJtraESrBTBsBh4XNm-6AHNsTZqZ0BsKXAZjT24ZMvrSjcq-Hx-l34EWJzadKnNvYslJeHd_6mgQRUQ6FcaSqDKHCXXQTdABATMP”,“createTime”:“2021-05-04T17:52:43.967Z”}
图片描述