Hey everyone, I’m stuck with Twitch API authentication in PHP and could really use some help.
I’m trying to build a simple app that fetches user data from Twitch, but I keep running into authentication issues. The OAuth flow seems straightforward in the documentation, but my implementation isn’t working.
Here’s my first attempt at getting the authorization:
$client_id = 'my_app_client_id';
$redirect_url = 'http://localhost/twitch/callback.php';
$auth_url = 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=' . $client_id . '&redirect_uri=' . $redirect_url . '&scope=user_read';
$response = json_decode(file_get_contents($auth_url), true);
var_dump($response); // prints null
$access_key = $response['access_token'];
echo $access_key; // obviously nothing here
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, 'Authorization: OAuth ' . $access_key);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
$final_result = json_decode($output, true);
print_r($final_result);
That didn’t work at all, so I found another approach online:
$curl_handle = curl_init('https://api.twitch.tv/kraken/oauth2/token');
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
$params = array(
'client_id' => 'my_correct_client_id',
'client_secret' => 'my_correct_secret',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/twitch/callback.php',
'code' => $_GET['code']
);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($curl_handle);
$decoded_response = json_decode($result, true);
$token = $decoded_response['access_token'];
echo $token;
function fetch_api_data($endpoint) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$user_info = json_decode(fetch_api_data('https://api.twitch.tv/kraken/user?oauth_token=' . $token . '&client_id=' . $params['client_id']));
print_r($user_info);
This second approach gets me a 401 Unauthorized error. I’m pretty sure my client ID and secret are correct since I copied them directly from my Twitch developer console.
Could the issue be that I’m testing on localhost? Has anyone successfully implemented Twitch OAuth with PHP? Any guidance would be really appreciated.