WooCommerce REST API 深度开发指南

API 基础架构与认证

1.1 REST API 核心配置

WooCommerce REST API 采用 OAuth 1.0a 和 HTTP Basic Auth 两种认证方式。在 wp-config.php中启用 API 支持:

define('WC_API_ENABLED', true);
define('WC_API_DEBUG', false);

1.2 密钥生成与管理

在 WooCommerce 后台生成 API 密钥:

// 自动生成API密钥的函数
function generate_wc_api_keys($user_id, $description) {
    $consumer_key = 'ck_' . wc_rand_hash();
    $consumer_secret = 'cs_' . wc_rand_hash();
    
    update_user_meta($user_id, 'woocommerce_api_consumer_key', $consumer_key);
    update_user_meta($user_id, 'woocommerce_api_consumer_secret', $consumer_secret);
    update_user_meta($user_id, 'woocommerce_api_key_description', $description);
    
    return [
        'consumer_key' => $consumer_key,
        'consumer_secret' => $consumer_secret
    ];
}

订单管理 API

2.1 订单创建与处理

/**
 * 通过API创建订单
 */
function create_order_via_api($order_data) {
    $wc_api_url = home_url('/wp-json/wc/v3/orders');
    
    $response = wp_remote_post($wc_api_url, [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
            'Content-Type' => 'application/json'
        ],
        'body' => json_encode([
            'payment_method' => 'bacs',
            'payment_method_title' => '银行转账',
            'set_paid' => true,
            'billing' => [
                'first_name' => $order_data['billing_first_name'],
                'last_name' => $order_data['billing_last_name'],
                'address_1' => $order_data['billing_address_1'],
                'city' => $order_data['billing_city'],
                'state' => $order_data['billing_state'],
                'postcode' => $order_data['billing_postcode'],
                'country' => $order_data['billing_country'],
                'email' => $order_data['billing_email'],
                'phone' => $order_data['billing_phone']
            ],
            'shipping' => [
                'first_name' => $order_data['shipping_first_name'],
                'last_name' => $order_data['shipping_last_name'],
                'address_1' => $order_data['shipping_address_1'],
                'city' => $order_data['shipping_city'],
                'state' => $order_data['shipping_state'],
                'postcode' => $order_data['shipping_postcode'],
                'country' => $order_data['shipping_country']
            ],
            'line_items' => [
                [
                    'product_id' => $order_data['product_id'],
                    'quantity' => $order_data['quantity'],
                    'variation_id' => $order_data['variation_id'] ?? 0
                ]
            ],
            'shipping_lines' => [
                [
                    'method_id' => 'flat_rate',
                    'method_title' => '快递',
                    'total' => $order_data['shipping_cost']
                ]
            ]
        ]),
        'timeout' => 30
    ]);
    
    if (is_wp_error($response)) {
        throw new Exception('订单创建失败: ' . $response->get_error_message());
    }
    
    $response_code = wp_remote_retrieve_response_code($response);
    $body = json_decode(wp_remote_retrieve_body($response), true);
    
    if ($response_code === 201) {
        return $body['id'];
    } else {
        throw new Exception('API错误: ' . ($body['message'] ?? '未知错误'));
    }
}

2.2 订单状态批量更新

/**
 * 批量更新订单状态
 */
function bulk_update_order_status($order_ids, $new_status) {
    $results = [];
    
    foreach ($order_ids as $order_id) {
        $api_url = home_url("/wp-json/wc/v3/orders/{$order_id}");
        
        $response = wp_remote_request($api_url, [
            'method' => 'PUT',
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode([
                'status' => $new_status
            ])
        ]);
        
        $results[$order_id] = !is_wp_error($response) && 
                             wp_remote_retrieve_response_code($response) === 200;
    }
    
    return $results;
}

产品管理 API

3.1 产品同步与库存管理

class Product_Sync_Manager {
    private $api_base;
    
    public function __construct() {
        $this->api_base = home_url('/wp-json/wc/v3');
    }
    
    /**
     * 同步外部产品到WooCommerce
     */
    public function sync_external_products($external_products) {
        $synced_products = [];
        
        foreach ($external_products as $external_product) {
            $existing_product = $this->find_product_by_sku($external_product['sku']);
            
            if ($existing_product) {
                $product_id = $this->update_product($existing_product['id'], $external_product);
            } else {
                $product_id = $this->create_product($external_product);
            }
            
            if ($product_id) {
                $synced_products[] = [
                    'id' => $product_id,
                    'name' => $external_product['name'],
                    'status' => 'synced'
                ];
            }
        }
        
        return $synced_products;
    }
    
    private function find_product_by_sku($sku) {
        $response = wp_remote_get($this->api_base . '/products?sku=' . urlencode($sku), [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET)
            ]
        ]);
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $products = json_decode(wp_remote_retrieve_body($response), true);
            return !empty($products) ? $products[0] : null;
        }
        
        return null;
    }
    
    private function create_product($product_data) {
        $response = wp_remote_post($this->api_base . '/products', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode([
                'name' => $product_data['name'],
                'type' => $product_data['type'] ?? 'simple',
                'regular_price' => $product_data['price'],
                'description' => $product_data['description'],
                'short_description' => $product_data['short_description'] ?? '',
                'sku' => $product_data['sku'],
                'stock_quantity' => $product_data['stock_quantity'],
                'manage_stock' => true,
                'stock_status' => $product_data['stock_quantity'] > 0 ? 'instock' : 'outofstock',
                'categories' => $this->prepare_categories($product_data['categories'])
            ])
        ]);
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 201) {
            $product = json_decode(wp_remote_retrieve_body($response), true);
            return $product['id'];
        }
        
        return false;
    }
}

3.2 产品变体管理

/**
 * 处理可变产品变体
 */
function manage_product_variations($product_id, $variations) {
    $api_url = home_url("/wp-json/wc/v3/products/{$product_id}/variations");
    $results = [];
    
    foreach ($variations as $variation) {
        $variation_data = [
            'regular_price' => $variation['price'],
            'stock_quantity' => $variation['stock'],
            'attributes' => array_map(function($attr) {
                return [
                    'name' => $attr['name'],
                    'option' => $attr['value']
                ];
            }, $variation['attributes'])
        ];
        
        $method = $variation['id'] ? 'PUT' : 'POST';
        $url = $variation['id'] ? $api_url . '/' . $variation['id'] : $api_url;
        
        $response = wp_remote_request($url, [
            'method' => $method,
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode($variation_data)
        ]);
        
        $results[] = [
            'variation' => $variation,
            'success' => !is_wp_error($response) && 
                        in_array(wp_remote_retrieve_response_code($response), [200, 201]),
            'response' => !is_wp_error($response) ? json_decode(wp_remote_retrieve_body($response), true) : null
        ];
    }
    
    return $results;
}

客户管理 API

4.1 客户数据同步

class Customer_Sync_Manager {
    private $api_base;
    
    public function __construct() {
        $this->api_base = home_url('/wp-json/wc/v3');
    }
    
    /**
     * 从CRM同步客户数据
     */
    public function sync_customers_from_crm($crm_customers) {
        $sync_results = [];
        
        foreach ($crm_customers as $crm_customer) {
            $existing_customer = $this->find_customer_by_email($crm_customer['email']);
            
            if ($existing_customer) {
                $result = $this->update_customer($existing_customer['id'], $crm_customer);
            } else {
                $result = $this->create_customer($crm_customer);
            }
            
            $sync_results[] = [
                'crm_id' => $crm_customer['id'],
                'wc_id' => $result['id'] ?? null,
                'status' => $result['success'] ? 'synced' : 'failed',
                'message' => $result['message'] ?? ''
            ];
        }
        
        return $sync_results;
    }
    
