How do I use access token from discord oauth2 login to get user information

11,166

As you know PHP you know you can get the Token as a Variable. With that Token, you can send requests to discords API. You need the Endpoint which gives you basic user information: http://discordapp.com/api/users/@me For the following, you need the CURL Libary

$curl_h = curl_init('http://discordapp.com/api/users/@me');

curl_setopt($curl_h, CURLOPT_HTTPHEADER, array(
     'User-Agent: MyCoolAuth v0.1',
     'Authorization: TOKEN'
    )
);
curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_h);

That reponse is an Array with all Infortmation you could need. A detailed explanation of its content can be found at discords developer portal.

Share:
11,166
Finley Sherwood
Author by

Finley Sherwood

Updated on June 05, 2022

Comments

  • Finley Sherwood
    Finley Sherwood almost 2 years

    I have been trying to setup my website so users can login through discord. At the moment, I have the following code:

    <html>
        <body>
            <?php
                session_start();
                if ($_SERVER['REQUEST_METHOD']=='POST')
                    {
                        $params = array(
                            'response_type' => 'token',
                            'client_id' => '550631359337594881',
                            'scope' => 'identify'
                        );
                        header('Location:https://discordapp.com/api/oauth2/authorize?'.http_build_query($params));
                    }
            ?>
            <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                <input type="submit" value="Login">
            </form>
        </body>
    </html>
    

    Which sends the user to the discord authorisation link, and then back to:

    http://localhost/#access_token=TOKEN&token_type=Bearer&expires_in=604800&scope=identify
    

    I am working on the site through an XAMPP local server so I can use PHP, that's why it is a http://localhost

    This is all good, however my issue is that I actually don't know where I am supposed to go from here. I have the token, token type, expiry, and scope, but I don't know how I am supposed to use them.

    WHAT I WANT

    I want to be able to get the user's discord avatar and username, hence why I used the identify scope (more info at https://discordapp.com/developers/docs/topics/oauth2). I would like it if it can be done in PHP, because I don't know how to use languages like JSON and AJAX and all that AT ALL, however if it is the only way, its better than nothing.

    Can someone please help me follow up after I receive the access token? Thanks in advance!