0

I am trying to connect to an API which is based on JSON-RPC 2.0. As i am new to this im not sure if im coding this correctly because all I am recieving is an error.

Can anyone give me a brief explanation on how to connect to API in PHP?

<?php
 header('Content-Type: application/json');
 //check if you have curl loaded
 if(!function_exists("curl_init")) die("cURL extension is not installed");

 $url = 'xxxxxxxxx';

$data = array(
"operator_id" => "xxxx",
"login"       => "xxxx",
"password"    => "xxxx",
);

$curl_options = array(
     CURLOPT_URL => $url,
     CURLOPT_HEADER => 0,
     CURLOPT_NOBODY => true,
     CURLOPT_POSTFIELDS => $data,
     CURLOPT_RETURNTRANSFER => TRUE,
     CURLOPT_TIMEOUT => 0,
     CURLOPT_SSL_VERIFYPEER => 0,
     CURLOPT_FOLLOWLOCATION => TRUE,
     CURLOPT_ENCODING => 'gzip,deflate',
     CURLINFO_HEADER_OUT    => true,
);

$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$output = curl_exec($ch);
curl_close($ch);

$arr = json_decode($output,true);
echo ($output);
?>

The response i am recieving is this: {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":null}

The response i should be recieving if successful login is: {"jsonrpc":"2.0","result":true,"error":null,"id":1,"ts":1368533487}

Yaseen AS
  • 3
  • 3

1 Answers1

4

You're not sending a JSON-RPC request at all.

The request must be a JSON body, so you must json_encode the data before passing it to CURLOPT_POSTFIELDS.

The posted json must have the keys method, params, id, and jsonrpc (the last should be set to "2.0"). Your data would go into params. The id can be set to whatever, but without it you shouldn't get a response at all.

It is a quite simple format. See the specification at http://www.jsonrpc.org/specification

fiddur
  • 1,768
  • 15
  • 11
  • Thanks mate! Ive just realised what i was trying to sent... Im not getting the correct response! Cheers again. – Yaseen AS Sep 30 '15 at 09:30