Skip to content
Advertisement

Making Curl to PHP request json rpc

I am trying to connect to Electroneum wallet rpc. The example Curl request is:-

 curl  -u user:pass --digest  -X POST http://127.0.0.1:8050/json_rpc  -d '{"jsonrpc":"2.0","id":"0","method":"'getaddress'","params":{}}'  -H 'Content-Type: application/json'

Which works perfectly fine on machine side. But when I try PHP like this

 $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:8050/json_rpc");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
    curl_setopt($ch, CURLOPT_USERPWD, "user" . ":" . "pass");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "{"jsonrpc":"2.0","id":"0","method":"getaddress'","params":{}}'");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
    curl_close($ch);
  print_r($response);

It returns { "error": { "code": -32601, "message": "Method not found" }, "id": "0", "jsonrpc": "2.0" }. I don’t know why it’s not working, maybe due to –digest. Help needed

Advertisement

Answer

You forgot to remove a single quote in your method name in your request options:

curl_setopt($ch, CURLOPT_POSTFIELDS, "{"jsonrpc":"2.0","id":"0","method":"getaddress'","params":{}}'");

should be:

curl_setopt($ch, CURLOPT_POSTFIELDS, "{"jsonrpc":"2.0","id":"0","method":"getaddress","params":{}}'");

But anyway, if you plan to do multiple different calls to their JSON-RPC API, I would advise you to use a client library that does all the JSON-RPC protocol handling for you, for example jsonrpc/jsonrpc.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement