Setting up a Discord oauth2 login on my website (with PHP?)

16,078

Solution 1

Try this

Credits to: eslachance

<?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);

define('OAUTH2_CLIENT_ID', '1234567890'); //Your client Id
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode'); //Your secret client code

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

session_start();

// 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));
  die();
}


// 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>';
    print_r($user);
  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));
  die();
}

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

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

?>

Solution 2

You have the code which is used to authenticate with many endpoints of the discord API. You need the http://discordapp.com/api/users/@me Endpoint. You authenticate with the Authorization Header. Take a look at the Developer Portal to find out more about your endpoint

Share:
16,078
Finley Sherwood
Author by

Finley Sherwood

Updated on June 04, 2022

Comments

  • Finley Sherwood
    Finley Sherwood almost 2 years

    So I'm having troubles learning how to set up a login through discord on my site. I've been browsing for literally hours and haven't been able to find anything I understand...

    At the moment, I have created the discord application, giving me a client ID and client secret, as well as a link back to my localhost:

    https://discordapp.com/api/oauth2/authorize?client_id=550631359337594881&redirect_uri=http%3A%2F%2Flocalhost&response_type=code&scope=identify

    At the moment I have it set up to redirect from a button to that URL, which then sends me to discord to accept. It then returns me to http://localhost?code=CODE_HERE

    However, I don't know what I am supposed to do with this code. I am trying to set it up so that it will show the person's username with hashtag thing, and their profile picture.

    I am currently using HTML, CSS, JS, and PHP on the site, but I think I might need to use something else, but I don't know how to set that up, or what it is I need. I am running my local server with XAMPP. I'd prefer if it is just PHP, but I'm open to other options.

    Does anyone know how I can convert the code to a username + image?

    Thanks in advance!

  • Minn
    Minn almost 4 years
    Please give credit to the original author of this code.
  • Jonathan J. Pecany
    Jonathan J. Pecany over 3 years
    It doesn't really explain which each part does. It is best to describe what each part does so not to confuse anyone.