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 GuzzleHttpClient();
try {
$response = $client->get("https://discord.com/api/v10/guilds/{$guildId}/members/{$discordId}", [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
],
]);
return $response->getStatusCode() == 200;
} catch (GuzzleHttpExceptionRequestException $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
]
]
Fixing 401 Unauthorized Error with Socialite Discord
New contributor
Thành Sơn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.