将卷曲请求转换为Node.JS服务器 - 将数据附加到请求?

时间:2014-11-02 02:16:20

标签: node.js curl https

我正在学习如何处理信用卡付款。以下是测试CURL ...

 curl -k -v -X POST -H "Content-Type:application/json" -H "Authorization: Basic Mxxxxxxxxxxxxxxxxxx=" -d "@json_file.txt" -o output.txt https://w1.xxxxxxxxxxxx.net/PaymentsAPI/Credit/Sale

json_file.txt包含

{
    "InvoiceNo":"1",
    "RefNo":"1",
    "Memo":"TEST_TEST_PHONY",
    "Purchase":"1.00",
    "AccountSource":"Swiped",
    "AcctNo":"5xxxxxxxxxxxxxxxxx1",
    "ExpDate":"0816",
    "OperatorID":"xxxxxxxxxx",
}

我转换为节点模块HTTPS

var https = require("https");

var options = {
    host: 'w1.xxxxxxxxxxxxxx.net',
    port: 443,
    path: '/PaymentsAPI/Credit/Sale',
    headers: { "Content-Type" :"application/json", 
    "Authorization" : "Basic Mxxxxxxxxxxxxxxxxxxxxxxxxxxx="} ,
    data: {
    "InvoiceNo":"1",
    "RefNo":"1",
    "Memo":"xxxxxxxxxxxxxxx",
    "Purchase":"1.00",
    "AccountSource":"Swiped",
    "AcctNo":"5xxxxxxxxxxxxxxxxx1",
    "ExpDate":"0816",
    "OperatorID":"xxxxxxxxxxxx",
    },
  method: 'POST'  
};

// oops...  400 Bad Request
// The request could not be understood by the server due to malformed syntax. 

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk.toString() );
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

问题出在原始curl请求上,JSON文本文件中包含的数据作为POST附件提交。卷曲请求工作正常。另一方面,我不清楚如何从node.js服务器那样做。响应标头返回正常,但我收到400响应(语法格式错误)。有人知道如何将JSON数据作为附件发送到HTTPS请求吗?

1 个答案:

答案 0 :(得分:1)

糟糕。我完全不了解req.write()的工作原理。这段代码很成功。感谢Dan Ourada @ Mercury Payments的帮助。注意,这里的所有代码都是纯沙盒。没有真正的买入买入。

var https = require("https");

var options = {
  host: 'w1.mercurycert.net',
  port: '443',
  path: '/PaymentsAPI/Credit/Sale',
  headers: { "Content-Type" :"application/json", "Authorization" : "Basic MDAzNTAzOTAyOTEzMTA1Onh5eg=="},
  method: 'POST'  
};

var inputdata = JSON.stringify( {
    "InvoiceNo":"1",
    "RefNo":"1",
    "Memo":"XXXXX",
    "Purchase":"1.00",
    "AccountSource":"Swiped",
    "AcctNo":"5499990123456781",
    "ExpDate":"0816",
    "OperatorID":"money2020",
  } );

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('Return info: ' + chunk);   // output the return raw data
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// attach input data to request body
req.write(inputdata);
req.end();

此处提供的信息,以防任何其他人卡住从CURL命令转换到Node.js http请求...

嘿,在玩完这个之后,我很惊讶将真实(和安全)支付系统整合到任何商家网站是多么的容易。 (显然需要Https网站。)