公众号配置
在开启服务器配置的时候需要验证自己的url.
router.get('/api/send', (req, res) => {
let token = wxToken;
let signature = req.query.signature;
let timestamp = req.query.timestamp;
let nonce = req.query.nonce;
let echostr = req.query.echostr;
let arr = [token, timestamp, nonce];
arr = arr.sort();
let str = arr.join('');
str = sh1(str);
if (str == signature) {
res.send(echostr)
} else {
res.json({})
}
})
接收短信
router.post('/api/send', (req, res) => {
var _da;
req.on("data", function (data) {
_da = data.toString("utf-8");
});
req.on("end", async function () {
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);
// Content = '<![CDATA[667898]]>'
var xml = joinXml(_da,'这个是回复的内容')
res.send(xml);
});
})
function getXMLNodeValue(node_name, xml) {
var tmp = xml.split("<" + node_name + ">");
var _tmp = tmp[1].split("</" + node_name + ">");
return _tmp[0];
}
function getXMLVal(xml){
return xml.split(']')[0].split('[').reverse()[0]
}
function joinXml(_da, val = '') {
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);
let resTxt = ''
if (val == '') {
resTxt = Content;
} else {
resTxt = '<![CDATA[' + val + ']]>'
}
return '<xml><ToUserName>' + FromUserName + '</ToUserName><FromUserName>' + ToUserName + '</FromUserName><CreateTime>' + CreateTime + '</CreateTime><MsgType>' + MsgType + '</MsgType><Content>' + resTxt + '</Content></xml>';
}