donde apiKey es unico por instalacion * y se obtuvo en el login. Sin secret global compartido entre plugins. */ class Agentia_API { private $base_url; public function __construct() { $this->base_url = rtrim(AGENTIA_API_URL, '/'); } /** * Request al backend. * * @param string $method HTTP method * @param string $endpoint Path del endpoint * @param array|null $body JSON body * @param string|null $apiKey Si se pasa, se envia como Authorization: Bearer */ private function request($method, $endpoint, $body = null, $apiKey = null) { $url = $this->base_url . $endpoint; $headers = [ 'Content-Type' => 'application/json', ]; if (!empty($apiKey)) { $headers['Authorization'] = 'Bearer ' . $apiKey; } $args = [ 'method' => $method, 'timeout' => 30, 'headers' => $headers, ]; if ($body !== null) { $args['body'] = json_encode($body); } $response = wp_remote_request($url, $args); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } $code = wp_remote_retrieve_response_code($response); $data = json_decode(wp_remote_retrieve_body($response), true); if ($code >= 400) { return ['error' => isset($data['message']) ? $data['message'] : 'Error del servidor', 'code' => $code]; } return $data; } /** * Login. Endpoint publico (sin Bearer). * Envia siteUrl para que el backend pueda validar la regla "1 sitio por empresa". */ public function login($email, $password, $siteUrl = null) { $payload = [ 'email' => $email, 'password' => $password, ]; if (!empty($siteUrl)) { $payload['siteUrl'] = $siteUrl; } return $this->request('POST', '/wp/login', $payload); } /** * Listar flujos disponibles. Requiere apiKey. */ public function get_configs_by_company($id_company) { $apiKey = get_option('agentia_api_key', ''); return $this->request('GET', '/wp/configs-by-company/' . intval($id_company), null, $apiKey); } /** * Obtener estadisticas. Requiere apiKey. */ public function get_stats($id_wp_account) { $apiKey = get_option('agentia_api_key', ''); return $this->request('GET', '/wp/stats/' . intval($id_wp_account), null, $apiKey); } /** * Generar SSO code para auto-login en el frontend. Requiere apiKey. */ public function get_sso_code($api_key) { return $this->request('POST', '/wp/sso-code', ['apiKey' => $api_key], $api_key); } /** * Obtener config del widget por apiKey. Endpoint publico (apiKey en path). */ public function get_widget_config($api_key) { return $this->request('GET', '/wp/widget-config/' . urlencode($api_key)); } }