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.

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

微信开发系列之二 - 在微信公众号里开发一个自动应答的图灵机器人相关推荐

  1. 微信公众号开发 - 配置表设计以及接入公众号接口开发

    微信公众号开发文章目录 1.微信公众号开发 - 环境搭建 2.微信公众号开发 - 配置表设计以及接入公众号接口开发 3.微信公众号开发 - token获取(保证同一时间段内只请求一次) 4.微信公众号 ...

  2. 微信公众号里如何上传html,微信公众号怎么做表单,微信万能表单如何添加到公众号里...

    微信的使用占据着大众的日常,而微信上的一些订单.预约.登记.投诉.反馈等功能都可以使用微信万能表单来实现,那么微信万能表单怎么做?下文带来微信公众号表单制作方法,方法很简单,需要的朋友一起看看吧. 微 ...

  3. easywechat微信开发系列(1):公众号网页授权

    准备工作: 1.已认证的服务号(apppid.appsecret.token.aes_key) 2.安全域名 3.已经用composer安装好easywechat 1.config/app.php 的 ...

  4. 微信分享链接标题和小图片-不通过公众号接口开发

    方法一:不通过公众号接口开发 在boby 和head之间添加下面的代码即可,图片路径自行修改. 注意这个图片必须是大于300px300px的 <body><div style ='m ...

  5. 公众号商城开发和微信小程序商城开发有什么区别?

    小程序和公众号商城都属于微商城,但是有很多朋友也不知道这两者之间有什么区别.对于选择做公众号商城还是小程序商城时,出现了选择困难症.既然微信小程序商城和微信公众号商城都是微信内的产品aigao0607 ...

  6. JAVA微信公众号后台开发 接口接入

    前期准备 注册一个公众号,完成认证,阅读开发手册,选取开发工具,配置环境等等. 微信公众号开发标准 通过阅读文档我们了解到微信服务器向开发者提供接口,具体的流程如下 由上图可以看出,开发者需要做的:接 ...

  7. 公众号抽奖怎么做_分享公众号里放微信抽奖活动链接步骤

    微信抽奖活动相信大家一定不会陌生的,而且我们在做公众号营销活动的时候,首选的也是抽奖链接,那么抽奖活动的类型也是五花八门,可以让我们选择的也是非常多,那么今天小编就来分享一款我们常用的在公众号里边的抽 ...

  8. C#微信公众号开发系列教程二(新手接入指南)

    此系列前面已经更新了两篇博文了,都是微信开发的前期准备工作,现在切入正题,本篇讲解新手接入的步骤与方法,大神可直接跳过,也欢迎大神吐槽. 微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教 ...

  9. SAP系统和微信集成的系列教程之八:100行代码在微信公众号里集成地图搜索功能

    本系列的英文版Jerry写作于2017年,这个教程总共包含十篇文章,发表在SAP社区上. 系列目录 (1) 微信开发环境的搭建 (2) 如何通过微信公众号消费API (3) 微信用户关注公众号之后,自 ...

最新文章

  1. 从html到pug模板,将变量从html-webpack-plugin传递到pug模板
  2. JDK的bin目录下所有程序的使用介绍
  3. VMware NSX for vSphere 6.3.0 发行说明
  4. 15-3 并发调度器
  5. Django 前后端数据传输、ajax、分页器
  6. mysql建用户注册登录表_登录注册数据库建立
  7. C++ 隐藏窗口在任务栏的显示
  8. C#莱姆达表达式的使用
  9. JVM虚拟机安装苹果系统
  10. redis全面讲解使用场景
  11. 70句计算机英语,医务人员常用英语70句
  12. html语义化标签和无语义化标签
  13. 微信小程序 后台播放,多页面播放
  14. Linux socket编程
  15. 医学统计学 第四章(定量资料的统计描述)
  16. (原创)分布式系统应对单点故障策略选择
  17. 基于php的宠物狗销售网站
  18. 用计算机如何画柳条,柳条简笔画
  19. TP-link WR703N v1.17固件不拆机绕过RSA验证强刷openwrt
  20. 【Impala】根据当前日期取去年、今年、上月、日期差

热门文章

  1. openwrt 在centos7 上的开发环境搭建时需要注意的地方
  2. 1)phpmyadmin导入数据库大小限制修改
  3. 【转】测试架构师团队的管理
  4. 【观点】风雨20年:我所积累的20条编程经验
  5. 通过VsPhere体验MAC OS X
  6. Adwords 账户细分思路
  7. AT24C02的多字节数据读写
  8. 〖Python〗-- Django内置Admin
  9. [acm]HDOJ 1200 To and Fro
  10. C# 事件(第四章)