})
})
}
至此,后端配置好了,我们已经能够正常使用微信的接口了,但是微信每日接口请求是有上限的,通过2000次/天,因此如果网站上线后,一量当天访问量超过2000次你的接口将失效,而且每次都请求微信接口两次,造成请求时间浪费,所以我们需要将以上获取信息缓存在后端,避免造成接口失效以及多次请求微信后台。
缓存access_token及jsapi_ticket
此处直接上代码,利用node_cache包进行缓存
const request = require('request')
const express = require('express')
const app = express()
const sha1 = require('sha1')
const waterfall = require('async/waterfall')
const NodeCache = require('node-cache')
const cache = new NodeCache({stdTTL: 3600, checkperiod: 3600}) //3600秒后过过期app.get('/wxJssdk', (req, res) => {
let wx = req.query
// 1)将token、timestamp、nonce三个参数进行字典序排序
let token = 'jegfjaeghfuyawegfgjdbh'
let timestamp = wx.timestamp
let nonce = wx.nonce
// 2)将三个参数字符串拼接成一个字符串进行sha1加密
let list = [token, timestamp, nonce] let result = sha1(list.sort().join(''))
// 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
if (result === wx.signature) {
res.send(wx.echostr)
} else {
res.send(false)
}
})
app.get('/wxJssdk/getJssdk', (req, res) => {
let grant_type = 'client_credential'
let appid = 'your app id'
let secret = 'your app secret' // appscret
let steps = []
// 第一步,获取access_token
steps.push((cb) => {
let steps1 = []
// 第1.1步,从缓存中读取access_token
steps1.push((cb1) => {
let access_token = cache.get('access_token', (err, access_token) => {
cb1(err, access_token)
})
})
// 第1.2步,缓存中有access_token则直接返回,如果没有,则从服务器中读取access_token
steps1.push((access_token, cb1) => {
if (access_token) {
cb1(null, access_token, 'from_cache')
} else {
request('https://api.weixin.qq.com/cgi-bin/token?grant_type=' + grant_type + '&appid=' + appid + '&secret=' + secret, (err, response, body) => {
cb1(err, JSON.parse(body).access_token, 'from_server')
})
}
})
// 第1.3步,如果是新从服务器取的access_token,则缓存起来,否则直接返回
steps1.push((access_token, from_where, cb1) => {
if (from_where === 'from_cache') {
console.log(' === 成功从缓存中读取access_token: ' + access_token + ' ===')
cb1(null, access_token)
} else if (from_where === 'from_server') {
cache.set('access_token', access_token, (err, success) => {









