Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nguyenthanhson's avatar

Fixing 401 Unauthorized Error with Socialite Discord

I'm performing code checks to see if the current user is a member of the guild or not using the following code (using the Socialite library - discord):

public function redirectToProvider()
{
    return Socialite::driver('discord')
        ->with(['access_type' => 'offline'])
        ->scopes([
            'identify',
            'email',
            'guilds',
            'applications.commands',
            'applications.commands.permissions.update',
            'guilds.join',
            'bot',
            'connections',
            'guilds.members.read',
            'role_connections.write',
        ])
        ->redirect();
}

public function handleProviderCallback()
{
    $user = Socialite::driver('discord')->user();
    $discordId = $user->getId();
    $accessToken = $user->token;
    $refreshToken = $user->refreshToken;
    $guildId = '1220351452170555402';
    $isMember = $this->checkGuildMember($discordId, $accessToken, $guildId);
    dd($isMember);
    if ($isMember) {
        dd('mem');
    } else {
        dd('notmem');
    }
}

protected function checkGuildMember($discordId, $accessToken, $guildId)
{
    $client = new \GuzzleHttp\Client();
    try {
        $response = $client->get("https://discord.com/api/v10/guilds/{$guildId}/members/{$discordId}", [
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
            ],
        ]);

        return $response->getStatusCode() == 200;
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        if ($e->hasResponse()) {
            $response = $e->getResponse();
            $statusCode = $response->getStatusCode();
            $body = $response->getBody()->getContents();
            \Log::error('Discord API Error:', [
                'status_code' => $statusCode,
                'response_body' => json_decode($body, true),
            ]);
            dd([
                'status_code' => $statusCode,
                'response_body' => json_decode($body, true),
            ]);
        }

        return false;
    }
}

I tried dd($user->approvedScopes) and it returned an array:

array:8 [▼
  0 => "guilds.join"
  1 => "guilds"
  2 => "guilds.members.read"
  3 => "identify"
  4 => "connections"
  5 => "applications.commands.permissions.update"
  6 => "email"
  7 => "role_connections.write"
]

But when running the checkGuildMember() function, it returned an array:

array:2 [▼
  "status_code" => 401
  "response_body" => array:2 [▼
    "message" => "401: Unauthorized"
    "code" => 0
  ]
]

0 likes
4 replies
RobertsP's avatar
RobertsP
Best Answer
Level 4

Hi @nguyenthanhson

This is how I checked if user is in my guild

    public function index()
    {
        return Socialite::driver('discord')
            ->setScopes([
                'identify',
                'guilds',
                'guilds.join',
                'guilds.members.read'
            ])
            ->redirect();
    }
    public function store(Request $request)
    {
        $discordUser = Socialite::driver('discord')->user();

        if ($this->isInGuild($discordUser->token)) {
            dd('do stuff');
        }

        $user = User::updateOrCreate([
            'discord_id' => $discordUser->getId()
        ], [
            'username' => $discordUser->getName(),
            'display_name' => $discordUser->user['global_name'],
            'avatar' => $discordUser->getAvatar()
        ]);

        Auth::login($user);

        return redirect()->route('index');
    }
    protected function isInGuild(string $accessToken): bool
    {
        try {
            $response = Http::withToken($accessToken)->get('https://discord.com/api/users/@me/guilds');
            if ($response->successful()) {
                return collect($response->json())->contains('id', "1203517911197679677");
            }

            Log::error('Discord API error', [
                'status' => $response->status(),
                'body' => $response->body()
            ]);

        } catch (Exception $e) {
            Log::error('Exception occurred while checking guild membership', [
                'message' => $e->getMessage()
            ]);
        }

        return  false;
    }
2 likes
nguyenthanhson's avatar

@RobertsP Thank you for helping me, but could you assist me with this? I want to automatically add users to a group if they are not already in the group. I tried this but got a 401 error

array:2 [▼
  "status_code" => 401
  "response_body" => array:2 [▼
    "message" => "401: Unauthorized"
    "code" => 0
  ]
]

