ggwp
ggwp

Reputation: 29

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

Upvotes: 1

Views: 2518

Answers (2)

Keinan Goichman
Keinan Goichman

Reputation: 121

There are actually 2 single quote in line 6 that shoud be removed:

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\":{}}");

Please note that on some gateways such as https://cloudflare-eth.com the params list should be written with square brackets and not curly ones:

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

Upvotes: 1

linkboss
linkboss

Reputation: 676

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.

Upvotes: 3

Related Questions