wpdb = $wpdb; $this->webhooks_table = $wpdb->prefix . 'ai_app_onsite_webhooks'; // Include webhook job management and cron system with correct paths require_once plugin_dir_path(__FILE__) . 'includes/webhook-jobs.php'; require_once plugin_dir_path(__FILE__) . 'includes/webhook-cron.php'; require_once plugin_dir_path( __FILE__ ) . 'includes/webhook-helpers.php'; // Add AJAX hooks add_action( 'wp_ajax_ai_app_onsite_load_webhooks', array( $this, 'load_webhooks' ) ); add_action( 'wp_ajax_ai_app_onsite_save_webhook', array( $this, 'save_webhook' ) ); add_action( 'wp_ajax_ai_app_onsite_delete_webhook', array( $this, 'delete_webhook' ) ); add_action( 'wp_ajax_ai_app_onsite_test_webhook', array( $this, 'test_webhook' ) ); } /** * Load webhooks for the specified app */ public function load_webhooks(): void { // Verify nonce if ( ! wp_verify_nonce( $_POST['nonce'], 'ai_app_onsite_plugin_settings_nonce' ) ) { wp_die( 'Security check failed' ); } $app_id = intval( $_POST['app_id'] ); if ( ! $app_id ) { wp_send_json_error( 'Invalid app ID' ); return; } $webhooks = $this->wpdb->get_results( $this->wpdb->prepare( "SELECT * FROM {$this->webhooks_table} WHERE app_id = %d ORDER BY created_at DESC", $app_id ) ); wp_send_json_success( $webhooks ); } /** * Save (create or update) a webhook for the specified app */ public function save_webhook(): void { // Verify nonce if ( ! wp_verify_nonce( $_POST['nonce'], 'ai_app_onsite_plugin_settings_nonce' ) ) { wp_die( 'Security check failed' ); } $webhook_id = intval( $_POST['webhook_id'] ); $app_id = intval( $_POST['app_id'] ); $webhook_url = sanitize_url( $_POST['webhook_url'] ); $method = 'POST'; $payload_format = 'json'; $status = 'active'; // Validate required fields if ( ! $app_id || ! $webhook_url ) { wp_send_json_error( 'App ID and Webhook URL are required' ); return; } // Validate URL if ( ! filter_var( $webhook_url, FILTER_VALIDATE_URL ) ) { wp_send_json_error( 'Invalid webhook URL' ); return; } // Validate method if ( ! in_array( $method, [ 'GET', 'POST' ] ) ) { wp_send_json_error( 'Invalid HTTP method' ); return; } // Validate payload format if ( ! in_array( $payload_format, [ 'json', 'form' ] ) ) { wp_send_json_error( 'Invalid payload format' ); return; } // Validate status if ( ! in_array( $status, [ 'active', 'inactive' ] ) ) { wp_send_json_error( 'Invalid status' ); return; } $data = array( 'app_id' => $app_id, 'webhook_url' => $webhook_url, 'method' => $method, 'payload_format' => $payload_format, 'webhook_status' => $status, 'updated_at' => current_time( 'mysql' ) ); // Check if webhook exists for this app_id $existing_webhook = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT id FROM {$this->webhooks_table} WHERE app_id = %d", $app_id ) ); if ( $existing_webhook ) { // Update existing webhook $result = $this->wpdb->update( $this->webhooks_table, $data, array( 'id' => $existing_webhook->id ), array( '%d', '%s', '%s', '%s', '%s', '%s' ), array( '%d' ) ); if ( $result === false ) { wp_send_json_error( 'Failed to update webhook' ); return; } wp_send_json_success( 'Webhook updated successfully' ); } else { // Create new webhook $data['created_at'] = current_time( 'mysql' ); $data['webhook_event'] = 'response_created'; // Default event $result = $this->wpdb->insert( $this->webhooks_table, $data, array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ); if ( $result === false ) { wp_send_json_error( 'Failed to create webhook' ); return; } wp_send_json_success( 'Webhook created successfully' ); } } /** * Delete a webhook by ID */ public function delete_webhook(): void { // Verify nonce if ( ! wp_verify_nonce( $_POST['nonce'], 'ai_app_onsite_plugin_settings_nonce' ) ) { wp_die( 'Security check failed' ); } $webhook_id = intval( $_POST['webhook_id'] ); if ( ! $webhook_id ) { wp_send_json_error( 'Invalid webhook ID' ); return; } $result = $this->wpdb->delete( $this->webhooks_table, array( 'id' => $webhook_id ), array( '%d' ) ); if ( $result === false ) { wp_send_json_error( 'Failed to delete webhook' ); return; } wp_send_json_success( 'Webhook deleted successfully' ); } /** * Test webhook connection by sending a sample payload */ public function test_webhook(): void { // 1) Security if ( ! isset($_POST['nonce']) || ! wp_verify_nonce( $_POST['nonce'], 'ai_app_onsite_plugin_settings_nonce' ) ) { wp_die( 'Security check failed' ); } // 2) Input $webhook_url = isset($_POST['webhook_url']) ? sanitize_url( wp_unslash($_POST['webhook_url']) ) : ''; if ( ! $webhook_url || ! filter_var( $webhook_url, FILTER_VALIDATE_URL ) ) { wp_send_json_error( 'Invalid webhook URL' ); return; } // 3) Payload $test_payload = array( 'timestamp' => current_time( 'mysql' ), 'message' => 'This is a webhook connection request from AIappOnsite', 'event' => 'webhook_connection_request', ); // Common headers $accept_headers = array( 'User-Agent' => 'AIappOnsite-Webhook/1.0', 'Accept' => 'application/json, */*;q=0.1', ); // 4) STEP A — POST to /exec WITHOUT auto-follow (like curl without -L) $post_args = array( 'method' => 'POST', 'timeout' => 20, 'redirection' => 0, // IMPORTANT: do not auto-follow the 302 'headers' => $accept_headers + array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $test_payload ), 'data_format' => 'body', // prevent http_build_query on string body ); $post_res = wp_remote_request( $webhook_url, $post_args ); if ( is_wp_error( $post_res ) ) { wp_send_json_error( 'Connection failed: ' . $post_res->get_error_message() ); return; } $post_code = wp_remote_retrieve_response_code( $post_res ); $post_body = wp_remote_retrieve_body( $post_res ); $redirect_url = wp_remote_retrieve_header( $post_res, 'location' ); // 5) STEP B — Apps Script typically returns 302 + Location to an echo URL if ( ($post_code === 302 || $post_code === 303) && ! empty( $redirect_url ) ) { // Fetch the echo URL with a clean GET (no body), exactly like curl -L $get_args = array( 'timeout' => 20, 'headers' => $accept_headers, ); $get_res = wp_remote_get( $redirect_url, $get_args ); if ( is_wp_error( $get_res ) ) { wp_send_json_error( 'Follow-up fetch failed: ' . $get_res->get_error_message() ); return; } $get_code = wp_remote_retrieve_response_code( $get_res ); $get_body = wp_remote_retrieve_body( $get_res ); // Try to parse JSON; if not JSON, return raw body but still treat as a valid echo $decoded = json_decode( $get_body, true ); if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded ) ) { // Prefer the JSON contract from your GAS script $ok = ! isset( $decoded['success'] ) || (bool) $decoded['success']; if ( $ok ) { wp_send_json_success( array( 'message' => 'Connection verified successfully (redirected)', 'status_code' => 200, 'response' => $decoded, ) ); } wp_send_json_error( array( 'message' => 'Endpoint responded with failure (redirected)', 'status_code' => isset($decoded['status_code']) ? (int)$decoded['status_code'] : $get_code, 'response' => $decoded, ) ); } // Non-JSON body but reached echo URL — still a success for connectivity wp_send_json_success( array( 'message' => 'Connection verified (redirected, non-JSON body)', 'status_code' => $get_code, 'response' => $get_body, ) ); return; } // 6) No redirect path (some deployments return 200 directly) // Try to parse JSON from the initial response $decoded_direct = json_decode( $post_body, true ); if ( json_last_error() === JSON_ERROR_NONE && is_array( $decoded_direct ) ) { $ok = isset($decoded_direct['success']) ? (bool)$decoded_direct['success'] : ($post_code >= 200 && $post_code < 300); if ( $ok ) { wp_send_json_success( array( 'message' => 'Connection verified (no redirect)', 'status_code' => $post_code, 'response' => $decoded_direct, ) ); } else { wp_send_json_error( array( 'message' => 'Endpoint responded with failure (no redirect)', 'status_code' => isset($decoded_direct['status_code']) ? (int)$decoded_direct['status_code'] : $post_code, 'response' => $decoded_direct, ) ); } return; } // 7) Fallback: not JSON — treat 2xx as OK, otherwise error if ( $post_code >= 200 && $post_code < 300 ) { wp_send_json_success( array( 'message' => 'Connection verified (no redirect, non-JSON body)', 'status_code' => $post_code, 'response' => $post_body, ) ); } else { wp_send_json_error( array( 'message' => 'Connection failed', 'status_code' => $post_code, 'response' => $post_body, ) ); } } /** * Trigger webhook for actual events * * @param int|string $app_id App ID to filter webhooks * @param array $data Data to send in the webhook payload */ public function trigger_webhook( $app_id, array $data ): void { $webhooks = $this->wpdb->get_results( $this->wpdb->prepare( "SELECT * FROM {$this->webhooks_table} WHERE app_id = %d AND webhook_status = 'active'", $app_id ) ); } /** * Queue webhook for delayed sending (replaces immediate trigger_webhook) * * @param int|string $app_id App ID to filter webhooks * @param array $payload Data to send in the webhook payload */ public static function queue_webhook( $app_id, array $payload): void { $response_id = $payload['response_id'] ?? ''; if (!$response_id) { error_log('[AIappOnsite] Cannot queue webhook: missing response_id'); return; } // Get all active webhooks for this app, and return if no webhook is available global $wpdb; $webhooks_table = $wpdb->prefix . 'ai_app_onsite_webhooks'; $webhooks = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$webhooks_table} WHERE app_id = %d AND webhook_status = 'active'", $app_id ) ); if (empty($webhooks)) { return; } // Get delay setting with filter support $delay = (int) apply_filters('aiapp_webhook_delay_seconds', 60); $driver = (string) apply_filters('aiapp_webhook_async_driver', class_exists('\ActionScheduler') ? 'action_scheduler' : 'wp_cron' ); // Store job in database $job_data = [ 'status' => 'queued', 'scheduled_at' => time() + $delay ]; if (!aiapp_jobs_upsert($response_id, $job_data)) { error_log("[AIappOnsite] Failed to store webhook job for response_id: {$response_id}"); return; } // Schedule the job using preferred driver if ($driver === 'action_scheduler' && class_exists('\ActionScheduler')) { \as_schedule_single_action( time() + $delay, 'aiapp_send_webhook', array('response_id' => $response_id), 'aiapp' ); } else { // Use WP-Cron as fallback $hook_args = array('response_id' => $response_id); if (!wp_next_scheduled('aiapp_send_webhook', $hook_args)) { wp_schedule_single_event(time() + $delay, 'aiapp_send_webhook', $hook_args); } } } /** * Dispatch webhook sends to all active webhooks for an app (used by cron processor) * * @param int $app_id App ID to filter webhooks * @param array $payload Enriched payload data */ public function dispatch_sends(int $app_id, array $payload): void { // Check for idempotency - if already sent for this response_id, skip $response_id = $payload['response_id'] ?? ''; if ($response_id) { $job = aiapp_jobs_get($response_id); if ($job && $job['status'] === 'sent') { error_log("[AIappOnsite] Webhook already sent for response_id: {$response_id}, skipping"); return; } } // Get all active webhooks for this app $webhooks = $this->wpdb->get_results( $this->wpdb->prepare( "SELECT * FROM {$this->webhooks_table} WHERE app_id = %d AND webhook_status = 'active'", $app_id ) ); if (empty($webhooks)) { error_log("[AIappOnsite] No active webhooks found for app_id: {$app_id}"); return; } // Send to each webhook foreach ($webhooks as $webhook) { try { $this->send_webhook_with_logging($webhook, $payload); } catch (Exception $e) { error_log("[AIappOnsite] Failed to send webhook {$webhook->id}: " . $e->getMessage()); } } } /** * Enhanced send_webhook method with better logging and error handling */ private function send_webhook_with_logging($webhook, array $payload): void { $method = strtoupper((string) ($webhook->method ?? 'POST')); $url = esc_url_raw((string) $webhook->webhook_url); $response_id = $payload['response_id'] ?? ''; $format = strtolower((string) ($webhook->payload_format ?? 'json')); $headers = array( 'User-Agent' => 'AIappOnsite-Webhook/1.0', 'Accept' => 'application/json, */*;q=0.1', ); // Default to POST JSON if unsupported method if ($method !== 'POST' && $method !== 'GET') { $method = 'POST'; $format = 'json'; } // Prepare request args $args = array( 'method' => $method, 'timeout' => 20, 'blocking' => apply_filters('aiapp_webhook_blocking', false), 'headers' => $headers, 'redirection' => 0, // do not auto-follow 302; handle manually ); if ($method === 'POST') { if ($format === 'json') { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $args['data_format'] = 'body'; } else { $args['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; $args['body'] = $payload; } } elseif ($method === 'GET') { $url = add_query_arg($payload, $url); } // STEP A: send the request $response = wp_remote_request($url, $args); $log_data = array( 'webhook_id' => $webhook->id, 'endpoint' => $url, 'method' => $method, 'timestamp' => gmdate('c'), ); if (is_wp_error($response)) { $error_message = $response->get_error_message(); $log_data['status'] = 'error'; $log_data['error'] = $error_message; error_log("[AIappOnsite] Webhook {$webhook->id} failed: {$error_message}"); if ($response_id) { aiapp_jobs_mark_failed($response_id, $error_message); } } else { $status_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $location = wp_remote_retrieve_header($response, 'location'); // STEP B: handle Apps Script redirect manually (like curl -L) if (($status_code === 302 || $status_code === 303) && $location) { $follow_res = wp_remote_get($location, array( 'timeout' => 20, 'headers' => $headers, )); if (!is_wp_error($follow_res)) { $status_code = wp_remote_retrieve_response_code($follow_res); $body = wp_remote_retrieve_body($follow_res); } else { $log_data['status'] = 'error'; $log_data['error'] = $follow_res->get_error_message(); error_log("[AIappOnsite] Webhook {$webhook->id} follow-up failed: {$log_data['error']}"); } } $log_data['status_code'] = $status_code; $log_data['response'] = substr($body, 0, 500); if ($status_code >= 200 && $status_code < 300) { $log_data['status'] = 'success'; } else { $log_data['status'] = 'http_error'; error_log("[AIappOnsite] Webhook {$webhook->id} failed with HTTP {$status_code}: {$body}"); if ($response_id) { $should_retry = ($status_code >= 500 && $status_code < 600); aiapp_jobs_mark_failed($response_id, "HTTP {$status_code}: {$body}", $should_retry); } } } // Store webhook log if ($response_id && isset($payload['user_id'])) { $this->wpdb->update( $this->wpdb->prefix . 'ai_app_onsite_app_usage_statistics', array('webhook_triggered' => wp_json_encode($log_data)), array('user_id' => $payload['user_id']), array('%s'), array('%s') ); } } } // Initialize the webhook handler new AI_App_Onsite_Webhook_Handler(); }