要使用微信提供的功能接口,就須要獲取到access_token,這是開發公衆號必不可少的一部api
access_token有效期20分鐘,建議保存起來,過時後在從新獲取微信
獲取流程以下:app
我將微信相關的操做封裝在 lib/wechat.js 中,同時在同級目錄下新建 token.txt 用於保存獲取到的access_tokenui
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()
在app.js中調用wechat.js下的 getAccessToken 方法獲取,而後保存在全局對象中,這樣其餘文件中能夠直接調用this
var wechat = require('./lib/wechat'); wechat.getAccessToken().then(token => { global.accessToken = token }) //校驗請求 app.use(wechat.init);