Home  >  Article  >  Web Front-end  >  Node.js+Koa development response event example

Node.js+Koa development response event example

零下一度
零下一度Original
2017-06-25 09:15:111514browse

The events in the WeChat official account include subscription events/code scanning events/click events/jump link events, etc. For details, please refer to the documentation.

Let’s implement the subscription event here. The implementation process of other events is similar.

When someone subscribes to the public account, the WeChat server will push an event to our server. This event is a data packet in XML format.

1. We implement the response to post events under index routing.

It can be understood that when WeChat pushes a message to our server, the message will go here first.

/routes/index.js added:

router.post('/', index_middleware.post(config.wechat));

2. Implement the post method in index_middleware:

is how we should handle the WeChat server post request to our server.

The general process is to first receive the data packet sent by the WeChat server, then parse the XML data packet, and then perform logical processing on our server based on the received data to form a reply message in XML format. .

/wechat/index_middleware.js added:

exports.post = function(opts) {return function *(next) {var token = opts.token;var signature = this.query.signature;var nonce = this.query.nonce;var timestamp = this.query.timestamp;var echostr = this.query.echostr;var str = [token, timestamp, nonce].sort().join('');var sha = sha1(str);if (sha !== signature) {this.body = 'wrong';return false;
        }var data = yield getRawBody(this.req, {
            length: this.length,
            limit: '1mb',
            encoding: this.charset
        });var message = yield util.parseXMLAsync(data);var xml = yield autoReply(message.xml, wechat);
        console.log(message);
        console.log(xml);this.status = 200;this.type = 'application/xml';this.body = xml;
    };
};

The data here is the data packet we received, using the raw-body component. At the same time, the tool function util and the custom function autoReply are used.

Therefore, the following code needs to be added to /wechat/index_middleware.js:

var getRawBody = require('raw-body');var util = require('./util');var autoReply = require('./autoReply');

3. Implement the parseXMLAsync method in the util tool function. Its function is to asynchronously Format xml into json data.

/wechat/util.js:

var fs = require('fs');var xml2js = require('xml2js');

exports.parseXMLAsync = function(xml) {return new Promise(function(resolve, reject) {
        xml2js.parseString(xml, {
            trim: true,
            explicitArray: false}, function(err, content) {if (err) {
                reject(err);
            }
            resolve(content);
        });
    });
};

The xml2js component is used here.

4. Implement the autoReply function. Its function is to logically process the data packets sent by the WeChat server to form the XML format data we need to send to WeChat.

/wechat/autoReply.js:

var createXML = require('./createXML');function autoReply(message, wechat) {if (message.MsgType === 'event') {if (message.Event === 'subscribe') {if (message.EventKey) {
                console.log('扫码进入');
            }var now = new Date().getTime();return Promise.resolve(createXML({
                ToUserName: message.FromUserName,
                FromUserName: message.ToUserName,
                MsgType: 'text',
                Content: 'Hello!!'}));
        }else if (message.Event === 'unsubscribe') {
            console.log('取关');return Promise.resolve('');
        }
    }
}

Only the following and unfollowing events are implemented here, and the createXML function is also used. Its function is to encapsulate the data. Into xml format:

/wechat/createXML.js:

function createXML(messageObj) {var { ToUserName, FromUserName, MsgType = 'text'} = messageObj;var CreateTime = new Date().getTime();var header = `<xml>
                    <ToUserName><![CDATA[${ToUserName}]]></ToUserName>
                    <FromUserName><![CDATA[${FromUserName}]]></FromUserName>
                    <CreateTime>${CreateTime}</CreateTime>
                    <MsgType><![CDATA[${MsgType}]]></MsgType>`;var content = '';switch(MsgType) {case 'text':var { Content } = messageObj;
            content = `<Content><![CDATA[${Content}]]></Content>
                     </xml>`;break;case 'image':var { MediaId }  = messageObj;
            content = `<Image>
                         <MediaId><![CDATA[${MediaId}]]></MediaId>
                       </Image>
                     </xml>`;break;case 'voice':var { MediaId } = messageObj;
            content = `<Voice>
                         <MediaId><![CDATA[${MediaId}]]></MediaId>
                       </Voice>
                     </xml>`;break;case 'video':var { MediaId, Title, Description } = messageObj;
            content = `<Video>
                         <MediaId><![CDATA[${MediaId}]]></MediaId>
                         <Title><![CDATA[${Title}]]></Title>
                         <Description><![CDATA[${Description}]]></Description>
                       </Video> 
                     </xml>`;break;case 'music':var { Title, Description, MusicUrl, HQMusicUrl, ThumbMediaId } = messageObj;
            content = `<Music>
                         <Title><![CDATA[${Title}]]></Title>
                         <Description><![CDATA[${Description}]]></Description>
                         <MusicUrl><![CDATA[${MusicUrl}]]></MusicUrl>
                         <HQMusicUrl><![CDATA[${HQMusicUrl}]]></HQMusicUrl>
                         <ThumbMediaId><![CDATA[${ThumbMediaId}]]></ThumbMediaId>
                       </Music>
                     </xml>`;break;case 'news':var { Articles } = messageObj;var ArticleCount = Articles.length;
            content = `<ArticleCount>${ArticleCount}</ArticleCount><Articles>`;for (var i = 0; i < ArticleCount; i++) {
                content += `<item>
                                <Title><![CDATA[${Articles[i].Title}]]></Title>
                                <Description><![CDATA[${Articles[i].Description}]]></Description>
                                <PicUrl><![CDATA[${Articles[i].PicUrl}]]></PicUrl>
                                <Url><![CDATA[${Articles[i].Url}]]></Url>
                              </item>`;            }
            content += '</Articles></xml>';break;default:
            content = `<Content><![CDATA[Error]]></Content>
                     </xml>`;    }    var xml = header + content;return xml;
}

module.exports = createXML;

After completing the above work, start our server, follow the official account again, and you should receive a message Hello! ! Information.

In this way, the processing of events of concern is realized.

The above is the detailed content of Node.js+Koa development response event example. 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