api_url, [ 'method' => 'POST', 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_token, 'X-Widget-Id' => $widget_id, 'Origin' => $origin, 'Referer' => $referer, 'X-Origin' => $origin, 'Accept' => 'application/json', 'X-Requested-With' => 'XMLHttpRequest' ], 'body' => wp_json_encode($payload), 'timeout' => $this->timeout, 'sslverify' => true ] ); if (is_wp_error($response)) { return $response; } $status_code = (int) wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); if ($status_code < 200 || $status_code >= 300) { $message = $this->extract_error_message_from_body($body); if (empty($message)) { $message = sprintf('Chat service returned HTTP %d', $status_code); } return new WP_Error('http_error', $message, ['status_code' => $status_code]); } if (empty($body)) { return new WP_Error('empty_response', 'Chat service returned an empty response'); } $data = json_decode($body, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) { return new WP_Error('invalid_response', 'Invalid response from chat service'); } // Support both Shopify format (status: success) and other formats if (isset($data['status']) && $data['status'] !== 'success') { return new WP_Error('api_status_error', $this->extract_error_message_from_body($body) ?: 'Request failed'); } return $data; } /** * Extracts a meaningful error message from API response body. * * @param string $body * * @return string */ private function extract_error_message_from_body($body) { if (empty($body)) { return ''; } $decoded = json_decode($body, true); if (!is_array($decoded)) { return ''; } foreach (['message', 'error', 'detail', 'response'] as $key) { if (!empty($decoded[$key]) && is_string($decoded[$key])) { return sanitize_text_field($decoded[$key]); } } if (!empty($decoded['data']) && is_array($decoded['data'])) { foreach (['message', 'error', 'detail'] as $nested_key) { if (!empty($decoded['data'][$nested_key]) && is_string($decoded['data'][$nested_key])) { return sanitize_text_field($decoded['data'][$nested_key]); } } } return ''; } /** * Get API configuration */ public function get_config() { $opts = get_option($this->option_key, []); return [ 'api_token' => $opts['api_token'] ?? '', 'widget_id' => $opts['widget_id'] ?? '', 'agent_id' => $opts['agent_id'] ?? '', 'user_id' => $opts['user_id'] ?? '', 'agent_name' => $opts['agent_name'] ?? 'AI Assistant', 'auto_insert' => $opts['auto_insert'] ?? 0, ]; } /** * Check if plugin is configured */ public function is_configured() { $config = $this->get_config(); return !empty($config['widget_id']) && !empty($config['agent_id']) && !empty($config['user_id']); } }