Skip to Content

In previous blog Wechat development series 1 – setup your development environment I introduce the necessary step to setup environment for Wechat development.

In this blog, let’s try to achieve some features which makes more sense – the Q&A service implementation based on Wechat platform.
Q&A service typically has the following activity flow:
1. The users of your Wechat subscription account send some text to your subscription account as question;
2. The Wechat platform delegates the message sent by your user to the given url maintained in the subscription account. See mine below for example:
3. Now it is your turn: parse the text sent delegate from Wechat platform, and send answer back into the requested HTTP response. Once that has been done, your end user will receive the answer with the help of Wechat platform.
In this blog I will introduce two kinds of Q&A service implemented.
1. Echo service: Your subscription account users will receive exactly the same text as they send. In order to prove that the text has really reached the nodejs server, I add a prefix “Add by Jerry:” in front of the echo string.
See example below:
2. Tuning service: this service is more smart than the echo service: it will call tuning API to try to chat with your subscription account user:
Here below are the detail steps to implement these two kinds of Q&A service.

Echo service

1. implement server.js which is the entry point of your nodejs server logic:
var express = require('express');
var routesEngine = require('./jerryapp/routes/index.js'); 
var app = express();
routesEngine(app);

app.listen(process.env.PORT || 3000, function () {
  console.log('Listening on port, process.cwd(): ' + process.cwd() );
});
2. implement index.js which is used in server.js:
var request = require('request');
var echoService = require("../service/echo.js");
module.exports = function (app) {
  app.route('/').post(function(req,res){
    echoService(req, res);
  });
};
The code above shows that when your user send a text to your subscription account, an HTTP post request containing this text will be delegated to your nodejs server by Wechat platform, as a result it is your responsibility to parse the text from HTTP post, do your own logic ( simple echo or tuning handling ) and send the response back. The echo service in this blog is implemented in module echo.js.
3. Implement echo.js:
var getXMLNodeValue = require("../tool/xmlparse.js");
var replyMessage = require("../tool/replyMessage.js");
const content_pattern = /<!\[CDATA\[(.*)\]\]>/;
module.exports = function(req, res){
  var _da;
   req.on("data",function(data){
        _da = data.toString("utf-8");
    });
    req.on("end",function(){
        var Content = getXMLNodeValue('Content',_da);
        var body = content_pattern.exec(Content);
        if( body.length === 2) {
            Content = "Add by Jerry: " + body[1];
        } 
        var xml = replyMessage(_da, Content);
        res.send(xml);
    });
};
Here I simply add the hard coded prefix “Add by Jerry:” to the original text and send it back.
The source code of utility module xmlparse.js:
module.exports = function(node_name, xml){
    var tmp = xml.split("<"+node_name+">");
    var _tmp = tmp[1].split("</"+node_name+">");
    return _tmp[0];
};
replyMessage.js:
var getXMLNodeValue = require("./xmlparse.js");
module.exports = function(originalBody, contentToReply){
  var ToUserName = getXMLNodeValue('ToUserName', originalBody);
  var FromUserName = getXMLNodeValue('FromUserName',originalBody);
  var CreateTime = getXMLNodeValue('CreateTime',originalBody);
  var MsgType = getXMLNodeValue('MsgType',originalBody);
  var Content = contentToReply;
  var MsgId = getXMLNodeValue('MsgId', originalBody);
  var xml = '<xml><ToUserName>'+FromUserName+'</ToUserName><FromUserName>'+ToUserName+'</FromUserName><CreateTime>'+CreateTime+'</CreateTime><MsgType>'+MsgType+'</MsgType><Content>'+Content+'</Content></xml>';
  console.log("xml to be sent: " + xml);
  return xml;
};

Tuning Service

It has almost the same steps as done for Echo service except some small enhancement.
In index.js, simply replace echoService call with tuningService.
The implementation of tuning service module:
var request = require('request');
var getXMLNodeValue = require("../tool/xmlparse.js");
var replyMessage = require("../tool/replyMessage.js");
const content_pattern = /<!\[CDATA\[(.*)\]\]>/;

const url = "http://www.tuling123.com/openapi/api?key=de4ae9269c7438c33de5806562a35cac&info=";

module.exports = function(req, res){
  var _da;
    req.on("data",function(data){
        _da = data.toString("utf-8");
    });
    req.on("end",function(){
        console.log("original text: " + _da);
        var Content = getXMLNodeValue('Content',_da);
        console.log("content: " + Content);
        var body = content_pattern.exec(Content);
        console.log("result size: " + body.length);
        var requesturl = "";
        if( body.length === 2){
            requesturl = url + encodeURI(body[1]);
        } 
        var options = {
            url: requesturl,
            method: "GET"
        };
        request(options,function(error,response,data){
           if(data){
              var text = JSON.parse(data).text;
              var xml = replyMessage(_da, text);
              res.send(xml);
           }else {
              res.send("Error when calling Tuning API: " + error);
              console.log(error);
           }
        });
    });
};
In this module I just use a free tuning service provided by http://www.tulin123.com, which is very convenient to consume via Restful API call.
To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply