$api_key, 'email' => $email, 'service' => $service, ); // Use WordPress's built-in function to make the remote request. $response = wp_remote_post($auth_server_url, array( 'method' => 'POST', 'timeout' => 45, // seconds 'redirection' => 5, 'blocking' => true, // Make sure WordPress waits for the response 'headers' => array(), 'body' => $body, )); // Check if the request itself failed (e.g., DNS error, server down). if (is_wp_error($response)) { // You might want to log this for debugging purposes. // error_log('API validation request failed: ' . $response->get_error_message()); return new WP_Error('auth_server_connection_failed', 'Could not connect to the authentication server. Please try again later.'); } // Get the HTTP status code and the body from the response. $response_code = wp_remote_retrieve_response_code($response); $response_body = wp_remote_retrieve_body($response); $decoded_body = json_decode($response_body, true); // Check for a successful (200 OK) response code from the auth server. if ($response_code !== 200) { // If the server returned an error (like 401, 429, etc.), use its error message. $error_message = isset($decoded_body['message']) ? $decoded_body['message'] : 'An unknown error occurred during authentication.'; $error_code = isset($decoded_body['code']) ? $decoded_body['code'] : 'authentication_failed'; return new WP_Error($error_code, $error_message); } // At this point, the auth server has confirmed the request is valid. return true; }