skip to Main Content

I’m trying to exchange my authorization token for a bearer token. According to the docs it should be a application/x-www-form-urlencoded request. My code looks like this:

$res = Http::withHeaders([
    'Accept'       => 'application/json',
    'Content-Type' => 'application/x-www-form-urlencoded',
    'Cache-Control' => 'no-cache'
])->post('https://open.tiktokapis.com/v2/oauth/token/', [
    'client_id'    => 'my-client-id',
    'client_secret' => 'my-client-secret',
    'code'          => $request->code,
    'grant_type'    => 'authorization_code',
    'redirect_uri'  => 'https://example.com/callback/tiktok',
]);

I keep receiving:

{"error":"invalid_request","error_description":"The request parameters are malformed.","log_id":"20230621065239FB74CE96D69DA40A2B46"}

What could be going on here? Already tried contacting tiktok a week ago but no response.

2

Answers


  1. IlluminateSupportFacadesHttp facade seems to create some problems with the internal protected variable $bodyFormat of IlluminateHttpClientPendingRequest class as it creates the instance of this class internally while making requests.

    You could rather directly use PendingRequest class to make requests like below:

    Snippet:

    <?php
    
    use IlluminateHttpClientPendingRequest; 
    
    $o = new PendingRequest();
    $o->asForm(); // to set content type header to application/x-www-form-urlencoded
    
    $res = $o->post('https://open.tiktokapis.com/v2/oauth/token/', [
      'client_key'    => 'CLIENT_KEY', // your value here
      'client_secret' => 'CLIENT_SECRET', // your value here
      'code'          =>  'CODE', // your value here
      'grant_type'    => 'authorization_code',
      'redirect_uri'  => 'https://example.com/callback/tiktok' // your value here
    ]);
    
    dd($res->body());
    

    Online Demo

    Login or Signup to reply.
  2. I was facing the same issue earlier. I had to encode the body parameters, and after that, it worked. PHP is not my first language, but maybe you can try something like this:

    $res = Http::withHeaders([
        'Accept'       => 'application/json',
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Cache-Control' => 'no-cache'
    ])->post('https://open.tiktokapis.com/v2/oauth/token/', http_build_query([
        'client_key'    => 'my-client-id',
        'client_secret' => 'my-client-secret',
        'code'          => $request->code,
        'grant_type'    => 'authorization_code',
        'redirect_uri'  => 'https://example.com/callback/tiktok',
    ]));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search