新建项目
$ npm i egg-init -g
$ egg-init wechat_public_number_demo --type=simple
$ cd wechat_public_number_demo
$ npm i
$ npm run dev
$ open localhost:7001
接入公众号
由于配置的URL必须要域名,为了实现本地开发,本人采用Sunny-Ngrok进行端口映射,具体用法请自行百度。
**注意:**端口若不为80,则无法配置成功。
config/config.default.js
config.wechat_config = {
token: 'wechat_public_number_demo',
};
router.js
router.get('/wechat', controller.home.fromWechat);
controller/home.js
const crypto = require('crypto');
async fromWechat() {
const token = this.ctx.app.config.wechat_config.token;
const query = this.ctx.query;
const timestamp = query.timestamp;
const nonce = query.nonce;
const signature = query.signature;
const echostr = query.echostr;
const str = [ token, timestamp, nonce ].sort().join('');
const hash = crypto.createHash('sha1');
hash.update(str);
const sha = hash.digest('hex');
if (sha === signature) {
this.ctx.body = echostr;
}
}
package.json
"dev": "egg-bin dev --port=80",
获取access_token
config/config.default.js
appId: 'wx230f799414023398',
appSecret: '27118b180d47a9b11c094a03cea63a74',
getAccessTokenUrl: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET',
schedule/access_token.js
'use strict';
const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
static get schedule() {
return {
interval: '2h',
type: 'all',
};
}
async subscribe() {
const config = this.ctx.app.config.wechat_config;
const url = config.getAccessTokenUrl.replace('APPID', config.appId).replace('APPSECRET', config.appSecret);
const res = await this.ctx.curl(url, {
dataType: 'json',
});
console.log(res.data.access_token);
this.ctx.app.access_token = res.data.access_token;
}
}
module.exports = UpdateCache;
app.js
'use strict';
module.exports = app => {
app.beforeStart(async () => {
await app.runSchedule('access_token');
});
};
自定义菜单
由于egg内置了安全插件,请求会报错,暂时的解决方案是关闭csrf检查。
config.default.js
postCreateMenuUrl: 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN',
config.security = {
csrf: {
enable: false,
},
};
app.js
const menu