authorize.net json return extra characters

非 Y 不嫁゛ 提交于 2019-12-01 19:25:23

I encountered the same issue when developing my library for accessing their JSON API. In the code that handles the response I had to strip those characters out in order to properly decode the string as JSON.

Line 113:

$this->responseJson = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $responseJson);

I'm having the same issue in Node.js with JSON.parse().

var https = require('https');
var requestData = {
  "getCustomerProfileIdsRequest": {
    "merchantAuthentication": {
      "name": "your-auth-name-here",
      "transactionKey": "your-trans-key-name-here"
    }
  }
};
var requestString = JSON.stringify(requestData);
var req = https.request({
  host: "apitest.authorize.net",
  port: "443",
  path: "/xml/v1/request.api",
  method: "POST",
  headers: {
    "Content-Length": requestString.length,
    "Content-Type": "application/json"
  }
});

req.on('response', function (resp) {
  var response = '';

  resp.setEncoding('utf8');
  resp.on('data', function(chunk) {
    response += chunk;
  });
  resp.on('end', function() {
    var buf = new Buffer(response);
    console.log('buf[0]:', buf[0]); // 239 Binary 11101111
    console.log('buf[0] char:', String.fromCharCode(buf[0])); // "ï"
    console.log('buf[1]:', buf[1]); // 187 Binary 10111011
    console.log('buf[1] char:', String.fromCharCode(buf[1])); // "»"
    console.log('buf[2]:', buf[2]); // 191 Binary 10111111
    console.log('buf[2] char:', String.fromCharCode(buf[2])); // "¿"
    console.log('buf[3]:', buf[3]); // 123
    console.log('buf[3] char:', String.fromCharCode(buf[3])); // "{"

    // Note: The first three chars are a "Byte Order Marker" i.e. `BOM`, `ZERO WIDTH NO-BREAK SPACE`, `11101111 10111011 10111111`

    response = JSON.parse(response); // Throws error: 'Unrecoverable exception. Unexpected token SyntaxError: Unexpected token'
    console.log(response);
  });
});
req.on('error', function (error) {
  console.log(JSON.stringify(error));
});

req.on('socket', function(socket) {
  socket.on('secureConnect', function() {
    req.write(requestString);
    req.end();
  });
});

If I call trim() on the response, it works:

response = JSON.parse(response.trim());

Or replace the BOM:

response = response.replace(/^\uFEFF/, '');
response = JSON.parse(response);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!