Home  >  Article  >  WeChat Applet  >  NodeJs develops WeChat public account WeChat event interaction example code

NodeJs develops WeChat public account WeChat event interaction example code

高洛峰
高洛峰Original
2017-03-21 16:00:391534browse

This article mainly introduces the relevant information about using NodeJs to develop WeChat event interaction examples for WeChat public accounts. Friends in need can refer to it

WeChat public accounts have rules. Once the developer mode is turned on, other All regular functions must be called through interface. For example, the custom menu function must be generated by sending a post request. This chapter will talk about how nodejs interacts with WeChat through the entire process from following to unfollowing. The entrance to these functions is the URL you filled in the test official account (replaced with /login/wechat below).

Event interaction

After scanning the QR code to follow the WeChat official account, WeChat will call your interface /login/wechat , and comes with a piece of xml information. First, you need to obtain some signatures, and check whether they are consistent with the TOKEN you filled in through encryption and sorting. If they are consistent, parse the xml. When node parses xml, the module must be referenced first. Therefore, first introduce the xml parsing module

//xml解析模块
var XMLJS = require('xml2js');
//解析,将xml解析为json
var parser = new XMLJS.Parser();
//重组,将json重组为xml
var builder = new XMLJS.Builder();

to obtain the xml package sent by WeChat through the monitoring data of req. The following is the xml packet data sent by WeChat to your backend interface (/yourapi mentioned in the previous article) after a new user follows the official account. After parsing, its structure is as follows:

NodeJs develops WeChat public account WeChat event interaction example code

tousername: Recipient [Public WeChat ID here]

fromusername: Sender [User openid here]

createTime: sending time

msgtype: message type [event (response event), text (push message), image (push graphic message), etc.]

event : Message name [Follow here]

eventkey: Customized key, which can be customized when setting up the web page. We will talk about it later

The above is used as a The data packet sent by WeChat to your interface after the user follows it. What is useful to us above is fromusername, which is the openid of the follower. After we obtain the openid of the user when following, we can use the specific interface provided by WeChat (https://api.weixin.qq.com/cgi-bin/ user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN) to obtain the user’s avatar, gender, nickname and other information to build a reliable database for your app.

Code implementation

//微信事件推送的入口
app.post('/yourapi', function(req, res, next) {
//获取参数
var query = req.query; 
//签名
var signature = query.signature; 
//输出的字符,你填写的TOKEN 
var echostr = query.echostr; 
//时间戳
var timestamp = query['timestamp']; 
//随机字符串
var nonce = query.nonce; 
var oriArray = new Array(); 
oriArray[] = nonce; 
oriArray[] = timestamp; 
oriArray[] = appConfig.token;
//排序参数
oriArray.sort(); 
var original = oriArray[]+oriArray[]+oriArray[]; 
//加密
var scyptoString = sha(original); 
//判断是否与你填写TOKEN相等
if (signature == scyptoString) {
//获取xml数据
req.on("data", function(data) {
//将xml解析
parser.parseString(data.toString(), function(err, result) {
var body = result.xml;
var messageType = body.MsgType[];
//用户点击菜单响应事件
if(messageType === 'event') {
var eventName = body.Event[];
(EventFunction[eventName]||function(){})(body, req, res);
//自动回复消息
}else if(messageType === 'text') {
EventFunction.responseNews(body, res);
//第一次填写URL时确认接口是否有效
}else {
res.send(echostr);
}
});
});
} else { 
//认证失败,非法操作
res.send("Bad Token!"); 
}
});
//微信客户端各类回调用接口
var EventFunction = {
//关注
subscribe: function(result, req, res) {
//存入openid 通过微信的接口获取用户的信息同时存入数据库。
},
//注销
unsubscribe: function(openid, req, res) {
//删除对应id
},
//打开某个网页
VIEW: function() {
//根据需求,处理不同的业务
},
//自动回复
responseNews: function(body, res) {
//组装微信需要的json
var xml = {xml: {
ToUserName: body.FromUserName,
FromUserName: body.ToUserName,
CreateTime: + new Date(),
MsgType: 'text',
Content: '编辑@+您想说的话,我们可以收到'
}};
var reciviMessage = body.Content[]
if(/^\@.*/.test(reciviMessage)) {
xml.xml.Content = '已经收到您的建议,会及时处理!'
}<br>//将json转为xml
xml = builder.buildObject(xml);<br>//发送给微信
res.send(xml);
}
}

Here, it is suitable to adopt the strategy in JS design pattern Mode , write your own business in the subscribe method, and by sending a request with the openid parameter, you can save several pieces of information to the database and establish a session when the user follows the WeChat ID. In this way, when the user opens your web page next time, he does not need to authenticate again. He only needs to compare the openid and query the database.

The above is the detailed content of NodeJs develops WeChat public account WeChat event interaction example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn