Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

manny1979's avatar

cURL request to Laravel Http Client

I am trying to convert a curl request to laravel http client. For some reason I am getting a 403 response where as I get a 200 with curl.

This is the code I am working with:

$payload = json_encode(['token' => $token]);

$encoded = base64_encode($userId . ':' . $userKey);
$authHeader = ['Authorization: Basic ' . $encoded];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . 'order/confirm');
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $authHeader);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$curl_response = curl_exec($ch);
$curl_response = json_decode($curl_response);

return json_encode($curl_response);

And this is its equivalent I hope with the Laravel's new HTTP client:

$encoded = base64_encode($userId . ':' . $userKey);
$authHeader = ['Authorization: Basic ' . $encoded];

$response = Http::withHeaders($authHeader)
     ->withOptions([
            'debug' => config('app.env'),
    ])
     ->post($url . 'order/confirm', ['token' => $token])

return $response->throw()->json();

Any ideas as to why I may be getting a 403 with Laravel's Http Client when I am getting 200 with curl?

Thank you...

0 likes
2 replies
manny1979's avatar
manny1979
OP
Best Answer
Level 1

Fixed my own issue. Modified the code a bit and and used the withToken method. To get around my 403 issue, I set the token type to null as by default, it uses Bearer where as mine was Basic.

$encoded = base64_encode($userId . ':' . $userKey);
$authHeader = ['Basic ' . $encoded];

$response = Http:withHeaders([
                'accept' => 'application/json'
            ])
     ->withToken($authHeader, null)
     ->withOptions([
            'debug' => config('app.env'),
    ])
     ->post($url . 'order/confirm', ['token' => $token])

return $response->throw()->json();

That fixed the issue for me.

Please or to participate in this conversation.