$config['client_id'], 'redirect_uri' => $config['redirect_uri'], 'response_type' => 'code', 'scope' => 'identify', 'state' => $state, 'prompt' => 'consent', ]; return 'https://discord.com/oauth2/authorize?' . http_build_query($params); } /** * Tauscht den OAuth-Code gegen ein Access-Token und liest damit die * Discord-Identitaet (ID + Benutzername) aus. * * @return array{id: string, username: string} * @throws RuntimeException */ function discord_exchange_code(string $code): array { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } $config = discord_config(); $ch = curl_init('https://discord.com/api/oauth2/token'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query([ 'client_id' => $config['client_id'], 'client_secret' => $config['client_secret'], 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $config['redirect_uri'], ]), CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'], CURLOPT_TIMEOUT => 10, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $curlError); } $tokenData = json_decode($response, true); if ($httpCode !== 200 || !is_array($tokenData) || empty($tokenData['access_token'])) { throw new RuntimeException('Discord hat den Login-Code nicht akzeptiert.'); } $ch2 = curl_init('https://discord.com/api/users/@me'); curl_setopt_array($ch2, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $tokenData['access_token']], CURLOPT_TIMEOUT => 10, ]); $userResponse = curl_exec($ch2); $userHttpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE); curl_close($ch2); if ($userResponse === false || $userHttpCode !== 200) { throw new RuntimeException('Discord-Benutzerdaten konnten nicht abgerufen werden.'); } $userData = json_decode($userResponse, true); if (!is_array($userData) || empty($userData['id']) || !isset($userData['username'])) { throw new RuntimeException('Unerwartete Antwort von Discord.'); } return [ 'id' => (string) $userData['id'], 'username' => (string) $userData['username'], ]; }