March 18, 2024 · Tommy Bordas

WooCommerce Connectors and Integrations

woocommercewordpressapiintegration

WooCommerce is a powerful e-commerce platform that often requires integration with external systems. Here's my approach to creating robust and maintainable connectors.

Common Integration Types

  • ERP and management systems
  • Logistics platforms
  • Marketing automation tools
  • CRM and customer service
  • Payment systems

Connector Architecture

Base Structure

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']);
    }
}

Event Handling

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('Syncing order #%s: %s -> %s', $order_id, $old_status, $new_status),
                ['source' => 'erp-sync']
            );
            
            $this->api_client->syncOrder($order);
        } catch (Exception $e) {
            $this->logger->error(
                sprintf('Error syncing order #%s: %s', $order_id, $e->getMessage()),
                ['source' => 'erp-sync']
            );
        }
    }
}

Data Synchronization

Products and 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);
        }
    }
}

Orders

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;
    }
}

Error Handling

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' => 'Sync failures detected',
                'failures' => $failed_syncs,
                'timestamp' => current_time('mysql')
            ]);
        }
    }
}

Security and Performance

Authentication

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);
    }
}

Caching

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;
    }
}

Testing and Validation

Unit Tests

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);
    }
}

Results and Benefits

  1. Reliability

    • Robust synchronization
    • Efficient error handling
    • Real-time monitoring
  2. Performance

    • Query optimization
    • Smart caching
    • Asynchronous processing
  3. Maintenance

    • Modular code
    • Automated testing
    • Clear documentation

Conclusion

Well-designed connectors are essential for a high-performing WooCommerce store. This approach ensures reliable and maintainable integrations with your external systems.