DSB-PlugIn/AddOn/Calender_Office365_User/callback.php

70 lines
1.9 KiB
PHP

<?php
$config = require 'config.php';
if (!isset($_GET['code'])) {
die("Authorization code fehlt.");
}
$code = $_GET['code'];
// ➤ Token anfordern
$data = [
'client_id' => $config['client_id'],
'scope' => $config['scopes'],
'code' => $code,
'redirect_uri' => $config['redirect_uri'],
'grant_type' => 'authorization_code',
'client_secret' => $config['client_secret'],
];
$ch = curl_init($config['token_url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded',
]);
$response = curl_exec($ch);
curl_close($ch);
$tokenData = json_decode($response, true);
if (!isset($tokenData['access_token'])) {
die("Fehler beim Token-Abruf: " . $response);
}
// ➤ E-Mail-Adresse vom User holen
$ch = curl_init($config['graph_url'] . '/me');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $tokenData['access_token'],
]);
$userResponse = curl_exec($ch);
curl_close($ch);
$userData = json_decode($userResponse, true);
$email = $userData['mail'] ?? $userData['userPrincipalName'] ?? null;
if (!$email) {
die("Fehler beim Abrufen der E-Mail.");
}
// ➤ Speichern in tokens.json
$tokens = [];
if (file_exists($config['token_storage'])) {
$tokens = json_decode(file_get_contents($config['token_storage']), true);
}
$tokens[$email] = [
'access_token' => $tokenData['access_token'],
'refresh_token' => $tokenData['refresh_token'],
'expires_in' => $tokenData['expires_in'],
'time_saved' => time()
];
file_put_contents($config['token_storage'], json_encode($tokens, JSON_PRETTY_PRINT));
echo "Erfolgreich verbunden mit: <b>$email</b><br>";
echo "<a href='calendar.php?email=" . urlencode($email) . "'>Zum Kalender-Tool</a>";