nodejs微信聊天服务器,nodejs微信消息收发接口的实现

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 = ''+FromUserName+''+ToUserName+''+CreateTime+''+MsgType+''+Content+'';

res.send(xml);

});

};

function getXMLNodeValue(node_name,xml){

var tmp = xml.split("");

var _tmp = tmp[1].split(""+node_name+">");

return _tmp[0];

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值