Use NodeJs to develop WeChat Public Account (3) WeChat event interaction instances and nodejs instances

Source: Internet
Author: User
Tags openid

Use NodeJs to develop public account (3) event interaction instances and nodejs instances

The public account has a rule. Once the developer mode is enabled, other common functions must be called through interfaces. For example, the custom menu function must be generated by sending a post request. In this chapter, we will talk about how nodejs interacts with each other by following the entire process of removing attention. The entry to these functions is the URL you entered in the test public number (replaced by/login/wechat ).

Event Interaction

After scanning the QR code to follow the public account, your interface/login/wechat will be called and an xml message will be included. First, you need to obtain some signatures, whether the encryption and sorting ratios are consistent with the TOKEN you entered. If they are consistent, xml parsing is performed. When parsing xml, node must first reference the module. Therefore, the xml parsing module is introduced first.

// Xml parsing module var XMLJS = require ('xml2js'); // parse the xml to jsonvar parser = new XMLJS. parser (); // restructured json into xmlvar builder = new XMLJS. builder ();

Use the req listener data to obtain the xml package sent. The following is the xml package data sent by a new user to your background interface (/yourapi mentioned in the previous article) after paying attention to the public number. After parsing, its structure is as follows:

Tousername: Recipient [public account here]

Fromusername: sender [openid here]

CreateTime: sending time

Msgtype: Message Type [event (RESPONSE event), text (PUSH message), image (push text message), etc]

Event: Message name [follow here]

Eventkey: Custom key, which can be customized when setting a webpage.

The above is the data packet sent to your interface after the user pays attention to it. In the face of our useful is fromusername, that is, the attention of the openid, we get the user's attention to the openid can be provided by the specific interface (https://api.weixin.qq.com/cgi-bin/user/info? Access_token = ACCESS_TOKEN & openid = OPENID & lang = zh_CN) obtains the user's profile picture, gender, nickname, and other information to create a reliable database for your app.

Code Implementation

// The Event push entry app. post ('/yourapi', function (req, res, next) {// obtain the parameter var query = req. query; // sign var signature = query. signature; // The output character. You entered the TOKEN var echostr = query. echostr; // timestamp var timestamp = query ['timestamp']; // random string var nonce = query. nonce; var oriArray = new Array (); oriArray [] = nonce; oriArray [] = timestamp; oriArray [] = appConfig. token; // The sorting parameter oriArray. sort (); var original = oriArray [] + oriArray [] + OriArray []; // encrypt var scyptoString = sha (original); // determine whether the TOKEN is equal to the TOKEN you enter if (signature = scyptoString) {// retrieve xml data req. on ("data", function (data) {// Parse xml into parser. parseString (data. toString (), function (err, result) {var body = result. xml; var messageType = body. msgType []; // the user clicks the menu to respond to the event if (messageType === 'event') {var eventName = body. event []; (EventFunction [eventName] | function () {}) (body, req, res); // automatically replies to messages} e Lse if (messageType === 'text') {EventFunction. responseNews (body, res); // check whether the interface is valid when you enter the URL for the first time} else {res. send (echostr) ;}}) ;}} else {// authentication failed, the res operation is invalid. send ("Bad Token! ") ;}}); // Various callback interfaces of the client var EventFunction ={// follow subscribe: function (result, req, res) {// Save the user information to the database through the openid interface .}, // Unsubscribe: function (openid, req, res) {// Delete the corresponding id}, // open a webpage VIEW: function () {// as required, processing Different services}, // automatically responds to responseNews: function (body, res) {// assemble the required jsonvar xml = {xml: {ToUserName: body. fromUserName, FromUserName: body. toUserName, CreateTime: + new Date (), MsgType: 'text', Content: 'edit @ +, you can receive'}; var reciviMessage = body. content [] if (/^ \@. */. test (reciviMessage) {xml. xml. content = 'Your suggestion has been received and will be processed in time! '} <Br> // convert json to xmlxml = builder. buildObject (xml); <br> // send it to res. send (xml );}}

This method is applicable to the JS design mode. You can write your own business in the subscribe method by sending a request with the openid parameter, you can save a few pieces of data to the database and establish a session when paying attention to the number. In this way, you do not need to authenticate again when opening your web page. You only need to compare the openid and then query the database.

Articles you may be interested in:
  • Use Nodejs to develop public account backend service instances
  • Node. js public platform development tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.