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

mikromike's avatar

how to convert javascript btoa(string) to laravel http client format?

hello

I tried to convert curl request to laravel 10 http client format.

 curl -X POST -d "grant_type=client_credentials" -d "scope=connect.api.read connect.api.write" 
  -u "{client_id}:{client_secret}"
  https://api.connect.domain.com/as/token.oauth2 

to 		

 $basic_data = config('services.elements.clientID'). ':' . config('services.elements.secretID');


    $basic = base64_encode($basic_data);
    $response = Http::
    withHeaders([
       'Authorization' => 'Basic ' .$basic,
       'content-type'=> 'application/x-www-form-urlencoded'
     ])
    ->post('https://api.connect.domain.com/as/token.oauth2',[
        'grant_type'=>'client_credentials',
        'scope'=>'connect.api.read'
    ]);


    dd($response);

-- Api documentation gives example in Javascript:

 const client = '...' // client id;
 const secret = '...' // secret value
const basic = btoa(`${client}:${secret}`);
const opts = {
  headers: {
   'Authorization': `Basic ${basic}`,
   'user-agent': 'NodeJs',
   'Content-type': 'application/x-www-form-urlencoded'
   },
  method: 'POST'
 };

Question: javascript

   const basic = btoa(`${client}:${secret}`); is it same as 

   $basic_data = config('services.elements.clientID'). ':' . config('services.elements.secretID');
    $basic = base64_encode($basic_data);   ??

--> Api gives me error " 400" ?

     reasonPhrase: "Bad Request"
    -statusCode: 400.

Thanks Mika.

0 likes
9 replies
Snapey's avatar

have you tried dd on the request?

$response = Http::
    withHeaders([
       'Authorization' => 'Basic ' .$basic,
       'content-type'=> 'application/x-www-form-urlencoded'
     ])
    ->dd()
    ->post('https://api.connect.domain.com/as/token.oauth2',[
        'grant_type'=>'client_credentials',
        'scope'=>'connect.api.read'
    ]);
mikromike's avatar

@Snapey, yes. But I tried to figure out how to use base64_encode, because they give example as javascript

  const basic = btoa(`${client}:${secret}`);

and this is not 'application/json but 'application/x-www-form-urlencoded',

maybe I have to do different way

  Http::withHeaders([])

I am stuck.....

Snapey's avatar

ok, I see one difference

You are base64 encoding the : in the Authorization string

try

$clientId = base64_encode(config('services.elements.clientID'));
$clientSecret = base64_encode(config('services.elements.secretID'));

    $response = Http::
    withHeaders([
       'Authorization' => "Basic {$clientId}:{$clientSecret}",
       'content-type'=> 'application/x-www-form-urlencoded'
     ])
    ->post('https://api.connect.domain.com/as/token.oauth2',[
        'grant_type'=>'client_credentials',
        'scope'=>'connect.api.read'
    ]);
mikromike's avatar

@Snapey,

    const client = '...' // client id;
    const secret = '...' // secret value
    const basic = btoa(`${client}:${secret}`);
  • Do they base_encode semicolon ?
mikromike's avatar

This is how they show example in Javascript:

                      const req = https.request(url, opts, (r) => {
                                             let raw = '';
                                           r.on('data', (d) =>  { raw += d; });  

	<---- ???? What is that data?
	in Laravel http client: is it that header array ????


                                          r.on('end', () => { console.log(raw); });
                                     });

-- These two line need to be inside body ---

                              req.write('grant_type=client_credentials');
                            req.write('scope=connect.api.read');
                     req.end();
Snapey's avatar

@mikromike yes. I guess so.

You sure your config ID and secret are not already encoded as base64?

Snapey's avatar
Snapey
Best Answer
Level 122

I think you are missing ->asForm() on your request so that the data is correctly encoded.

https://laravel.com/docs/10.x/http-client#sending-form-url-encoded-requests

Your original Authorization was ok. However, Laravel can handle that for you also https://laravel.com/docs/10.x/http-client#authentication

 $response = Http::asForm()
	->withBasicAuth(config('services.elements.clientID'), config('services.elements.secretID'))
    ->post('https://api.connect.domain.com/as/token.oauth2',[
        'grant_type'=>'client_credentials',
        'scope'=>'connect.api.read'
    ]);

Please or to participate in this conversation.