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?