Source:

public function redirectToProvider()
    {
        return Socialite::driver('discord')
            ->with(['access_type' => 'offline'])
            ->setScopes([
                'identify',
                'guilds',
                'guilds.join',
                'guilds.members.read'
            ])
            ->redirect();
    }

    public function handleProviderCallback()
    {
        $discordUser = Socialite::driver('discord')->user();
        $discordId = $discordUser->getId();
        $accessToken = $discordUser->token;
        $refreshToken = $discordUser->refreshToken;

        if ($this->isInGuild($discordUser->token)) {
            $data = DiscordModel::updateOrCreate([
                'discord_id' => $discordId
            ], [
                'user_id' => auth()->user()->id,
                'username' => $discordUser->nickname,
                'display_name' => $discordUser->user['global_name'],
                'avatar' => $discordUser->getAvatar(),
                'access_token' => $accessToken,
                'refresh_token' => $refreshToken,
            ]);
            $user = UsersModel::where('id', auth()->user()->id)->first();
            $user->discord = $discordId;
            $user->save();
            return redirect()->route('home')->with(noti('Discord connect successful', 'success'));
        } else {
            $response = $this->addUserToGuild($discordUser->token, $discordUser->getId());
            if ($response->successful()) {
                $data = DiscordModel::updateOrCreate([
                    'discord_id' => $discordId
                ], [
                    'user_id' => auth()->user()->id,
                    'username' => $discordUser->nickname,
                    'display_name' => $discordUser->user['global_name'],
                    'avatar' => $discordUser->getAvatar(),
                    'access_token' => $accessToken,
                    'refresh_token' => $refreshToken,
                ]);
                $user = UsersModel::where('id', auth()->user()->id)->first();
                $user->discord = $discordId;
                $user->save();
                return redirect()->route('home')->with(noti('Discord connect successful', 'success'));
            } else {
                Log::error('Failed to add user to guild', [
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);
                return redirect()->route('home')->with(noti('Discord connect failed', 'error'));
            }
        }
    }
    protected function addUserToGuild(string $accessToken, string $discordId)
    {
        try {
            return Http::withToken($accessToken)->put("https://discord.com/api/guilds/1220351452170555402/members/{$discordId}", [
                'access_token' => $accessToken,
            ]);
        } catch (Exception $e) {
            Log::error('Exception occurred while adding user to guild', [
                'message' => $e->getMessage()
            ]);
            return response()->serverError();
        }
    }

    protected function isInGuild(string $accessToken): bool
    {
        try {
            $response = Http::withToken($accessToken)->get('https://discord.com/api/users/@me/guilds');
            if ($response->successful()) {
                return collect($response->json())->contains('id', "1220351452170555402");
            }
            Log::error('Discord API error', [
                'status' => $response->status(),
                'body' => $response->body()
            ]);
        } catch (Exception $e) {
            Log::error('Exception occurred while checking guild membership', [
                'message' => $e->getMessage()
            ]);
        }
        return  false;
    }
RobertsP's avatar

@nguyenthanhson

You need to provide your bot token in authorization header like this Bot {$botToken} and also you need to provide user's access_token in your request body.

This information is written in discord's official docs: https://discord.com/developers/docs/resources/guild#add-guild-member

Here is how I implemented it in my laravel application.

    protected function joinGuild(string $accessToken, string $userId): bool
    {
        $guildId = config('services.discord.guild_id');
        $botToken = config('services.discord.bot_token');

        $response = Http::withHeaders([
            'Authorization' => "Bot {$botToken}"
        ])->asJson()
          ->put("https://discord.com/api/v10/guilds/{$guildId}/members/{$userId}", [
              'access_token' => $accessToken,
              'roles' => ['1248232571763163156']
          ]);

        if ($response->successful()) {
            return true;
        }

        Log::error('Discord API error', [
            'status' => $response->status(),
            'body' => $response->body()
        ]);

        return false;
    }
1 like

Please or to participate in this conversation.