Search code examples
phpjsonbasic-authentication

PHP JSON Error when using Basic Authentication


I'm new to PHP and I'm trying to send a JSON request via basic authentication. The server responds with this error:

 object(stdClass)#1 (2) { ["error"]=> object(stdClass)#2 (2) {  
 ["code"]=> int(-32600) ["message"]=> string(44) "expected content type 
 to be application/json" } ["jsonrpc"]=> string(3) "2.0" } 

From the API documentation, here is the request format:

  Request Format:

  {
      "jsonrpc": "2.0",
       "id":1,
       "method": "acct.name.get",
       "params": [
             "QrOxxEE9-fATtgAD" ]
  }

Here is the code...Any help would be great - thanks

 <?php

 $username = "username";
 $password = "password";

 $request = [
    'jsonrpc' => '2.0',
    'id' => 1,
    'method' => 'acct.name.get',
    'params' =>['CA6ph0n7EicnDADS'],
 ];

 $curl_post_data = json_encode($request);

 $service_url = 'https://userapi.voicestar.com/api/jsonrpc/1';
 $curl = curl_init($service_url);
 curl_setopt($curl, CURLOPT_URL, $service_url);
 curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 curl_setopt($curl, CURLOPT_USERPWD,  "username:password");
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_POST, true);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 $curl_response = curl_exec($curl);
 $response = json_decode($curl_response);
 curl_close($curl);

 var_dump($response);

?>

Solution

  • Actually, it's the small things... your JSON/Array is malformed. an extra comma at the end of params might actually be the problem. try the following.

    Malformed arrays will cause json_encode to return a null.

     <?php
    
     $username = "username";
     $password = "password";
    
     $request = [
        'jsonrpc' => '2.0',
        'id'      => 1,
        'method'  => 'acct.name.get',
        'params'  => ['CA6ph0n7EicnDADS']
     ];
    
     $curl_post_data = json_encode($request);
    
     $headers = ['Content-type: application/json'];
    
    
     $service_url = 'https://userapi.voicestar.com/api/jsonrpc/1';
     $curl = curl_init($service_url);
     curl_setopt($curl, CURLOPT_URL, $service_url);
     curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
     curl_setopt($curl, CURLOPT_USERPWD,  "username:password");
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_POST, true);
     curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
     curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     $curl_response = curl_exec($curl);
     $response = json_decode($curl_response);
     curl_close($curl);
    
     var_dump($response);
    
    ?>