How to retrieve OAuth token from Twitch API

I’m working on a project that needs to get an OAuth token from Twitch’s API. After the user logs in through Twitch, they get sent back to my site with a code parameter in the URL.

Here’s what I’m trying to do:

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

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

My token function looks like this:

function fetch_token($auth_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' => $auth_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 problem is that nothing comes back from this function. It just returns empty. Has anyone run into this before? What could be going wrong here?

Had the same problem - it’s probably your error handling. You’re assuming the JSON always has an access_token, but failed requests return null or error responses instead. Debug it first: dump the raw $result and $json_data to see what Twitch is actually sending back. Also set your Content-Type header to application/x-www-form-urlencoded since you’re posting form data. Without error checking, you can’t tell if it’s a network issue, bad credentials, or malformed request causing the empty response.

Double-check your callback_url matches exactly what’s in your Twitch dev console. Even one extra slash or wrong protocol (http vs https) breaks it silently. Try adding curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false) for testing - SSL issues cause this all the time.