我正在尝试验证使用Node.js和Express从TrialPay发送的消息。 TrialPay使用HMAC-MD5哈希对请求进行签名,并在验证时提供these instructions

这是我的代码:

app.post('/trialpay', function(req, res) {

    var key = "[MY MERCHANT KEY]";
    var hash = req.header("TrialPay-HMAC-MD5");
    var data = req.body.toString();

    var crypted = require("crypto").createHmac("md5", key)
        .update(data)
        .digest("hex");

    if (hash == crypted) {
        res.writeHead(200, {"Content-Type": "plain/text"});
        res.end("Success!");
    } else {
        throw new Error("Invalid TrialPay Hash");
    }
});

显然,这是行不通的(哈希不匹配)。

免责声明:首先,我对Node.js并不陌生,并且几乎没有JavaScript经验。

更新

我没有意识到该链接受到保护。



这是TrialPay如何指示您在Google App Engine(Python)中进行验证的示例:
class MyHandler(webapp.RequestHandler):
  def post(self):
  key = '[YOUR MERCHANT KEY]'
  tphash = self.request.headers['TrialPay-HMAC-MD5']
  if hmacmd5(key,self.request.body) != tphash:
    logging.info('invalid trialpay hash')
    return

更新2
req.body打印为:
{
  oid: 'sample-order-id',
  sid: 'customer-sid',
  order_date: '04/24/2012',
  timestamp: '04/24/2012 16:28:46',
  first_name: 'customer-firstname',
  last_name: 'customer-lastname',
  email: '[email protected]',
  revenue: '10.00',
  zip_code: '94041',
  country: 'US'
}

最佳答案

这应该可以解决问题:

var crypto = require('crypto');

function calculateSignature(key) {
    return function(req, res, next) {
        var hash = req.header("TrialPay-HMAC-MD5"),
            hmac = crypto.createHmac("md5", key);

        req.on("data", function(data) {
            hmac.update(data);
        });

        req.on("end", function() {
            var crypted = hmac.digest("hex");

            if(crypted === hash) {
                // Valid request
                return res.send("Success!", { "Content-Type": "text/plain" });
            } else {
                // Invalid request
                return res.send("Invalid TrialPay hash", { "Content-Type": "text/plain" }, 403);
            }
        });

        req.on("error", function(err) {
            return next(err);
        });
    }
}

app.post("/trialpay", calculateSignature("[MY MERCHANT KEY]"));

10-04 17:20