$code, 'client_id' => GOOGLE_CLIENT_ID, 'client_secret' => GOOGLE_CLIENT_SECRET, 'redirect_uri' => GOOGLE_REDIRECT_URI, 'grant_type' => 'authorization_code' ]; $ch = curl_init($token_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($token_data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $token_info = json_decode($response, true); if (isset($token_info['access_token'])) { // Success! Store the token and redirect. $_SESSION['access_token'] = $token_info['access_token']; if (isset($token_info['refresh_token'])) { $_SESSION['refresh_token'] = $token_info['refresh_token']; } unset($_SESSION['last_auth_code']); // Clean up the used code. header('Location: index.php'); exit(); } else { // Log the detailed error from Google for server-side debugging. error_log("Google OAuth Error: " . $response); // Display a clear, actionable error message to the user. $error_title = "Authentication Failed!"; $error_message = "The application was unable to get an access token from Google."; $google_response = "
" . htmlspecialchars($response, ENT_QUOTES, 'UTF-8') . "
"; $most_likely_cause = "This is most likely due to an incorrect Client ID or Client Secret in the google_config.php file."; $instructions = "Please double-check that the credentials you copied from the Google Cloud Console are correct and have no typos or extra spaces."; // Simple HTML for the error page echo << {$error_title}

{$error_title}

{$error_message}

{$most_likely_cause}

{$instructions}

Google's Raw Response: {$google_response}
HTML; exit(); } ?>