shmy / cn-pay

比较好用的支付宝,微信支付node版SDK
MIT License
60 stars 13 forks source link

undefined TypeError: Cannot read property 'sign' of undefined #4

Closed napasa closed 6 years ago

napasa commented 6 years ago

TypeError: Cannot read property 'sign' of undefined at Wechat.verify (C:\Users\Administrator\Desktop\test\node_modules\cn-pay\src\wechat\index.js:48:25) at app.post (C:\Users\Administrator\Desktop\test\index.js:36:16) at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Administrator\Desktop\test\node_modules\express\lib\router\index.js:275:10) at expressInit (C:\Users\Administrator\Desktop\test\node_modules\express\lib\middleware\init.js:40:5)

该错误原因有express不原生支持xml parser,因此需要插件。 对于该错误可如下方式解决:

const xmlparser = require('express-xml-bodyparser');
 app.post('/official_pay/tenpay_callback', xmlparser({trim: false, explicitArray: false}), function(req, res, next) {  
    if (wechat.verify(req.body.xml)) { // 一句话验签,就这么简单
        console.log("微信支付异步验签成功:");
        // 业务逻辑
        res.send(wechat.success()); // 可以调用success或fail方法 返回结果
    } else {
        console.log("微信支付异步验签失败:");
        res.send(wechat.fail("验签失败"));
    }
 }
shmy commented 6 years ago

是哪个环节

shmy commented 6 years ago

你打印下req.body 有哪些属性

shmy commented 6 years ago
verify(body, sign) {
    body = typeof body === 'string' ? util.parseXML(body) : body;
    sign = sign || body.sign;
    return sign === util.generateSign(body, this.config.key);
  }

你打印出怎么有个xml的属性,那你传入req.body.xml试试吧

shmy commented 6 years ago

如果body未解析,但是能拿到字符串,插件内部会自动转换的

napasa commented 6 years ago

不太懂。我是业余的。你看看能不能写个例子方便别人使用。