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:
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:
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;
};