微信公众号自动回复 node

纯属分享记录:

app.js

var bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
var wx = require('./admin/wx/wx.js');
//解析xml
app.use(bodyParser.xml({
limit: '1MB',
xmlParseOptions: {
    normalize: true,
    normalizeTags: true,
    explicitArray: false
}
}));

//微信
app.post('/wx',function(req,res){
    wx.replyWx(req,res);
});

wx.js

//微信自动回复
function wx(){
    this.replyWx = function(req,res){
        res.writeHead(200, {'Content-Type': 'application/xml'});
      var data = req.body.xml;
      if(data.msgtype === 'event' && data.event === 'subscribe'){
          data.content = '欢迎关注浅唱姩華,这里是开发者试用帐号!';
          msgText(res,data);
      }else if(data.msgtype === 'event' && data.event === 'unsubscribe'){
          //取消关注了
      }else if(data.msgtype === 'text'){//文本消息
          msgText(res,data);
      }else if(data.msgtype === 'image'){//图片消息
          data.content = '你好暂不支持图片回复';
          msgText(res,data);
      }else if(data.msgtype === 'video'){//视频消息
          data.content = '你好暂不支持视频回复';
          msssage(res,data);
      }else if(data.msgtype === 'voice'){//语言消息
          data.content = '你好暂不支语音回复';
          msssage(res,data);
      }
    }
}

function msgText(res,data){
    //fromusername 接受者openid
    //tousername  发送者openid
     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>';
      res.end(resMsg);
}

module.exports = new wx();

访问路径就是你token验证通过的路径,这里是自动回复文本消息,用户发什么,你自动回什么

原文地址:https://www.cnblogs.com/bruce-gou/p/6367447.html