使用 nodeJs 开发微信公众号(获取access_token)

使用微信提供的功能接口,就需要获取到access_token,这是开发公众号必不可少的一部

access_token有效期20分钟,建议保存起来,过期后在重新获取

获取流程如下:

我将微信相关的操作封装在 lib/wechat.js 中,同时在同级目录下新建 token.txt 用于保存获取到的access_token

const wxConfig = require(\'../config/wx.js\') const fs = require(\'fs\') const path = require(\'path\') const sha1 = require(\'sha1\') const request = require(\'request\') function Wechat(){ this.appId = wxConfig.appId, this.appSecret = wxConfig.appSecret, this.token = wxConfig.token } //校验请求是否来自微信 Wechat.prototype.init = function(req, res, next) { var token = wxConfig.token var signature = req.query.signature var nonce = req.query.nonce var timestamp = req.query.timestamp var echostr = req.query.echostr var str = [token, timestamp, nonce].sort().join(\'\') var sha = sha1(str) if (sha === signature) { next() }else{ res.send(\'error\') } }; //获取access_token Wechat.prototype.getAccessToken = function(){ var data = fs.readFileSync(path.resolve(__dirname, \'./token.txt\')) try{ accessToken = JSON.parse(data) if(accessToken.expires_in > Date.parse(new Date())){ return Promise.resolve(accessToken.access_token) }else{ //已过期 return this.updateAccessToken() } } catch(err){ //文件为空 return this.updateAccessToken() } } //从微信重新拉取access_token Wechat.prototype.updateAccessToken = function(){ const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appId}&secret=${this.appSecret}` // 返回accesstoken格式如下 // { // "access_token":"string", // "expires_in":7200 // } return new Promise((resolve, reject) => { request(url, function(err, response, body){ var accessToken = JSON.parse(response.body) accessToken[\'expires_in\'] = Date.parse(new Date())+((7200 - 20)*1000) fs.writeFileSync(path.resolve(__dirname, \'./token.txt\') , JSON.stringify(accessToken)) resolve(accessToken.access_token) }) }) } module.exports = new Wechat()

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zggwxw.html