Implermented login
This commit is contained in:
parent
923d6ca242
commit
51c20b55a0
30 changed files with 2495 additions and 39 deletions
79
src/php/Api/DiscordAPI.php
Normal file
79
src/php/Api/DiscordAPI.php
Normal file
|
@ -0,0 +1,79 @@
|
|||
<?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}";
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue