Home > other >  CURL Post request yields in error '{"error":"invalid_request"}' (lengt
CURL Post request yields in error '{"error":"invalid_request"}' (lengt

Time:10-26

CURL Post request yields in error '{"error":"invalid_request"}' (length=27) here is my code

    $url="https://..................."; 
    $authorization=""; //base64 string TE1TQXBpOkxNUContinue...=
    $curl = curl_init();
    $auth_data = array(
      'scope'   => 'LMSApi LMSRead',
      'grant_type'      => 'client_credentials'
    );
    $ops=array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_SSL_VERIFYHOST =>false,
      CURLOPT_SSL_VERIFYPEER => false,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_POSTFIELDS=>$auth_data,
      CURLOPT_HTTPAUTH=> CURLAUTH_BASIC,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_HTTPHEADER => array(
      'Content-Type'=> 'application/x-www-form-urlencode',
      'Authorization'=> 'Basic '.$authorization
      )
    );
    curl_setopt_array($curl,$ops);
    $response = curl_exec($curl);
    var_dump($response);
    curl_close($curl);

when using postman it works but returns always false while using above code. don't know what I am doing wrong.curl_error($ch) results in empty string

help is required

CodePudding user response:

if someone have the same problem, following is the solution.

passing 'grant_type=client_credentials&scope=specify scope' directly to CURLOPT_POSTFIELDS instead of an array solved my problem. the code now looks like as bellow.

$url="https://something.com";   
$headerpost=array(
  'Content-Type: application/x-www-form-urlencoded',
  'Authorization: Basic yourbase64string'
);

 $ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials&scope=LMSApi LMSRead');
curl_setopt($ch, CURLOPT_HTTPHEADER,$headerpost);

$result = curl_exec($ch);
$jsonresult=json_decode($result,true);
curl_close($ch);
  • Related