18 mars 2024 · Tommy Bordas

Connecteurs et Intégrations WooCommerce

woocommercewordpressapiintegration

WooCommerce est une plateforme e-commerce puissante qui nécessite souvent des intégrations avec des systèmes externes. Voici mon approche pour créer des connecteurs robustes et maintenables.

Types d'Intégrations Courantes

  • ERP et systèmes de gestion
  • Plateformes logistiques
  • Outils de marketing automation
  • CRM et service client
  • Systèmes de paiement

Architecture des Connecteurs

Structure de Base

class WC_Integration_Base {
    protected $api_client;
    protected $logger;
    
    public function __construct() {
        $this->init_api_client();
        $this->init_hooks();
        $this->logger = wc_get_logger();
    }
    
    protected function init_hooks() {
        add_action('woocommerce_order_status_changed', [$this, 'handle_order_status_change'], 10, 3);
        add_action('woocommerce_new_order', [$this, 'handle_new_order']);
    }
}

Gestion des Événements

class WC_ERP_Integration extends WC_Integration_Base {
    public function handle_order_status_change($order_id, $old_status, $new_status) {
        try {
            $order = wc_get_order($order_id);
            $this->logger->info(
                sprintf('Synchronisation commande #%s: %s -> %s', $order_id, $old_status, $new_status),
                ['source' => 'erp-sync']
            );
            
            $this->api_client->syncOrder($order);
        } catch (Exception $e) {
            $this->logger->error(
                sprintf('Erreur sync commande #%s: %s', $order_id, $e->getMessage()),
                ['source' => 'erp-sync']
            );
        }
    }
}

Synchronisation des Données

Produits et Stock

class WC_Product_Sync {
    public function sync_product($external_product) {
        $product = new WC_Product_Simple();
        
        $product->set_name($external_product['name']);
        $product->set_regular_price($external_product['price']);
        $product->set_stock_quantity($external_product['stock']);
        
        $product->save();
        
        return $product;
    }
    
    public function update_stock($sku, $quantity) {
        $product = wc_get_product_id_by_sku($sku);
        if ($product) {
            wc_update_product_stock($product, $quantity);
        }
    }
}

Commandes

class WC_Order_Sync {
    public function export_order($order) {
        $data = [
            'order_number' => $order->get_order_number(),
            'status' => $order->get_status(),
            'customer' => [
                'email' => $order->get_billing_email(),
                'first_name' => $order->get_billing_first_name(),
                'last_name' => $order->get_billing_last_name()
            ],
            'items' => array_map(function($item) {
                return [
                    'sku' => $item->get_product()->get_sku(),
                    'quantity' => $item->get_quantity(),
                    'price' => $item->get_total()
                ];
            }, $order->get_items())
        ];
        
        return $data;
    }
}

Gestion des Erreurs

Retry System

class WC_Sync_Retry {
    private $max_retries = 3;
    
    public function handle_sync_failure($callback, $data) {
        $retry_count = get_option("sync_retry_{$data['id']}", 0);
        
        if ($retry_count < $this->max_retries) {
            as_schedule_single_action(
                time() + (300 * ($retry_count + 1)),
                'do_sync_retry',
                ['callback' => $callback, 'data' => $data]
            );
            
            update_option("sync_retry_{$data['id']}", $retry_count + 1);
        } else {
            $this->notify_admin_of_failure($data);
        }
    }
}

Monitoring

class WC_Integration_Monitor {
    public function check_sync_status() {
        $failed_syncs = $this->get_failed_syncs();
        
        if (count($failed_syncs) > 0) {
            $this->send_alert([
                'title' => 'Échecs de synchronisation détectés',
                'failures' => $failed_syncs,
                'timestamp' => current_time('mysql')
            ]);
        }
    }
}

Sécurité et Performance

Authentification

class WC_API_Auth {
    public function validate_request() {
        $signature = $_SERVER['HTTP_X_API_SIGNATURE'] ?? '';
        $timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
        
        if (!$this->is_valid_timestamp($timestamp)) {
            return false;
        }
        
        return $this->verify_signature($signature, $timestamp);
    }
}

Cache

class WC_Integration_Cache {
    public function get_cached_data($key) {
        $data = wp_cache_get($key, 'integration_cache');
        
        if (false === $data) {
            $data = $this->fetch_fresh_data($key);
            wp_cache_set($key, $data, 'integration_cache', 3600);
        }
        
        return $data;
    }
}

Tests et Validation

Tests Unitaires

class WC_Integration_Test extends WP_UnitTestCase {
    public function test_order_sync() {
        $order = $this->create_test_order();
        $sync = new WC_Order_Sync();
        
        $result = $sync->export_order($order);
        
        $this->assertEquals($order->get_order_number(), $result['order_number']);
        $this->assertArrayHasKey('items', $result);
    }
}

Résultats et Bénéfices

  1. Fiabilité

    • Synchronisation robuste
    • Gestion des erreurs efficace
    • Monitoring en temps réel
  2. Performance

    • Optimisation des requêtes
    • Mise en cache intelligente
    • Traitement asynchrone
  3. Maintenance

    • Code modulaire
    • Tests automatisés
    • Documentation claire

Conclusion

Des connecteurs bien conçus sont essentiels pour une boutique WooCommerce performante. Cette approche garantit des intégrations fiables et maintenables avec vos systèmes externes.