egg-mp icon indicating copy to clipboard operation
egg-mp copied to clipboard

能否增加微信支付结果通知的处理

Open wulisensen opened this issue 5 years ago • 1 comments

感谢代码分享,接收微信支付的回调要处理xml,插件能否一并解决了呢?

wulisensen avatar Sep 11 '19 03:09 wulisensen

非常感谢您的建议~

首先,即便不处理微信支付的回调,也不影响正常支付流程。

其次,此插件也预留了响应支付结果的能力,依赖了两个库:

  "dependencies": {
    "egg": "^2.23.0",
    "xml-js": "^1.6.11"
  },

可以写个中间件拦截text/xml类型的请求,把转换后的结果放到request.body对象即可,简单实现如下:

// 自定义Egg插件
module.exports = () => {
  return async (ctx, next) => {
    const { request } = ctx;
    if (request.header["content-type"] === "text/xml") {
      var req = request.req;
      await new Promise(function (resolve, reject) {
        let buf = "";
        req.on("data", chunk => {
          buf += chunk;
        });
        req.on("end", () => {
          request.body = ctx.helper.xml2json(buf); // xml-js库内置方法
          resolve();
        });
      });
      return next();
    }
    return next();
  };
};

最后,社区已有许多很好解决方案了,比如koa-xml-bodyegg-xml-body,秉承一个插件只做一件事理念,暂不考虑一并解决。

unclexiao avatar Sep 11 '19 13:09 unclexiao