详解nodejs微信公众号开发——3.封装消息响应模块

2020-06-17 07:05:27易采站长站整理

</Music>
<% } %>else if(msgType ==='news'){ %>
<ArticleCount><%= content.length %></ArticleCount>
<Articles>
<% content.forEach(function(item){ %>
<item>
<Title><![CDATA[<%= item.title %>]]></Title>
<Description><![CDATA[<%= item.description %>]]></Description>
<PicUrl><![CDATA[<%= item.picUrl %>]]></PicUrl>
<Url><![CDATA[<%= item.url %>]]></Url>
</item>
<% }) %>
</Articles>
<% } %>
</xml>
*/});

var compiled = ejs.compiled(tpl);

exports = module.exports = {
compiled:compiled
};

3. 处理接收到的消息

修改

generator.js
中之前直接回复消息的那部分代码,我们将处理回复内容的逻辑交给业务层,等其处理完毕,继续执行下面的代码,封装消息内容成xml并回复出去。


var message = util.formatMessage(content.xml);

this.weixin = message; //挂载消息

yield handler.call(this,next); //转到业务层逻辑

wechat.replay.call(this); //真正回复

4.业务层的处理逻辑

app.js
里面中间件的使用方式修改为:


var weixin = require('./weixin');
...
app.use(wechat(config.wechat,weixin.reply));

weixin.reply
generator.js
中的
handler
,我们将公众号业务成的逻辑都写在
weixin.js
里面,如回复消息、将来的爬取电影网站信息、支付等。


exports.reply = function* (next){
var message = this.weixin;

if(message.magType === 'event'){
if(message.Event === 'subscribe'){
if(message.EventKey) console.log('扫描二维码关注:'+message.EventKey+' '+message.ticket);
this.body = '终于等到你,还好我没放弃';
}else if(message.Event === 'unsubscribe'){
console.log(message.FromUserName +' 悄悄地走了...');
}
}else{
//
}

yield next;
}

5.回复消息

我们在Wechat原型链上增加

replay
方法:


Wechat.prototype.replay = function(){
var content = this.body;
var message = this.weixin;

var xml = util.tpl(content,message);

this.status = 200;