Home >Web Front-end >JS Tutorial >Using NodeJs to develop WeChat public accounts (3) WeChat event interaction example_node.js
WeChat official account has a rule that once the developer mode is turned on, all other regular functions must be completed through interface calls. For example, custom menu functions must be generated by sending post requests. 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 attach 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 If consistent, xml parsing will be performed. 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();
Use the monitoring data of req to obtain the xml package sent by WeChat. 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:
tousername: Recipient [This is the public WeChat ID]
fromusername: sender [here is user openid]
createTime: sending time
msgtype: message type [event (response event), text (push message), image (push graphic message), etc.]
event: message name [Follow here]
eventkey: a custom key, which can be customized when setting up the web page. This will be discussed later
The above is the data packet sent by WeChat to your interface when a 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) Get 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 use the strategy pattern in the JS design pattern. Write your own business in the subscribe method. By sending a request with the openid parameter, you can save several of the user's information when they follow the WeChat account. database and establish a session. 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.