PHP cURL Request for Web Service Returning Error

655 views Asked by At

I continue to receive the error: "Failed to de-serialize entity" when making the REST request below. I'm assuming it has to do with the formatting of my json, but can't for the life of me figure it out. Any help would be much appreciated.

//LOGIN
//Set the url for login
$url = $urlRoot . "/session";

//Build the resource request
$params = array("encryptedPassword" => false, "indentifier" => $userName, "password" => $password);

//JSON encode parameters
$jsonParams = json_encode($params) ;

//Set up the curl resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json; charset=UTF-8",
    "Accept: application/json; charset=UTF-8", 
    "X-IG-API-KEY: ".$apiKey,
    "Version: 1"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonParams);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //**NB delete this line for production

$result = curl_exec($ch);

//Output login response - includes the header
echo($result) . PHP_EOL;

//Close curl resource to free up system resources
curl_close($ch);

Heres's a link that further details the resource that I'm trying to consume https://labs.ig.com/rest-trading-api-reference/service-detail?id=124

I tried successfully to consume the service in pure JS alone. Perhaps contrasting the code will make my error in PHP obvious to someone.

function login() {

   // Get username and password from user interface fields
   apiKey = $("#apikey").val();
   var identifier = $("#username").val();
   var password = $("#password").val();

   if (apiKey=="" || identifier=="" || password=="") {
       return false;
   }

   password = encryptedPassword(password);
   console.log("Encrypted password " + password);

   // Create a login request, ie a POST request to /session
   var req = new Request();
   req.method = "POST";
   req.url = urlRoot + "/session";

   // Set up standard request headers, i.e. the api key, the request content type (JSON), 
   // and the expected response content type (JSON)
   req.headers = {
      "Content-Type": "application/json; charset=UTF-8",
      "Accept": "application/json; charset=UTF-8",
      "X-IG-API-KEY": apiKey,
      "Version": "2"
   };

   // Set up the request body with the user identifier (username) and password
   var bodyParams = {};
   bodyParams["identifier"] = identifier;
   bodyParams["password"] = password;
   bodyParams["encryptedPassword"] = true;
   req.body = JSON.stringify(bodyParams);

   // Prettify the request for display purposes only
   $("#request_data").text(js_beautify(req.body) || "");

   // Send the request via a Javascript AJAX call
   try {
      $.ajax({
         type: req.method,
         url: req.url,
         data: req.body,
         headers: req.headers,
         async: false,
         mimeType: req.binary ? 'text/plain; charset=x-user-defined' : null,
         success: function (response, status, data) {

            // Successful login 
            // Extract account and client session tokens, active account id, and the Lightstreamer endpoint,
            // as these will be required for subsequent requests
            account_token = data.getResponseHeader("X-SECURITY-TOKEN");
            console.log("X-SECURITY-TOKEN: " + account_token);
            client_token = data.getResponseHeader("CST");
            console.log("CST: " + client_token);
            accountId = response.currentAccountId;
            lsEndpoint = response.lightstreamerEndpoint;

            // Prettify response for display purposes only
            $("#response_data").text(js_beautify(data.responseText) || "");

            // Show logged in status message on screen
            $("#loginStatus").css("color", "green").text("Logged in as " + accountId);
         },
         error: function (response, status, error) {

            // Login failed, usually because the login id and password aren't correct
            handleHTTPError(response);
         }
      });
   } catch (e) {
      handleException(e);
   }

    return true;

}
1

There are 1 answers

1
MonkeyZeus On

JSON is versioned. You will have to make sure that the version you are encoding with can be decoded on the other side.

Below is the output of phpinfo(); on my PHP 5.6.3 install:

enter image description here

There are also various JSON validation sites like this one: http://jsonlint.com/