false, 'sync_started' => false, 'enrichment_sent' => false, 'scrape_started' => false, 'errors' => [], ]; // Step 1: Auto-generate WC REST API keys $wc_keys = self::generate_wc_api_keys(); if (is_wp_error($wc_keys)) { $results['errors'][] = 'WC keys: ' . $wc_keys->get_error_message(); return $results; } // Step 2: Send credentials to AddToChat API $shop_url = get_site_url(); $connect_result = self::connect_woocommerce($api_key, $shop_url, $wc_keys['consumer_key'], $wc_keys['consumer_secret']); if (is_wp_error($connect_result)) { $results['errors'][] = 'Connect: ' . $connect_result->get_error_message(); return $results; } $results['wc_connected'] = true; update_option('addtaisa_connected', true); update_option('addtaisa_shop_url', $shop_url); // Step 3: Trigger catalog sync $sync = self::trigger_sync($api_key); if (!is_wp_error($sync)) { $results['sync_started'] = true; update_option('addtaisa_last_sync', current_time('mysql')); // Step 3b: Enrich products and send extra data to API $enrich_result = self::enrich_and_send($api_key); if (!is_wp_error($enrich_result)) { $results['enrichment_sent'] = true; } else { $results['errors'][] = 'Enrichment: ' . $enrich_result->get_error_message(); } } else { $results['errors'][] = 'Sync: ' . $sync->get_error_message(); } // Step 4: Auto-discover & scrape site content $scrape = self::trigger_auto_scrape($api_key); if (!is_wp_error($scrape)) { $results['scrape_started'] = true; } else { $results['errors'][] = 'Scrape: ' . $scrape->get_error_message(); } return $results; } /** * Generate WooCommerce REST API keys programmatically. * Uses the wc_create_api_key approach or direct DB insert. */ private static function generate_wc_api_keys(): array|WP_Error { if (!class_exists('WooCommerce')) { return new WP_Error('no_wc', 'WooCommerce non détecté'); } global $wpdb; // Direct DB queries on WC internal tables — no REST API / CRUD exists for // `woocommerce_api_keys`. One-shot operation at connection time, not hot path; // caching would add complexity with no perf benefit. // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $existing = $wpdb->get_row( $wpdb->prepare( "SELECT consumer_key, consumer_secret, truncated_key FROM {$wpdb->prefix}woocommerce_api_keys WHERE description = %s AND permissions = %s LIMIT 1", 'AddToChat - Auto', 'read_write' ) ); if ($existing) { // Keys exist but we only have truncated_key in DB (WC hashes the full key) // We need to regenerate since we can't recover the original $wpdb->delete( "{$wpdb->prefix}woocommerce_api_keys", ['description' => 'AddToChat - Auto', 'permissions' => 'read_write'] ); } // phpcs:enable // Generate new keys $consumer_key = 'ck_' . wc_rand_hash(); $consumer_secret = 'cs_' . wc_rand_hash(); $data = [ 'user_id' => get_current_user_id(), 'description' => 'AddToChat - Auto', 'permissions' => 'read_write', 'consumer_key' => wc_api_hash($consumer_key), 'consumer_secret' => $consumer_secret, 'truncated_key' => substr($consumer_key, -7), ]; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- one-shot WC key creation, WP has no high-level API for woocommerce_api_keys. $wpdb->insert("{$wpdb->prefix}woocommerce_api_keys", $data); if ($wpdb->insert_id === 0) { return new WP_Error('db_error', 'Impossible de créer les clés WC API'); } return [ 'consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, ]; } /** * Send WC credentials to AddToChat API. */ private static function connect_woocommerce(string $api_key, string $shop_url, string $ck, string $cs): array|WP_Error { $response = wp_remote_post(ADDTAISA_API_URL . '/v1/merchants/me/connect-woocommerce', [ 'headers' => [ 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', ], 'body' => wp_json_encode([ 'shop_url' => $shop_url, 'consumer_key' => $ck, 'consumer_secret' => $cs, 'language' => substr(get_locale(), 0, 2), 'locale' => get_locale(), ]), 'timeout' => 15, ]); if (is_wp_error($response)) return $response; $code = wp_remote_retrieve_response_code($response); if ($code >= 400) { $body = json_decode(wp_remote_retrieve_body($response), true); return new WP_Error('api_error', $body['error']['message'] ?? "Erreur API ($code)"); } return json_decode(wp_remote_retrieve_body($response), true) ?: []; } /** * Trigger catalog sync via API. */ private static function trigger_sync(string $api_key): array|WP_Error { $response = wp_remote_post(ADDTAISA_API_URL . '/v1/catalog/sync', [ 'headers' => [ 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', ], 'timeout' => 15, ]); if (is_wp_error($response)) return $response; $code = wp_remote_retrieve_response_code($response); if ($code >= 400) { return new WP_Error('sync_error', 'Sync failed (code ' . $code . ')'); } return []; } /** * Run the product enricher and POST the enriched data to the API. */ private static function enrich_and_send(string $api_key): array|WP_Error { if (!class_exists('Addtaisa_Product_Enricher')) { return new WP_Error('no_enricher', 'Product enricher class not loaded'); } $enriched = Addtaisa_Product_Enricher::enrich_all(); if (empty($enriched)) { return []; // Nothing to enrich, not an error } // Map to the API format: { external_id, extra_data } $items = array_map(function ($item) { return [ 'external_id' => $item['product_id'], 'extra_data' => $item['extra_data'], ]; }, $enriched); // Send in batches of 500 (API limit) $batches = array_chunk($items, 500); $total_updated = 0; foreach ($batches as $batch) { $response = wp_remote_post(ADDTAISA_API_URL . '/v1/catalog/enrich', [ 'headers' => [ 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', ], 'body' => wp_json_encode(['items' => $batch]), 'timeout' => 30, ]); if (is_wp_error($response)) return $response; $code = wp_remote_retrieve_response_code($response); if ($code >= 400) { return new WP_Error('enrich_error', 'Enrichment failed (code ' . $code . ')'); } $body = json_decode(wp_remote_retrieve_body($response), true); $total_updated += ($body['data']['updated'] ?? 0); } return ['updated' => $total_updated]; } /** * Trigger auto-discover + scrape of site content. */ private static function trigger_auto_scrape(string $api_key): array|WP_Error { $response = wp_remote_post(ADDTAISA_API_URL . '/v1/scraping/auto-discover', [ 'headers' => [ 'X-API-Key' => $api_key, 'Content-Type' => 'application/json', ], 'timeout' => 15, ]); if (is_wp_error($response)) return $response; $code = wp_remote_retrieve_response_code($response); if ($code >= 400) { return new WP_Error('scrape_error', 'Auto-discover failed (code ' . $code . ')'); } return []; } }