node微信开发笔记

服务器验证加消息回复

const express = require('express'),
      crypto = require('crypto'),
      config = require('./config');
const bodyParser = require('body-parser')
require('body-parser-xml')(bodyParser)
var app = express();
app.get('/', (req, res) => {
  console.log(req.query)
  let signature = req.query.signature,
      timestamp = req.query.timestamp,
      nonce = req.query.nonce,
      echostr = req.query.echostr;
  let array = [config.token,timestamp,nonce]
  array.sort()
  let tempStr = array.join('')
  const hashCode = crypto.createHash('sha1'); //创建加密类型 
  let resultCode = hashCode.update(tempStr,'utf8').digest('hex'); //对传入的字符串进行加密
  if(resultCode === signature){
    res.send(echostr);
  }else{
   res.send('mismatch');
  }
})

app.use(bodyParser.xml({
  limit: '1MB',
  xmlParseOptions: {
    normalize: true,
    normalizeTage: true,
    explicitArray: false
 }
}))

app.post('/', (req, res) => {
  res.writeHead(200, {'Content-Type': 'application/xml'});
  var data = req.body.xml;
  console.log(data)
  var resMsg = '<xml>' +
    '<ToUserName><![CDATA[' + data.FromUserName + ']]></ToUserName>' +
    '<FromUserName><![CDATA[' + data.ToUserName + ']]></FromUserName>' +
    '<CreateTime>' + parseInt(new Date().valueOf() / 1000) + '</CreateTime>' +
    '<MsgType><![CDATA[text]]></MsgType>' +
    '<Content><![CDATA['+data.Content+']]></Content>' +
    '</xml>';
  if (data.Content === '1') {
   let temp =  '<xml>' +
    '<ToUserName><![CDATA[' + data.FromUserName + ']]></ToUserName>' +
    '<FromUserName><![CDATA[' + data.ToUserName + ']]></FromUserName>' +
    '<CreateTime>' + parseInt(new Date().valueOf() / 1000) + '</CreateTime>' +
    '<MsgType><![CDATA[text]]></MsgType>' +
    '<Content><![CDATA[1.q\n2.ing]]></Content>' +
    '</xml>';
   res.end(temp)
  } else {
    res.end(resMsg);
  }
})

app.listen(3000)

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注