Using Laravel to query an API not working – cURL is working fine

  curl, laravel, php

I am trying to post the below as content-type application/x-www-form-urlencoded using Laravels Http Client:

$params = [
      'client_secret'   => config('client_secret'),
      'client_id'   => config('client_id'),
      'grant_type' => 'client_credentials',
      'scope' => 'authorization:grant'
];

$url = "https://api.example.org/api/v1/oauth/token";
$post = Http::asForm()->post($url, $params);

However, this returns a GuzzleHttp response, with the status 400 Bad Request.

Trying the same request with cURL is working just fine:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => 'client_secret=xxxxxxxxxxx&client_id=xxxxxxxxxx&grant_type=client_credentials&scope=user%3Acreate%2C%20authorization%3Agrant',
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/x-www-form-urlencoded'
    ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

The above cURL command successfully returns a 200 response from the API.

What am I doing wrong?

Source: Laravel

Leave a Reply