    private function find_customer_by_email($email) {
        $response = wp_remote_get($this->api_base . '/customers?email=' . urlencode($email), [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET)
            ]
        ]);
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $customers = json_decode(wp_remote_retrieve_body($response), true);
            return !empty($customers) ? $customers[0] : null;
        }
        
        return null;
    }
    
    private function create_customer($customer_data) {
        $response = wp_remote_post($this->api_base . '/customers', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode([
                'email' => $customer_data['email'],
                'first_name' => $customer_data['first_name'],
                'last_name' => $customer_data['last_name'],
                'billing' => [
                    'first_name' => $customer_data['first_name'],
                    'last_name' => $customer_data['last_name'],
                    'company' => $customer_data['company'] ?? '',
                    'address_1' => $customer_data['address'] ?? '',
                    'city' => $customer_data['city'] ?? '',
                    'state' => $customer_data['state'] ?? '',
                    'postcode' => $customer_data['postcode'] ?? '',
                    'country' => $customer_data['country'] ?? '',
                    'email' => $customer_data['email'],
                    'phone' => $customer_data['phone'] ?? ''
                ],
                'shipping' => [
                    'first_name' => $customer_data['first_name'],
                    'last_name' => $customer_data['last_name'],
                    'company' => $customer_data['company'] ?? '',
                    'address_1' => $customer_data['address'] ?? '',
                    'city' => $customer_data['city'] ?? '',
                    'state' => $customer_data['state'] ?? '',
                    'postcode' => $customer_data['postcode'] ?? '',
                    'country' => $customer_data['country'] ?? ''
                ],
                'meta_data' => [
                    [
                        'key' => 'crm_id',
                        'value' => $customer_data['id']
                    ]
                ]
            ])
        ]);
        
        return $this->parse_response($response);
    }
}

Webhooks 集成

5.1 Webhook 管理

class Webhook_Manager {
    /**
     * 创建订单相关的Webhook
     */
    public function setup_order_webhooks() {
        $webhooks = [
            [
                'name' => '订单创建通知',
                'topic' => 'order.created',
                'delivery_url' => 'https://your-app.com/webhooks/order-created'
            ],
            [
                'name' => '订单更新通知',
                'topic' => 'order.updated',
                'delivery_url' => 'https://your-app.com/webhooks/order-updated'
            ],
            [
                'name' => '订单删除通知',
                'topic' => 'order.deleted',
                'delivery_url' => 'https://your-app.com/webhooks/order-deleted'
            ]
        ];
        
        $results = [];
        foreach ($webhooks as $webhook_config) {
            $results[] = $this->create_webhook($webhook_config);
        }
        
        return $results;
    }
    
    private function create_webhook($config) {
        $response = wp_remote_post(home_url('/wp-json/wc/v3/webhooks'), [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode([
                'name' => $config['name'],
                'topic' => $config['topic'],
                'delivery_url' => $config['delivery_url'],
                'secret' => $this->generate_webhook_secret(),
                'status' => 'active'
            ])
        ]);
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 201) {
            $webhook = json_decode(wp_remote_retrieve_body($response), true);
            return [
                'success' => true,
                'id' => $webhook['id'],
                'secret' => $webhook['secret']
            ];
        }
        
        return [
            'success' => false,
            'error' => is_wp_error($response) ? $response->get_error_message() : '创建失败'
        ];
    }
    
    private function generate_webhook_secret() {
        return 'whsec_' . bin2hex(random_bytes(32));
    }
}

5.2 Webhook 验证处理

/**
 * 验证和处理Webhook请求
 */
function handle_webhook_request() {
    // 验证签名
    $signature = $_SERVER['HTTP_X_WC_WEBHOOK_SIGNATURE'] ?? '';
    $payload = file_get_contents('php://input');
    
    if (!$this->verify_signature($signature, $payload)) {
        http_response_code(401);
        exit('Invalid signature');
    }
    
    $data = json_decode($payload, true);
    $topic = $_SERVER['HTTP_X_WC_WEBHOOK_TOPIC'] ?? '';
    
    switch ($topic) {
        case 'order.created':
            $this->process_order_created($data);
            break;
        case 'order.updated':
            $this->process_order_updated($data);
            break;
        case 'product.updated':
            $this->process_product_updated($data);
            break;
    }
    
    http_response_code(200);
    echo 'Webhook processed successfully';
}

