问题
I am making a program using the Twitch API that involves getting a user's username and OAuth token. Currently my website has a "Connect with Twitch" button, which will allow the user to sign into twitch and return an access token (as a GET request to my URL) I can use to contact the API and get an OAuth token. This is the code I have for that part:
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if (isset($_GET['code']) && !empty($_GET['code'])) {
$code = $_GET['code'];
//Getting OAuth
$params = array(
'client_id' => 'my_client_id',
'client_secret' => 'my_client_secret',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://mytwitchapp.com/register.php', //Not my actual url
'code' => $code
);
$oauthResult = post_url_contents("https://api.twitch.tv/kraken/oauth2/token", $params);
$json_decoded_oauthResult = json_decode($oauthResult, true);
$oauth = $json_decoded_oauthResult['access_token'];
}
}
This is the post_url_contents() function I use:
function post_url_contents($url, $fields) {
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//SSL certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/cert/DigiCertGlobalRootCA.crt");
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
The above code works fine to get the OAuth key. I have tried submitting the $params
array to https://api.twitch.tv/kraken/
, which I have read should provide top-level statistics about the user, but the response I get is You are being redirected
("redirected" is a hyperlink to http://twitch.tv/kraken).
Any help is greatly appreciated!
回答1:
So after a lot of messing around, I have figured out how to do it (rather simple, it turns out).
Below the code in my first snippet, I have the following:
//Getting username
$usernameResult = file_get_contents("https://api.twitch.tv/kraken?oauth_token=" . $oauth);
$json_decoded_usernameResult = json_decode($usernameResult, true);
echo $username = $json_decoded_usernameResult['token']['user_name'];
Since I only need to send this information as a GET method instead of POST, I can just use file_get_contents()
and append on the OAuth key to the end of the URL. After that, its just going through the returned data to get the username.
来源:https://stackoverflow.com/questions/25251377/get-username-from-twitch-api-using-authorization-code-flow-php