oauth 2.0 – PHP Discord OAUTH2 code sample not working – Stack Overflow


Please see CONTRIBUTING for details.


A psr/log-compliant logging library is also required. We recommend monolog which will be used in examples.


The MIT License (MIT). Please see License File for more information.

Managing scopes

When creating your Discord authorization URL in Step 1, you can specify the state and scopes your application may authorize.

$options = [
    'scope' => ['identify', 'email', '...'] // array or string

$authorizationUrl = $provider->getAuthorizationUrl($options);

If neither are defined, the provider will utilize internal defaults.

At the time of authoring this documentation, the following scopes are available:

Php discord oauth2 code sample not working

So this code I found below doesn’t work I get to the authenticate screen then when t redirects me it just says Not logged in, Login in again. Does anyone know what I have to do to fix this? I am not very good at OATH2 and would like someone to walk me through.

I used the code from this gist.

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)


define('OAUTH2_CLIENT_ID', '1234567890');
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode');

$authorizeURL = 'https://discord.com/api/oauth2/authorize';
$tokenURL = 'https://discord.com/api/oauth2/token';
$apiURLBase = 'https://discord.com/api/users/@me';


// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {

  $params = array(
    'client_id' => OAUTH2_CLIENT_ID,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'response_type' => 'code',
    'scope' => 'identify guilds'

  // Redirect the user to Discord's authorization page
  header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));

// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {

  // Exchange the auth code for a token
  $token = apiRequest($tokenURL, array(
    "grant_type" => "authorization_code",
    'client_id' => OAUTH2_CLIENT_ID,
    'client_secret' => OAUTH2_CLIENT_SECRET,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'code' => get('code')
  $logout_token = $token->access_token;
  $_SESSION['access_token'] = $token->access_token;

  header('Location: ' . $_SERVER['PHP_SELF']);

if(session('access_token')) {
  $user = apiRequest($apiURLBase);

  echo '<h3>Logged In</h3>';
  echo '<h4>Welcome, ' . $user->username . '</h4>';
  echo '<pre>';
  echo '</pre>';

} else {
  echo '<h3>Not logged in</h3>';
  echo '<p><a href="?action=login">Log In</a></p>';

if(get('action') == 'logout') {
  // This must to logout you, but it didn't worked(

  $params = array(
    'access_token' => $logout_token

  // Redirect the user to Discord's revoke page
  header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);

  $response = curl_exec($ch);

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

  $headers[] = 'Accept: application/json';

    $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) {
  return array_key_exists($key, $_GET) ? $_GET[$key] : $default;

function session($key, $default=NULL) {
  return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;


EDIT: Basically in the if statement it doesn’t go into the logged-in part.

Refreshing a token

You can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse the fresh token from your data store to request a refresh:

// create $provider as in the initial example$existingAccessToken = getAccessTokenFromYourDataStore();

if ($existingAccessToken->hasExpired()) {
    $newAccessToken = $provider->getAccessToken('refresh_token', [
        'refresh_token' => $existingAccessToken->getRefreshToken()

    // Purge old access token and store new access token to your data store.


The following versions of PHP are supported.

Похожее:  Почему не приходят смс сообщения с кодом подтверждения Госуслуги

Sample authorization code flow

This self-contained example:


$ ./vendor/bin/parallel-lint src test
$ ./vendor/bin/phpcs src --standard=psr2 -sp
$ ./vendor/bin/phpunit --coverage-text


All request methods have the same footprint:

$http->get(string $url, $content = null, array $headers = []);
$http->post(string $url, $content = null, array $headers = []);
$http->put(string $url, $content = null, array $headers = []);
$http->patch(string $url, $content = null, array $headers = []);
$http->delete(string $url, $content = null, array $headers = []);

For other methods:

All methods return the decoded JSON response in an object:

Most Discord endpoints are provided in the Endpoint.php class as constants. Parameters start with a colon,
e.g. channels/:channel_id/messages/:message_id. You can bind parameters to then with the same class:

It is recommended that if the endpoint contains parameters you use the Endpoint::bind() function to sort requests into their correct rate limit buckets.
For an example, see DiscordPHP.

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *