98 行
2.5 KiB
PHP
98 行
2.5 KiB
PHP
<?php
|
|
/**
|
|
* 微软登录回调处理文件
|
|
* 处理微软 OAuth 授权回调,获取用户信息并重定向到绑定页面
|
|
*/
|
|
|
|
session_start();
|
|
|
|
// 加载配置文件
|
|
$config = require __DIR__ . '/../config.php';
|
|
$microsoftConfig = $config['microsoft'] ?? [];
|
|
|
|
// 检查必要参数
|
|
if (!isset($_GET['code'])) {
|
|
die('授权失败:缺少code参数');
|
|
}
|
|
|
|
$code = $_GET['code'];
|
|
|
|
// 1. 通过code获取access_token
|
|
$tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
|
|
$tokenParams = [
|
|
'client_id' => $microsoftConfig['client_id'] ?? '',
|
|
'client_secret' => $microsoftConfig['client_secret'] ?? '',
|
|
'code' => $code,
|
|
'redirect_uri' => $microsoftConfig['callback'] ?? '',
|
|
'grant_type' => 'authorization_code'
|
|
];
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $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_SSL_VERIFYPEER, false);
|
|
|
|
$tokenResponse = curl_exec($ch);
|
|
|
|
if (curl_errno($ch)) {
|
|
die('获取access_token失败:' . curl_error($ch));
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
$tokenData = json_decode($tokenResponse, true);
|
|
|
|
if (!isset($tokenData['access_token'])) {
|
|
die('获取access_token失败:' . $tokenResponse);
|
|
}
|
|
|
|
$accessToken = $tokenData['access_token'];
|
|
|
|
// 2. 通过access_token获取用户信息
|
|
$userInfoUrl = 'https://graph.microsoft.com/v1.0/me';
|
|
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $userInfoUrl);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $accessToken,
|
|
'User-Agent: ChatApp'
|
|
]);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
|
|
|
$userInfoResponse = curl_exec($ch);
|
|
|
|
if (curl_errno($ch)) {
|
|
die('获取用户信息失败:' . curl_error($ch));
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
$userInfo = json_decode($userInfoResponse, true);
|
|
|
|
if (!isset($userInfo['id'])) {
|
|
die('获取用户信息失败:' . $userInfoResponse);
|
|
}
|
|
|
|
// 3. 获取用户邮箱
|
|
$microsoftEmail = $userInfo['mail'] ?? '';
|
|
|
|
$microsoftId = $userInfo['id'];
|
|
$microsoftUsername = $userInfo['displayName'] ?? 'microsoft_user';
|
|
|
|
// 4. 保存第三方用户信息到Session,跳转到绑定页面
|
|
$_SESSION['oauth_provider'] = 'microsoft';
|
|
$_SESSION['oauth_user'] = [
|
|
'id' => $microsoftId,
|
|
'username' => $microsoftUsername,
|
|
'name' => $microsoftUsername,
|
|
'avatar' => '',
|
|
'email' => $microsoftEmail
|
|
];
|
|
|
|
// 5. 跳转回绑定页面
|
|
header('Location: ../oauth_bind.php');
|
|
exit;
|
|
?>
|