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://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;
}
?>
@lekovul

This comment has been minimized.

Copy link

lekovul commented Jan 12, 2019

I love you.. Thanks!

@MohammedWadee

This comment has been minimized.

Copy link

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 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 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 commented Apr 23, 2019

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

@getwh1ted

This comment has been minimized.

Copy link

getwh1ted commented May 8, 2019

How can I make a logout button?

@burtgithub

This comment has been minimized.

Copy link

burtgithub commented May 10, 2019

I love you.. Thanks!

@deyyanl

This comment has been minimized.

Copy link

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 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 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 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 commented Jun 24, 2019

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

@umair9747

This comment has been minimized.

Copy link

umair9747 commented Jun 25, 2019

So if i implement it on a complete new page, say for example if i have a button on homepage to open another webpage consisting of an upload form, i want the upload page to be only limited to signed in discord user.. So if i just put this whole code in my upload.HTML file will it work? And what's the redirect URL thing in the code?

@IIPoliII

This comment has been minimized.

Copy link

IIPoliII commented Aug 8, 2019

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

@AlexBrunGiglio

This comment has been minimized.

Copy link

AlexBrunGiglio commented Aug 27, 2019

I have put the clients id and private but each time I have the connection failure that appears...
I am well brought to the authorization page of my discord app

@JakyeRU

This comment has been minimized.

Copy link

JakyeRU commented Sep 22, 2019

Thank you!

@braindigitalis

This comment has been minimized.

Copy link

braindigitalis commented Feb 5, 2020

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

@korobot

This comment has been minimized.

Copy link

korobot 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 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 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 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 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.

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.