NodeJS Https.request issue

Viewed 57

I am trying to write a test post to the Zip API:

Zip Api

JSON posted, as per Zip Pay's example -

{
  "shopper": {
    "title": "Mr",
    "first_name": "John",
    "last_name": "Smith",
    "middle_name": "Joe",
    "phone": "0400000000",
    "email": "test@emailaddress.com",
    "birth_date": "2017-10-10",
    "gender": "Male",
    "statistics": {
      "account_created": "2015-09-09T19:58:47.697Z",
      "sales_total_number": 2,
      "sales_total_amount": 450,
      "sales_avg_value": 250,
      "sales_max_value": 350,
      "refunds_total_amount": 0,
      "previous_chargeback": false,
      "currency": "AUD"
    },
    "billing_address": {
      "line1": "10 Test st",
      "city": "Sydney",
      "state": "NSW",
      "postal_code": "2000",
      "country": "AU"
    }
  },
  "order": {
    "reference": "testcheckout1",
    "amount": 200,
    "currency": "AUD",
    "shipping": {
      "pickup": false,
      "tracking": {
        "uri": "http://tracking.com?code=CBX-343",
        "number": "CBX-343",
        "carrier": "tracking.com"
      },
      "address": {
        "line1": "10 Test st",
        "city": "Sydney",
        "state": "NSW",
        "postal_code": "2000",
        "country": "AU"
      }
    },
    "items": [
      {
        "name": "Awesome shoes",
        "amount": 200,
        "quantity": 1,
        "type": "sku",
        "reference": "1"
      }
    ]
  },
  "config": {
    "redirect_uri": "http://www.redirectsuccess.com/zipmoney/approved"
  },
  "metadata": {
    "name1": "value1"
  }
}

but I am getting an error message:

{"error":{"code":"request_invalid","message":"There are errors with the request, please see error items for more detail","details":[{"name":"Amount","message":"'Amount' must be greater than '0'."},{"name":"Currency","message":"Currency must be either 'AUD' or 'NZD'"},{"name":"Authority","message":"'Authority' must not be empty."}]}}

Cant figure out what is wrong. These elements exist in the data sent. Have used Axios and the request comes back fine. But Node's HTTPS object doesnt work. Why? :(

TIA

           const postData = JSON.stringify(data);
            

           let options = {
                "host": 'api.sandbox.zipmoney.com.au',
                "path": '/merchant/v1/charges',
                "method": 'POST',
                "port": 443,
                "encoding": "utf8",
                "headers": {
                    'Authorization': 'Bearer test',
                    'Content-Type': 'application/json',
                    'Content-Length': postData.length,
                    'Zip-Version': '2017-03-01'
                }
              };
    
            const req = https.request(options, (response)=>{
                console.log(`statusCode: ${response.statusCode}`)
                var str = ''
    
                response.on('data', function (chunk) {
                    str += chunk;
                });
              
                response.on('end', function () {
                    console.log("have end data")
    
                  console.log(str);
                });
    
            })
    
            req.on('error', error => {
                console.log("zip errors...")
                console.error(error)
            })
            
            req.write(postData)
            req.end();
1 Answers

I had some time to take another look at your question, today, but still haven't found a definite solution to your specific issue. While this post may not answer your question, I wanted to post my findings here.

Here is the code that I tried (based on your code) on my side using a different test API:

// ref: https://stackoverflow.com/q/66218603/1167750
// ref: https://attacomsian.com/blog/node-http-post-request
const https = require('https');

let data = {
  "title": "test",
  "body": "Content",
  "userId": 1
}

const postData = JSON.stringify(data);

let options = {
  "host": 'jsonplaceholder.typicode.com',
  "path": '/posts',
  "method": 'POST',
  "port": 443,
  "encoding": "utf8",
  "headers": {
    'Content-Type': 'application/json',
    'Content-Length': postData.length,
    'Zip-Version': '2017-03-01'
  }
};

const req = https.request(options, (response)=>{
    console.log(`statusCode: ${response.statusCode}`)
    var str = ''

    response.on('data', function (chunk) {
        str += chunk;
    });

    response.on('end', function () {
        console.log("have end data")

      console.log(str);
    });

})

req.on('error', error => {
    console.log("zip errors...")
    console.error(error)
})

req.write(postData)
req.end();

When I run this with Node, I get the output:

$ node test.js
statusCode: 201
have end data
{
  "title": "test",
  "body": "Content",
  "userId": 1,
  "id": 101
}

So I'm able to get a normal response back from this other API while using a lot of your code from your post. This seems to show that your approach with using Node's https module works for another API at least. Maybe this can help you narrow down where the issue is based on this test information.

Additionally, from your example json data, I don't see a place where the Authority field is filled out in your request. The error message you got indicated that it was required and the related documentation seems to require that too. But maybe this was simply removed from your json data before it was posted in your question for security reasons?

Seeing that you do have the amount and currency values set in your json order data, that seems to indicate that the API is not recognizing your json data that is being sent. But hearing that the axios approach works makes this issue still confusing.

Though it might not be necessary, I also checked your json data in a linter and it came back as valid (as you already know). Wanted to double check if there was some issue related to that, though.

Related