eve-indy-job-tracker/callback.php

82 lines
2.5 KiB
PHP
Executable file

<?php
require_once __DIR__ . "/session_bootstrap.php";
$client_id = "YOUR-EVE-CLIENT-ID";
// Replace with your ESI client secret from EVE Developer Portal
$client_secret = "YOUR-EVE-CLIENT-SECRET";
$redirect_uri = "YOUR-CALLBACK-URL"; // Example: https://your-domain.com/callback.php
// Validate the OAuth state and code
if (
!isset($_GET["code"]) ||
!isset($_GET["state"]) ||
$_GET["state"] !== $_SESSION["oauth2state"]
) {
exit("Invalid state or code");
}
$code = $_GET["code"];
$token_url = "https://login.eveonline.com/v2/oauth/token";
// Get the access and refresh tokens
$ch = curl_init($token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
http_build_query([
"grant_type" => "authorization_code",
"code" => $code,
"redirect_uri" => $redirect_uri,
])
);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
"Content-Type: application/x-www-form-urlencoded",
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$token_data = json_decode($response, true);
// Fail gracefully if token fetch fails
if (!is_array($token_data) || !isset($token_data["access_token"])) {
error_log("Token exchange failed: $response");
exit("Failed to retrieve access token");
}
// Use access token to get character info
$ch = curl_init("https://login.eveonline.com/oauth/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . $token_data["access_token"],
]);
$user_data = json_decode(curl_exec($ch), true);
curl_close($ch);
// Validate user info
if (!is_array($user_data) || !isset($user_data["CharacterID"])) {
error_log("Failed to verify character: " . json_encode($user_data));
exit("Character verification failed");
}
$character_id = $user_data["CharacterID"];
$character_name = $user_data["CharacterName"];
// Save access & refresh tokens in session
if (!isset($_SESSION["characters"][$character_id])) {
$_SESSION["characters"][$character_id] = [
"name" => $character_name,
"access_token" => $token_data["access_token"],
"refresh_token" => $token_data["refresh_token"] ?? null,
];
} else {
error_log("Character data already exists for ID: $character_id. Skipping overwrite.");
}
// Redirect back to main page
header("Location: index.php");
exit();