79 lines
No EOL
2.4 KiB
PHP
79 lines
No EOL
2.4 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace GamesShop\Api;
|
|
|
|
use Curl\Curl;
|
|
use Exception;
|
|
use GamesShop\Environment\EnvironmentHandler;
|
|
use GamesShop\Errors\ExtendedException;
|
|
|
|
final class DiscordAPI
|
|
{
|
|
const string OAUTH_TOKEN_URL = "https://discord.com/api/oauth2/token";
|
|
const string USER_ME_URL = 'https://discord.com/api/users/@me';
|
|
|
|
public function __construct(
|
|
private readonly EnvironmentHandler $env
|
|
)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @return array{id: string, global_name: string, avatar: string, discriminator: int}
|
|
* @throws Exception
|
|
*/
|
|
public function getUserFromCode(string $code, string $redirectUri): array {
|
|
$discordEnv = $this->env->getDiscordEnvironment();
|
|
|
|
$curl = new Curl();
|
|
$curl->setHeader('Content-Type', 'application/x-www-form-urlencoded');
|
|
$curl->setBasicAuthentication($discordEnv->clientId, $discordEnv->clientSecret);
|
|
|
|
$data =[
|
|
'grant_type' => 'authorization_code',
|
|
'code' => $code,
|
|
'redirect_uri' => $redirectUri
|
|
];
|
|
$curl->post(self::OAUTH_TOKEN_URL, $data);
|
|
|
|
if ($curl->error) {
|
|
$curl->diagnose();
|
|
|
|
throw new ExtendedException($curl->errorMessage, [ 'response' => $curl->response, 'data' => $data ]);
|
|
}
|
|
|
|
$accessToken = $curl->response->access_token;
|
|
$tokenType = $curl->response->token_type;
|
|
|
|
$curl = new Curl();
|
|
$curl->setHeader("authorization", "$tokenType $accessToken");
|
|
$curl->get(self::USER_ME_URL);
|
|
|
|
if ($curl->error) {
|
|
$curl->diagnose();
|
|
|
|
throw new ExtendedException($curl->errorMessage, [ 'response' => $curl->response, ]);
|
|
}
|
|
|
|
return [
|
|
'id' => $curl->response->id,
|
|
'global_name' => $curl->response->global_name,
|
|
'avatar' => $curl->response->avatar,
|
|
'discriminator' => (int) $curl->response->discriminator
|
|
];
|
|
}
|
|
|
|
public function getAvatarURL(string $userId, string|int $avatarHash) {
|
|
if (is_int($avatarHash)) {
|
|
return "https://cdn.discordapp.com/embed/avatars/{$avatarHash}.png";
|
|
}
|
|
|
|
$extension = 'png';
|
|
if (str_starts_with($avatarHash, 'a_')) {
|
|
$extension = 'gif';
|
|
}
|
|
|
|
return "https://cdn.discordapp.com/avatars/{$userId}/{$avatarHash}.{$extension}";
|
|
}
|
|
} |