V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lifesurge
V2EX  ›  程序员

nodejs 集成支付宝能收到 notify 请求但收不到 notify 数据

  •  
  •   lifesurge · 2015-02-12 10:45:24 +08:00 · 6979 次点击
    这是一个创建于 3359 天前的主题,其中的信息可能已经有所发展或是发生改变。
    鄙人正在集成支付宝即时交易接口
    用nodejs+express写的站
    提交订单和return url接收都正常,notify url虽能够收到post请求,但是req.body req.query req.params都是空的
    自己写代码往notify url 发送POST请求 notify url是能收到数据的

    请问,有木有人遇到过类似问题,可能是什么造成的?
    8 条回复    2015-07-02 15:42:42 +08:00
    rankjie
        1
    rankjie  
       2015-02-12 12:20:13 +08:00
    如果你检查下 header 和 raw_data 就会发现支付宝的 content-type 有问题(查commit可以看到是去年9月8号我发现了这问题...),发来的 header['content-type'] 是这么个玩意儿:

    application/x-www-form-urlencoded; text/html; charset=utf-8

    (哪位老师可以指导下为什么是这样的吗?我看w3并没找到有这样的写法)

    于是 bodyparser 看不懂这个 content-type,也就没法把数据解析出来

    我现在的解决办法就是加个中间件处理下,记得放在bodyparser之前

    app.use (req, res, next)->
    if req.url is '/api/alipays/notify' and req.get('content-type') is 'application/x-www-form-urlencoded; text/html; charset=utf-8'
    req.headers['content-type'] = 'application/x-www-form-urlencoded'
    next()
    lifesurge
        2
    lifesurge  
    OP
       2015-02-12 13:08:52 +08:00
    @rankjie 我按照你的方法试了,确实content-type像你所说的那样,但改过以后还是不行啊:

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();

    app.use(function(req, res, next){
    if(req.url == '/alipay/notify' && req.get('content-type') != 'application/x-www-form-urlencoded')
    req.headers['content-type'] = 'application/x-www-form-urlencoded';
    console.log(req.headers['content-type']); // 打印 application/x-www-form-urlencoded
    next();
    });

    app.use(bodyParser.urlencoded({extended:true}))
    app.use(bodyParser.json());
    lifesurge
        3
    lifesurge  
    OP
       2015-02-12 13:12:26 +08:00
    router.post('/alipay/notify', function(req, res){
    console.log(req.query);
    // 依然是空的
    rankjie
        4
    rankjie  
       2015-02-12 13:16:16 +08:00
    把 app.use(bodyParser.json()); 放到 app.use(bodyParser.urlencoded({extended:true})) 上面试试吧...
    rankjie
        5
    rankjie  
       2015-02-12 13:17:40 +08:00   ❤️ 1
    异步通知的数据是POST过来的,没有写在URL里。你取query能取到个蛋啊。。。都在body里啊。
    lifesurge
        6
    lifesurge  
    OP
       2015-02-12 13:40:13 +08:00
    @rankjie 取到啦,太感谢你了
    aki_xavier
        7
    aki_xavier  
       2015-02-12 14:06:54 +08:00
    content-type的这种写法本身是没问题的,bodyparser这个plugin不认也没办法
    jinwyp
        8
    jinwyp  
       2015-07-02 15:42:42 +08:00
    非常感谢 解决了这个问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1376 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:46 · PVG 07:46 · LAX 16:46 · JFK 19:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.