egg框架很強大,上周末突發奇想,用來作為微信公眾號后台怎么樣?想到就開干。
首先,要開發必須要先配置好才行,這里先講一下怎么配。
- 首先你要有一個公眾號,去申請,或者弄一個測試的公眾號,地址 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421137522
- 搞到公眾號后,就可以配置公眾號基本設置了,
- 然后大概的步驟可以參照微信官方的文檔進行,https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319
- 在egg的具體代碼
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,用來加密的,其他東西就不用裝了,照着代碼來就好了。
注:12、13、14行的參數填寫你自己的,可以在微信公眾號后台登錄進去查看到。