egg框架很强大,上周末突发奇想,用来做为微信公众号后台怎么样?想到就开干。微信
首先,要开发必需要先配置好才行,这里先讲一下怎么配。cookie
1 // config/config.default.js 2 'use strict'; 3 4 module.exports = appInfo => { 5 const config = exports = {}; 6 7 // use for cookie sign key, should change to your own and keep security 8 config.keys = appInfo.name + '_1511005864199_129'; 9 10 // add your config here 11 config.wechat_config = { 12 token: 'XXXXXX', 13 appid: 'XXXXXXX', 14 encodingAESKey: 'XXXXXX' 15 }; 16 return config; 17 }; 18 19 // controller/home.js 20 'use strict'; 21 const Controller = require('egg').Controller; 22 var sha1 = require('sha1') 23 class HomeController extends Controller { 24 async index() { 25 var obj = this.ctx.query 26 var token = this.ctx.app.config.wechat_config.token, 27 timestamp = obj.timestamp, 28 nonce = obj.nonce, 29 echostr = obj.echostr, 30 signature = obj.signature, 31 str = [token, timestamp, nonce].sort().join(''), 32 sha = sha1(str); 33 if(sha === signature){ 34 this.ctx.body = echostr + '' 35 } 36 } 37 } 38 39 module.exports = HomeController;
这些代码都是基于egg脚手架搭建出来,其中须要安装一个依赖,sha1,用来加密的,其余东西就不用装了,照着代码来就行了。app
注:十二、1三、14行的参数填写你本身的,能够在微信公众号后台登陆进去查看到。框架