时间:2021-01-25 10:26:31 | 栏目:NodeJS | 点击:次
在写之前我想先说说koa,koa相比express,在执行流程,以及组件方面优秀的多,koa本身没有提供过多的扩展组建,但是它便捷的组建扩展,可以让你自由的发挥,可以想写其他语言一样并行执行代码,如果说promise解放了繁琐的callback,那么 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升错误处理的效率。koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手,nodejs的天生的异步处理流程,使得它很适合微信公众号这种频繁的消息互动,再加上pm2的多进程管理,可以说已经很大程度的满足大号的消息转发互动已经公众号内部红包玩法。
在使用koa2搭建微信第三方公众平台是,首先要解决的是如果获取微信返回的xml流,以及如何返回对应的XML体给微信。
由于本身koa不是一个框架,所以得益于网上众多的中间件,自己搭建了一个类似于express的框架,本框架已经开源,详情请看我的git地址:https://github.com/yxz1025/koa-lana,所有的微信接发消息均在此框架中,请读者自行下载!
好了,首先,我们看看如何获取微信返回的xml流:
======tool.js===== //截获微信返回的xml流文件 const Promise = require('bluebird'); //普通post流转化为promise var Tool = { convertPost: function(req) { let post_data = ""; return new Promise(function(resolve, reject){ req.on('data', function(chunk) { post_data += chunk; }); req.on('end', function() { resolve(post_data); }); }); }, }; module.exports = Tool; =====weichat.js====== //微信响应主体文件 const router = require('koa-router')(); const parseMessage = require('../common/parseMessage'); const config = require('../config'); const WXBizMsgCrypt = require('wechat-crypto'); const middleware = require('../model/middleware'); const validator = require('validator'); const Aes = require('../common/aes'); const Tool = require('../common/tool'); const cryptor = new WXBizMsgCrypt(config.component_config.token, config.component_config.key, config.component_config.component_appid); //第三方授权路径 /:appid/callback /wechat/100234/callback router.post('/:appid/callback', async function(ctx, next) { let post_data = ""; let req = ctx.req; post_data = await Tool.convertPost(req); let xml = parseMessage(post_data); let signature = cryptor.getSignature(ctx.query.timestamp, ctx.query.nonce, xml.encrypt); if (ctx.query.msg_signature != signature) { ctx.body = 'Auth failed!'; // 指纹码不匹配时返回错误信息,禁止后面的消息接受及发送 } let message = middleware.decryptXml(xml); let appid = ctx.params.appid; message.appId = appid; //发送消息队列 switch (message.msgType) { case 'text': //测试 if (message.toUserName == "gh_3c884a361561") { if (message.content == "TESTCOMPONENT_MSG_TYPE_TEXT") { let text = middleware.text(message, message.content + "_callback"); let reply = middleware.encryptXml(text); return ctx.body = reply; } let content = message.content; if (content.indexOf("QUERY_AUTH_CODE") != -1) { ctx.body = ""; let code_li = content.split(":"); await middleware.customSend(message.fromUserName, code_li[1]); return; } } let keywords = validator.trim(message.content).toLowerCase(); let member_config = await middleware.getMemberConfig(message.toUserName, keywords); if (!member_config) { await middleware.sendMnsQuene(message); return ctx.body = "success"; }else{ //匹配成功 message.packetsId = parseInt(member_config.hongbaoId); message.keywords = keywords; await middleware.sendMnsQuene(message); let data = { title: member_config.news_title || '点我领红包', description: member_config.description || '第一轮红包雨开始了,手快有,手慢无!', picurl: member_config.picurl || 'http://7xqomp.com2.z0.glb.qiniucdn.com/17269743.png' }; let key = { fromUserName: message.fromUserName, toUserName: message.toUserName, keywords: keywords, appId: appid }; key = JSON.stringify(key); key = Aes.encypt(key); key = Aes.base64_encode(key); //获取授权域名 let auth_url = await middleware.packetDomain(); data.url = "http://" + appid + "." + auth_url + "/redPackets/koulin?key=" + key; let news = middleware.news(message, [data]); let reply = middleware.encryptXml(news); ctx.body = reply; return; } break; case 'event': await middleware.sendMnsQuene(message); //测试专用 if (message.toUserName == "gh_3c884a361561") { let text = middleware.text(message, message.event + "from_callback"); let reply = middleware.encryptXml(text); ctx.body = reply; return; } break; default: await middleware.sendMnsQuene(message); ctx.body = "success"; return; }; }); module.exports = router;