$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_params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error = curl_error($ch); curl_close($ch); if ($curl_error) { log_error("cURL Error: " . $curl_error); echo "An error occurred. Please try again later. (Code: 1)"; exit(); } if ($http_code == 200) { $token_data = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { log_error("Failed to decode JSON response: " . $response); echo "An error occurred. Please try again later. (Code: 2)"; exit(); } // Ensure the db directory exists if (!is_dir(dirname('db/google_tokens.json'))) { mkdir(dirname('db/google_tokens.json'), 0775, true); } if (file_put_contents('db/google_tokens.json', json_encode($token_data)) === false) { log_error("Failed to write tokens to db/google_tokens.json"); echo "An error occurred. Please try again later. (Code: 3)"; exit(); } $_SESSION['google_access_token'] = $token_data['access_token']; header('Location: dashboard.php'); exit(); } else { log_error("Error fetching access token. HTTP Code: " . $http_code . ", Response: " . $response); echo "An error occurred while trying to connect to Google. Please check your credentials in setup.php and try again."; } } else { log_error("Authorization code not found in callback."); echo "Authorization code not found."; }