1.首先需要在公众号的开发者中心启用服务器配置
exports.wechat = function (req, res) {
var echostr, nonce, signature, timestamp;
signature = req.query.signature;
timestamp = req.query.timestamp;
nonce = req.query.nonce;
echostr = req.query.echostr;
if(check(timestamp,nonce,signature,"weixin")){
return res.send(echostr);
}else{
return res.end();
}
};
function check(timestamp, nonce, signature ,token) {
var currSign, tmp;
tmp = [token, timestamp, nonce].sort().join("");
currSign = crypto.createHash("sha1").update(tmp).digest("hex");
return currSign === signature;
};
2.如果有用户发送消息给公众号,微信服务器就会发送一个post请求到服务器配置里的URL,只要接收post过来的xml内容再以xml格式返回就可以实现消息的接收和回复
exports.wechatdo = function (req, res) {
var _da;
req.on("data",function(data){
/*微信服务器传过来的是xml格式的,是buffer类型,因为js本身只有字符串数据类型,所以需要通过toString把xml转换为字符串*/
_da = data.toString("utf-8");
});
req.on("end",function(){
//console.log("end");
var ToUserName = getXMLNodeValue('ToUserName',_da);
var FromUserName = getXMLNodeValue('FromUserName',_da);
var CreateTime = getXMLNodeValue('CreateTime',_da);
var MsgType = getXMLNodeValue('MsgType',_da);
var Content = getXMLNodeValue('Content',_da);
var MsgId = getXMLNodeValue('MsgId',_da);
console.log(ToUserName);
console.log(FromUserName);
console.log(CreateTime);
console.log(MsgType);
console.log(Content);
console.log(MsgId);
var xml = '<xml><ToUserName>'+FromUserName+'</ToUserName><FromUserName>'+ToUserName+'</FromUserName><CreateTime>'+CreateTime+'</CreateTime><MsgType>'+MsgType+'</MsgType><Content>'+Content+'</Content></xml>';
res.send(xml);
});
};
function getXMLNodeValue(node_name,xml){
var tmp = xml.split("<"+node_name+">");
var _tmp = tmp[1].split("</"+node_name+">");
return _tmp[0];
}