109 行
2.8 KiB
PHP
109 行
2.8 KiB
PHP
<?php
|
|
/**
|
|
* Discord登录回调处理
|
|
*/
|
|
|
|
session_start();
|
|
require_once '../config.php';
|
|
|
|
$config = require '../config.php';
|
|
$discordConfig = $config['discord'] ?? [];
|
|
$clientId = $discordConfig['client_id'] ?? '';
|
|
$clientSecret = $discordConfig['client_secret'] ?? '';
|
|
$redirectUri = $discordConfig['callback'] ?? 'https://www.parlz.com/callback/discord.php';
|
|
|
|
// 获取Discord返回的参数
|
|
$code = $_GET['code'] ?? '';
|
|
$error = $_GET['error'] ?? '';
|
|
|
|
if ($error) {
|
|
// 登录失败
|
|
$_SESSION['error'] = 'Discord登录被取消或失败';
|
|
header('Location: ../index.php');
|
|
exit;
|
|
}
|
|
|
|
if (!$code || !$clientId || !$clientSecret) {
|
|
// 缺少必要参数
|
|
$_SESSION['error'] = 'Discord登录配置不完整,请联系管理员';
|
|
header('Location: ../index.php');
|
|
exit;
|
|
}
|
|
|
|
// 使用code兑换access token
|
|
$tokenUrl = 'https://discord.com/api/oauth2/token';
|
|
$tokenParams = [
|
|
'client_id' => $clientId,
|
|
'client_secret' => $clientSecret,
|
|
'grant_type' => 'authorization_code',
|
|
'code' => $code,
|
|
'redirect_uri' => $redirectUri,
|
|
'scope' => 'identify email'
|
|
];
|
|
|
|
$ch = curl_init($tokenUrl);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenParams));
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Content-Type: application/x-www-form-urlencoded'
|
|
]);
|
|
$tokenResponse = curl_exec($ch);
|
|
curl_close($ch);
|
|
|
|
$tokenData = json_decode($tokenResponse, true);
|
|
|
|
if (!isset($tokenData['access_token'])) {
|
|
// 获取access token失败
|
|
$_SESSION['error'] = 'Discord登录失败,请稍后重试';
|
|
header('Location: ../index.php');
|
|
exit;
|
|
}
|
|
|
|
$accessToken = $tokenData['access_token'];
|
|
|
|
// 使用access token获取用户信息
|
|
$userUrl = 'https://discord.com/api/users/@me';
|
|
|
|
$ch = curl_init($userUrl);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $accessToken
|
|
]);
|
|
$userResponse = curl_exec($ch);
|
|
curl_close($ch);
|
|
|
|
$userData = json_decode($userResponse, true);
|
|
|
|
if (!isset($userData['id'])) {
|
|
// 获取用户信息失败
|
|
$_SESSION['error'] = 'Discord登录失败,请稍后重试';
|
|
header('Location: ../index.php');
|
|
exit;
|
|
}
|
|
|
|
$discordId = $userData['id'];
|
|
$username = $userData['username'] ?? "Discord_$discordId";
|
|
$email = $userData['email'] ?? '';
|
|
$avatar = '';
|
|
|
|
// 构建头像URL
|
|
if (isset($userData['avatar'])) {
|
|
$avatarHash = $userData['avatar'];
|
|
$avatar = "https://cdn.discordapp.com/avatars/$discordId/$avatarHash.png";
|
|
}
|
|
|
|
// 保存第三方用户信息到Session,跳转到绑定页面
|
|
$_SESSION['oauth_provider'] = 'discord';
|
|
$_SESSION['oauth_user'] = [
|
|
'id' => $discordId,
|
|
'username' => $username,
|
|
'name' => $username,
|
|
'avatar' => $avatar,
|
|
'email' => $email
|
|
];
|
|
|
|
// 跳转回绑定页面
|
|
header('Location: ../oauth_bind.php');
|
|
exit;
|
|
?>
|