Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Discord oauth2 example PHP
<?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');
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';
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;
}
?>
@lekovul

This comment has been minimized.

Copy link

@lekovul lekovul commented Jan 12, 2019

I love you.. Thanks!

@MohammedWadee

This comment has been minimized.

Copy link

@MohammedWadee MohammedWadee commented Feb 15, 2019

hello can you solve the problem it's written UNKNOWN EROOR

@crusardri

This comment has been minimized.

Copy link

@crusardri crusardri commented Mar 12, 2019

hello can you solve the problem it's written UNKNOWN EROOR

Check the Redirect URI, put a complete working url
(http(s)://localhost/app)

@crusardri

This comment has been minimized.

Copy link

@crusardri crusardri commented Mar 13, 2019

Aslo @Jengas
To revoke a token, use apiRequest() with params "token", "client_id" and "client_secret"

@everalan10

This comment has been minimized.

Copy link

@everalan10 everalan10 commented Apr 23, 2019

Then, how would be the restricted access to a different URL given? i.e. https://localhost/some-article.php

@shir0xyz

This comment has been minimized.

Copy link

@shir0xyz shir0xyz commented May 8, 2019

How can I make a logout button?

@burtgithub

This comment has been minimized.

Copy link

@burtgithub burtgithub commented May 10, 2019

I love you.. Thanks!

@deyyanl

This comment has been minimized.

Copy link

@deyyanl deyyanl commented May 12, 2019

@everalan10

You can check if the session is started or not. If not, redirect to the login page.

@Daeloth

This comment has been minimized.

Copy link

@Daeloth Daeloth commented May 22, 2019

Where can I get the 'state' I have in the auth url, from my php? I see 'code', but your comment says there should be 'code' and 'state'

@Keyinator

This comment has been minimized.

Copy link

@Keyinator Keyinator commented Jun 21, 2019

Thanks @crusardri
Thanks to you I've got the logout working.
For everyone who may be new and doesn't get it fixed I've uploaded a fork with the logout function implemented: LINK

@Jengas

This comment has been minimized.

Copy link
Owner Author

@Jengas Jengas commented Jun 21, 2019

Thanks @crusardri
Thanks to you I've got the logout working.
For everyone who may be new and doesn't get it fixed I've uploaded a fork with the logout function implemented: LINK

Thanks for correcting my code! Would you allow me to add your code that you have provided with a link to this gist?

@RFlintstone

This comment has been minimized.

Copy link

@RFlintstone RFlintstone commented Jun 24, 2019

How do I get the authorizeURL, tokenURL and apiURLBase from the discord api? It won't log me in yet.

@IIPoliII

This comment has been minimized.

Copy link

@IIPoliII IIPoliII commented Aug 8, 2019

How can i auth only specific person that has a specific role?

@JakyeRU

This comment has been minimized.

Copy link

@JakyeRU JakyeRU commented Sep 22, 2019

Thank you!

@braindigitalis

This comment has been minimized.

Copy link

@braindigitalis braindigitalis commented Feb 5, 2020

Big thumbs up to this, much simpler than messing with a big heavyweight oauth lib!

@korobaka

This comment has been minimized.

Copy link

@korobaka korobaka commented Feb 8, 2020

Hello, is it possible to get also the user data in the js console? If yes, what is the command?

@tholeb

This comment has been minimized.

Copy link

@tholeb tholeb commented Feb 8, 2020

hey, yeah, simply use console.log('text or variable'); command but don't forget that the client can access those datas

@CSS-Lletya

This comment has been minimized.

Copy link

@CSS-Lletya CSS-Lletya commented Apr 3, 2020

Works like a charm up to this date!
Just replace client, secret, and create a redirect URL in the discord application.

Going to use this; thanks!

@jimmithe13th

This comment has been minimized.

Copy link

@jimmithe13th jimmithe13th commented May 15, 2020

This guy: https://www.fiverr.com/rubenrunn sell this code on fiverr :D You better should to report him. I found this code on my deliver . If you need proof to report him just message me so i can send you all my proof

@RubenRuNN

This comment has been minimized.

Copy link

@RubenRuNN RubenRuNN commented May 15, 2020

Hey, I am that guy that "sell this code on fiverr". No, I don't sell this code on fiverr. I use the structure of the code to implement discord oauth2 on projects. This code is open source since is not copyright protected.
This guy didn't research codes to do the login with discord on his website, he went on fiver and asked me that gig. I've done it, when he saw how it is he tried to escape the payment.

Sorry for bringing this here.

@salimregorce

This comment has been minimized.

Copy link

@salimregorce salimregorce commented Jun 11, 2020

work perfectly appreciate it (👍 !

@Lebleathan

This comment has been minimized.

Copy link

@Lebleathan Lebleathan commented Jun 13, 2020

Trying to get property 'access_token' of non-object on line 44 & 45
Can anyone help? @Jengas

@Jengas

This comment has been minimized.

Copy link
Owner Author

@Jengas Jengas commented Jul 7, 2020

Just edited endpoints. Should work now

@Alexis-Elaxis

This comment has been minimized.

Copy link

@Alexis-Elaxis Alexis-Elaxis commented Jul 14, 2020

Thank you <3

@MistercoDev

This comment has been minimized.

Copy link

@MistercoDev MistercoDev commented Aug 1, 2020

Sorry but I still have this error when I try to get the access token : "Notice: Trying to get property 'access_token' of non-object in C:\wamp64\www\index.php on line 44 & 45". I tried many things like reinstalling Wamp but it didn't work. I also tried to modify many things in the apiRequest function but it's always the same error. So I wrote this in my code : "echo json_encode($token);" and it returned "null". I don't know what to do. Sorry again for disturbing you.
Regards.
Misterco. (@Jengas)

@pisteuralpin

This comment has been minimized.

Copy link

@pisteuralpin pisteuralpin commented Aug 1, 2020

Hello, that doesn't work, I'm corretly redirected to my page but I'm not conneted

@MistercoDev

This comment has been minimized.

Copy link

@MistercoDev MistercoDev commented Aug 1, 2020

@pisteuralpin Try to remove " header('Location: ' . $_SERVER['PHP_SELF']);" at line 48 : tell us if you have an error. I think we have the same problem

@MistercoDev

This comment has been minimized.

Copy link

@MistercoDev MistercoDev commented Aug 3, 2020

Someone on Discord told me how to fix this problem : my redirect uri was a localhost. But I'm the only one who can access this localhost, not Discord. So, it can't give me the information that I want (the access token). And that's why $token is not an object : because Discord wasn't able to find my localhost and to give me the token. To fix the problem, I put my index.php on 000webhost (you can use another hosting service if you want) and it worked. So, just add the Discord OAuth2 at the end. Sorry again for disturbing you and for my bad english ^^' Have a nice day 😎

@Komischerboy

This comment has been minimized.

Copy link

@Komischerboy Komischerboy commented Aug 12, 2020

Doesn't work :/

@Komischerboy

This comment has been minimized.

Copy link

@Komischerboy Komischerboy commented Aug 12, 2020

Trying to get property 'access_token' of non-object in C:\inetpub\wwwroot\gmbh\JBot\api.php on line 44

@derrobin154

This comment has been minimized.

Copy link

@derrobin154 derrobin154 commented Aug 14, 2020

When I make an API request (line 37) and output it via print_r, nothing comes back. What can be the reason for this?

@inplex-sys

This comment has been minimized.

Copy link

@inplex-sys inplex-sys commented Aug 28, 2020

Be Careful about the ddos amplification

@abubakar-iqbal

This comment has been minimized.

Copy link

@abubakar-iqbal abubakar-iqbal commented Oct 6, 2020

Love it

@sobhanso

This comment has been minimized.

Copy link

@sobhanso sobhanso commented Oct 17, 2020

Can anyone help? The expiration date is for the past days!

@maxsupermanhd

This comment has been minimized.

Copy link

@maxsupermanhd maxsupermanhd commented Nov 20, 2020

Token revoke is not working even with apiRequest, am I dong something wrong? It says bad request and that's it...

@IIPoliII

This comment has been minimized.

Copy link

@IIPoliII IIPoliII commented Nov 20, 2020

@CraterMaik

This comment has been minimized.

Copy link

@CraterMaik CraterMaik commented Dec 2, 2020

the authentication section have a limit of how much? 7 days

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.