If you're diving into Oauth2, this answer will steer you in the right direction. I'll be showcasing JS examples utilizing the node-fetch
library for making web requests, assuming you have an express
backend set up.
First off, you need to guide the user to authorize their account with your client ID and the identify
scope. On authorization, they will be redirected to your designated redirect URI (https://example.com/redirect
as an example).
Upon redirection, a code
GET parameter will be present in the URL they land on. Grab this code and dispatch it to Discord's token URL to obtain an access token:
app.get('/redirect', async function (req, res) {
// Retrieve the code from GET params
var code = req.query.code;
// Create the POST body
var body = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'https://example.com/redirect',
};
// Send POST request to Discord
var site = await fetch("https://discord.com/api/v9/oauth2/token", {
method: 'POST',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
// Parse the response
var response = await site.json();
var accessToken = response['access_token'];
res.send(`Access token: ${accessToken}`);
})
Using the accessed token provided by Discord's response, you can proceed with a GET request to fetch information about the current user, employing an Authorization
header of Bearer XXXXX
(substitute XXXXX
with your access token):
var site = await fetch("https://discord.com/api/v9/users/@me", {
method: 'GET',
headers: {'Authorization': `Bearer ${accessToken}`}
});
var response = await site.json();
var username = response.username;
Given that I'm unaware of the specific libraries you're integrating, this should give you a solid foundation and understanding of the steps required to attain the desired information.