'Can't get Discord's username with PHP, oauth2 and cURL [duplicate]
My problem:
I would like to get the discord's username of a person when they have accepted it(with PHP). For that to happen, I created an HTML <a> that redirects users to the oauth2 Discord page when they have clicked on it. After they accepted, it returns me a code with a GET request.
And here is the problem. I have the code, but I didn't succeed in getting the person's username.
My code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)
error_reporting(E_ALL);
$tokenURL = 'https://discord.com/api/oauth2/token';
session_start();
// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {
echo get('code'); // Output the correct code
// Exchange the auth code for a token
$token = apiRequest($tokenURL, array(
"grant_type" => "authorization_code",
'client_id' =>'the_client_id',// It's not written 'the_client_id' but the real code
'client_secret' => 'the_client_secret',// It's not written 'the_client_secret' but the real client secret code
'code' => get('code')
));
$_SESSION['access_token'] = $token->access_token;
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if(session('access_token'))
$headers[] = 'Authorization: Bearer ' . session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function get($key, $default=NULL) { // Get the $key properly
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
?>
What is the problem that I have?
The problem is that the $token is null.
So, I tried to see why is it null, and it's null because:
$response = curl_exec($ch); is false
So I checked in my php.ini and with phpinfo() that cURL was enabled, and it is. So I don't know where is the problem
I also checked that my client_secret code was correct by resetting it, so I don't think that it is the problem.
There is some similars questions like:
Setting up a Discord oauth2 login on my website (with PHP?)
PHP Discord OAUTH2 code sample not working
But this is not the same problem. So don't put this question as [DUPLICATE] please
(I knew that was going to happend, but I reiterate what I said, it's not duplicated)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