高级功能与优化

6.1 批量操作处理

/**
 * 批量产品更新
 */
function batch_update_products($products_data) {
    $api_url = home_url('/wp-json/wc/v3/products/batch');
    
    $update_data = [
        'update' => []
    ];
    
    foreach ($products_data as $product_data) {
        $update_data['update'][] = [
            'id' => $product_data['id'],
            'regular_price' => $product_data['price'],
            'sale_price' => $product_data['sale_price'] ?? '',
            'stock_quantity' => $product_data['stock'],
            'meta_data' => [
                [
                    'key' => 'last_updated',
                    'value' => current_time('mysql')
                ]
            ]
        ];
    }
    
    $response = wp_remote_post($api_url, [
        'headers' => [
            'Authorization' => 'Basic ' . base64_encode(CONSUMER_KEY . ':' . CONSUMER_SECRET),
            'Content-Type' => 'application/json'
        ],
        'body' => json_encode($update_data),
        'timeout' => 60 // 批量操作需要更长时间
    ]);
    
    return $this->parse_batch_response($response);
}

6.2 API 速率限制处理

class Rate_Limited_API_Client {
    private $requests_made = 0;
    private $last_request_time = 0;
    private $rate_limit = 30; // 每分钟30个请求
    private $time_window = 60; // 60秒窗口
    
    public function make_request($url, $args = []) {
        $this->enforce_rate_limit();
        
        $response = wp_remote_request($url, $args);
        
        $this->requests_made++;
        $this->last_request_time = time();
        
        // 检查速率限制头
        $headers = wp_remote_retrieve_headers($response);
        if (isset($headers['X-WP-API-Limit'])) {
            $this->handle_rate_limit_headers($headers);
        }
        
        return $response;
    }
    
    private function enforce_rate_limit() {
        $elapsed = time() - $this->last_request_time;
        
        if ($elapsed < $this->time_window && $this->requests_made >= $this->rate_limit) {
            $sleep_time = $this->time_window - $elapsed + 1;
            sleep($sleep_time);
            $this->requests_made = 0;
        } elseif ($elapsed >= $this->time_window) {
            $this->requests_made = 0;
        }
    }
}

错误处理与监控

7.1 综合错误处理系统

class API_Error_Handler {
    public static function handle_response($response, $context = '') {
        if (is_wp_error($response)) {
            return self::log_error(
                'http_error',
                $response->get_error_message(),
                $context,
                ['error_code' => $response->get_error_code()]
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        if ($status_code >= 400) {
            $error_data = json_decode($body, true) ?? ['raw_response' => $body];
            
            return self::log_error(
                'api_error',
                "HTTP {$status_code}",
                $context,
                array_merge($error_data, ['status_code' => $status_code])
            );
        }
        
        return [
            'success' => true,
            'data' => json_decode($body, true)
        ];
    }
    
    private static function log_error($type, $message, $context, $data = []) {
        $log_entry = [
            'timestamp' => current_time('mysql'),
            'type' => $type,
            'message' => $message,
            'context' => $context,
            'data' => $data
        ];
        
        error_log('WooCommerce API Error: ' . json_encode($log_entry));
        
        // 发送到监控服务
        if (defined('API_MONITOR_URL')) {
            wp_remote_post(API_MONITOR_URL, [
                'body' => json_encode($log_entry),
                'blocking' => false // 非阻塞发送
            ]);
        }
        
        return [
            'success' => false,
            'error' => $message,
            'details' => $data
        ];
    }
}

通过以上完整的 WooCommerce API 集成方案,开发者可以构建强大的电商管理系统,实现订单处理、产品同步、客户管理和实时通知等高级功能。

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

1855-626-3292

微信咨询