node egg框架处理微信支付成功回调xml数据

直接上详细代码

首先使用egg框架中间件,在app目录建middleware文件夹,再创建一个js文件如

该js中的代码:

module.exports = () => {
    return async function (ctx, next) {
        var bodyParser = require('body-parser');
        ctx.app.use(bodyParser.urlencoded({
          extended:true
        }));
        await next();
    }
};

然后在路由中使用该中间件(此处我在'/wxpay'的回调路由中调用,具体结合自己实际)

  const xmlparse = app.middleware.xmlparse();
  app.post('/wxpay',xmlparse, app.controller.xcx.wxpay.wxPayCallBack);

最后是路由方法中的代码(此处我直接在controller层写的代码,自己也可在service层调用)

'use strict'
const Controller = require('egg').Controller;
const xml2js = require('xml2js').parseString;
class wxpayController extends Controller{
    async wxPayCallBack(){
        let data = '';
        let json = {};
        this.ctx.req.setEncoding('utf8');
        this.ctx.req.on('data',function(chunk){
           data += chunk;
        });
        let that = this;
        this.ctx.req.on('end',function(){
            xml2js(data,{explicitArray:false}, function (err, json) {
                console.log(json);//这里的json便是xml转为json的内容
                that.ctx.body = 'success';
            });
            
        });
    }
}
module.exports = wxpayController;
注:其中使用了两个组件(body-parser、xml2js)可自行安装

猜你喜欢

转载自blog.csdn.net/JiangYuXuan1994/article/details/79958583