How to retrieve OAuth token from Twitch API

I’m working on a Twitch integration and having trouble getting the OAuth token after user authorization. When users authenticate through Twitch, they get redirected back to my site with a code parameter, but my token request isn’t working.

Here’s my current setup:

<?php
   $auth_code = $_GET['code'];
   $token = $oauth_handler->fetch_token($auth_code);
   $username = $oauth_handler->get_user_info($token);

   if(isset($username)) {
      echo 'Welcome ' . $username . '! Login successful!';
   } else {
      echo 'Login failed!';
   }
?>

My token retrieval function looks like this:

function fetch_token($authorization_code) {
    $curl = curl_init($this->api_url . "oauth2/token");
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_POST, 1);
    $params = array(
        'client_id' => $this->app_id,
        'client_secret' => $this->app_secret,
        'grant_type' => 'authorization_code',
        'redirect_uri' => $this->callback_url,
        'code' => $authorization_code
    );
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $result = curl_exec($curl);
    $json_data = json_decode($result, true);
    return $json_data["access_token"];
}

The function doesn’t return anything and I can’t figure out why. Has anyone encountered this issue before?

I experienced similar issues with obtaining an OAuth token from Twitch. It often boils down to how your server handles errors. In your fetch_token function, ensure you’re capturing and logging any errors that may occur. For example, after executing the curl call, include error handling as follows:

$result = curl_exec($curl);
if ($result === false) {
    error_log('cURL Error: ' . curl_error($curl));
}
error_log('Twitch Response: ' . $result);
$json_data = json_decode($result, true);

Additionally, double-check that your redirect_uri is correctly set up in the Twitch developer portal, as mismatches can lead to failures. Auth codes also have a short lifespan, so be sure to promptly exchange them for tokens.