Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
JS How to get discord account data via oauth2

I am developing a moderation bot for discord, I am trying to create a paid plan and therefore I need users to log in with their discord account with oauth2 so that I can fetch user data and know which server has the pay plan, chin. So for now I just created an oauth2 url and set up a redirect for https://bouncerbot.goatcode.it/index.html

then, after the user has logged in, I have this url: https://bouncerbot.goatcode.it/index.html?code=nZauBH6wT0hxn8g8SsS1OwiDvN35nn&guild_id=872213710150713384&permissions=0 so now i want user data (profile picture, username etc) how can i get it?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This is definitely more of an Oauth2 question than a Discord question. This answer will use JS examples using the node-fetch library to make web requests, and assumes you're using an express backend.

First you want to have the user authorize their account with your client ID and the identify scope. When they click authorize, they'll be sent to your specified redirect URI (https://example.com/redirect for this example).

When they're redirected, there will be a code GET parameter on the URL they land on, which you should take and send to Discord's token URL to get an access token:

app.get('/redirect', async function (req, res) {
    // Check their GET params to get the code
    var code = req.query.code;

    // Make our POST body
    var body = {
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'grant_type': 'authorization_code',
        'code': code,
        'redirect_uri': 'https://example.com/redirect',
    };

    // POST that 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'},
    });

    // And parse the response
    var response = await site.json();
    var accessToken = response['access_token'];
    res.send(`Access token: ${accessToken}`);
})

Using the access token given in Discord's response, you can make a GET request to get the current user, using an Authorization header of Bearer XXXXX (where XXXXX is 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;

Without knowing more about which libraries you're using I can't specifically give you you'll need for these things, but that's a decent list of examples and which processes you'll need to go through to get the information you want.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I have a similar file you can pursue.

import { CLIENT_ID, CLINET_SECRET, AUTHORIZATION_URL, REDIRECT_URL } from '../config/keys';
import React, { useEffect } from 'react';
import axios from 'axios';

const Auth = (props) => {
    const getUserGuilds = async (accessToken) => {
        // console.log(`Guild ${accessToken.data.token_type} ${accessToken.data.access_token}`);
        try {
            const response = await axios.get('https://discord.com/api/users/@me/guilds', {
                headers: {
                    authorization: `${accessToken.data.token_type} ${accessToken.data.access_token}`
                }
            });
            // console.log(response.data);
            return response.data;
        } catch (error) {
            console.log(error);
        }
    }
    const getUserInfo = async (accessToken) => {
        // console.log(accessToken);
        // console.log(`User ${accessToken.data.token_type} ${accessToken.data.access_token}`);
        try {
            const response = await axios.get('https://discord.com/api/users/@me', {
                headers: {
                    authorization: `${accessToken.data.token_type} ${accessToken.data.access_token}`
                }
            });
            // console.log(response.data);
            return response.data;
        } catch (error) {
            console.log(error);
        }
    }
    const getToken = async (code) => {
        try {
            const options = new URLSearchParams({
                client_id: CLIENT_ID,
                client_secret: CLINET_SECRET,
                code,
                grant_type: 'authorization_code',
                redirect_uri: REDIRECT_URL,
                scope: 'identify guilds',
            });
            const result = await axios.post('https://discord.com/api/oauth2/token', options);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    const getInfo = async (code) => {
        const accessToken = await getToken(code);
        const userInfo = await getUserInfo(accessToken);
        const guildInfo = await getUserGuilds(accessToken);
        console.log({ userInfo, guildInfo });
    }

    useEffect(() => {

        const urlSearchParams = new URLSearchParams(window.location.search);
        const params = Object.fromEntries(urlSearchParams.entries());
        // console.log(params);
        if (!params.code) return;
        getInfo(params.code);
    });
    return (
        <div className="Auth">
            <br />
            <a className="btn" href={AUTHORIZATION_URL} >Login with discord</a>
        </div>
    )
}

export default Auth;

about 4 years ago · Juan Pablo Isaza Denunciar

0

As I understand it, I most likely want to make a login system and you want to do it with discord, you can check this resource. https://www.youtube.com/watch?v=tSS8VKwwjp0

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda