首页 / 教程文章 / WordPress小批量定制插件与CRM系统集成开发教程

WordPress小批量定制插件与CRM系统集成开发教程

WordPress小批量定制插件与CRM系统集成开发教程

概述

在当今数字化商业环境中,将WordPress网站与客户关系管理(CRM)系统集成已成为提升业务效率的关键策略。本教程将指导您开发一个WordPress定制插件,实现与CRM系统的双向数据同步,特别适合小批量定制业务场景。通过本教程,您将学习到完整的插件开发流程、API集成技术以及数据处理最佳实践。

环境准备与插件基础结构

首先,我们需要创建插件的基本文件结构。在WordPress的wp-content/plugins/目录下创建一个新文件夹,命名为custom-crm-integration

<?php
/**
 * Plugin Name: 小批量定制CRM集成
 * Plugin URI: https://yourwebsite.com/
 * Description: 将WordPress小批量定制订单与CRM系统集成
 * Version: 1.0.0
 * Author: 您的名称
 * License: GPL v2 or later
 * Text Domain: custom-crm-integration
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('CUSTOM_CRM_VERSION', '1.0.0');
define('CUSTOM_CRM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CUSTOM_CRM_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
class Custom_CRM_Integration {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->init_hooks();
    }
    
    private function init_hooks() {
        // 激活/停用插件钩子
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // 初始化
        add_action('init', array($this, 'init'));
        
        // 管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 保存设置
        add_action('admin_post_save_crm_settings', array($this, 'save_settings'));
    }
    
    public function activate() {
        // 创建必要的数据库表
        $this->create_tables();
        
        // 设置默认选项
        add_option('crm_integration_version', CUSTOM_CRM_VERSION);
    }
    
    public function deactivate() {
        // 清理临时数据
        // 注意:这里不清除设置,以便重新激活时保留配置
    }
    
    public function init() {
        // 加载文本域
        load_plugin_textdomain('custom-crm-integration', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }
    
    private function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'custom_crm_sync_log';
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            sync_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            operation_type varchar(50) NOT NULL,
            entity_type varchar(50) NOT NULL,
            entity_id varchar(100) NOT NULL,
            status varchar(50) NOT NULL,
            message text,
            PRIMARY KEY (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}

// 启动插件
Custom_CRM_Integration::get_instance();
?>

CRM API连接类

接下来,我们创建一个处理CRM API通信的类。这个类将负责所有与CRM系统的交互。

<?php
/**
 * CRM API连接处理器
 */

class CRM_API_Handler {
    
    private $api_url;
    private $api_key;
    private $api_secret;
    
    public function __construct($api_url, $api_key, $api_secret) {
        $this->api_url = rtrim($api_url, '/');
        $this->api_key = $api_key;
        $this->api_secret = $api_secret;
    }
    
    /**
     * 发送请求到CRM API
     * 
     * @param string $endpoint API端点
     * @param array $data 发送的数据
     * @param string $method HTTP方法 (GET, POST, PUT, DELETE)
     * @return array 响应数据
     */
    public function send_request($endpoint, $data = array(), $method = 'POST') {
        
        $url = $this->api_url . '/' . ltrim($endpoint, '/');
        
        // 准备请求头
        $headers = array(
            'Content-Type' => 'application/json',
            'X-API-Key' => $this->api_key,
            'X-API-Secret' => $this->api_secret,
        );
        
        // 准备请求参数
        $args = array(
            'method' => $method,
            'headers' => $headers,
            'timeout' => 30,
            'sslverify' => false, // 根据您的SSL配置调整
        );
        
        // 如果是GET请求,将参数添加到URL
        if ($method === 'GET' && !empty($data)) {
            $url = add_query_arg($data, $url);
        } else {
            $args['body'] = json_encode($data);
        }
        
        // 发送请求
        $response = wp_remote_request($url, $args);
        
        // 处理响应
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'error' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        // 解析JSON响应
        $data = json_decode($response_body, true);
        
        return array(
            'success' => ($response_code >= 200 && $response_code < 300),
            'code' => $response_code,
            'data' => $data
        );
    }
    
    /**
     * 创建CRM客户
     * 
     * @param array $customer_data 客户数据
     * @return array 响应结果
     */
    public function create_customer($customer_data) {
        // 验证必要字段
        $required_fields = array('email', 'first_name', 'last_name');
        foreach ($required_fields as $field) {
            if (empty($customer_data[$field])) {
                return array(
                    'success' => false,
                    'error' => "缺少必要字段: $field"
                );
            }
        }
        
        // 标准化数据格式
        $crm_customer_data = array(
            'customer' => array(
                'email' => sanitize_email($customer_data['email']),
                'firstName' => sanitize_text_field($customer_data['first_name']),
                'lastName' => sanitize_text_field($customer_data['last_name']),
                'phone' => isset($customer_data['phone']) ? sanitize_text_field($customer_data['phone']) : '',
                'company' => isset($customer_data['company']) ? sanitize_text_field($customer_data['company']) : '',
                'customFields' => array(
                    'wordpress_user_id' => isset($customer_data['user_id']) ? intval($customer_data['user_id']) : 0,
                    'registration_date' => date('Y-m-d H:i:s')
                )
            )
        );
        
        return $this->send_request('/api/v1/customers', $crm_customer_data, 'POST');
    }
    
    /**
     * 创建CRM订单
     * 
     * @param array $order_data 订单数据
     * @return array 响应结果
     */
    public function create_order($order_data) {
        // 验证必要字段
        if (empty($order_data['customer_id']) || empty($order_data['items'])) {
            return array(
                'success' => false,
                'error' => '缺少客户ID或订单项目'
            );
        }
        
        // 处理订单项目
        $order_items = array();
        foreach ($order_data['items'] as $item) {
            $order_items[] = array(
                'productId' => isset($item['product_id']) ? intval($item['product_id']) : 0,
                'productName' => sanitize_text_field($item['name']),
                'quantity' => intval($item['quantity']),
                'unitPrice' => floatval($item['price']),
                'customizations' => isset($item['customizations']) ? $item['customizations'] : array()
            );
        }
        
        $crm_order_data = array(
            'order' => array(
                'customerId' => intval($order_data['customer_id']),
                'orderNumber' => sanitize_text_field($order_data['order_number']),
                'orderDate' => date('Y-m-d H:i:s'),
                'totalAmount' => floatval($order_data['total']),
                'status' => 'pending',
                'items' => $order_items,
                'notes' => isset($order_data['notes']) ? sanitize_textarea_field($order_data['notes']) : '',
                'metadata' => array(
                    'wordpress_order_id' => intval($order_data['wordpress_order_id']),
                    'source' => 'wordpress_custom_plugin'
                )
            )
        );
        
        return $this->send_request('/api/v1/orders', $crm_order_data, 'POST');
    }
    
    /**
     * 根据邮箱查找CRM客户
     * 
     * @param string $email 客户邮箱
     * @return array 客户数据或错误信息
     */
    public function find_customer_by_email($email) {
        $response = $this->send_request('/api/v1/customers/search', array('email' => $email), 'GET');
        
        if ($response['success'] && !empty($response['data']['customers'])) {
            return array(
                'success' => true,
                'customer' => $response['data']['customers'][0]
            );
        }
        
        return array(
            'success' => false,
            'error' => '未找到客户'
        );
    }
}
?>

WooCommerce订单同步功能

对于小批量定制业务,通常使用WooCommerce处理订单。以下代码展示了如何将WooCommerce订单同步到CRM系统。

<?php
/**
 * WooCommerce订单同步
 */

class WooCommerce_CRM_Sync {
    
    private $crm_handler;
    
    public function __construct($crm_handler) {
        $this->crm_handler = $crm_handler;
        
        // 钩子:新订单创建时
        add_action('woocommerce_checkout_order_processed', array($this, 'sync_new_order'), 10, 3);
        
        // 钩子:订单状态更新时
        add_action('woocommerce_order_status_changed', array($this, 'sync_order_status'), 10, 4);
        
        // 钩子:手动同步操作
        add_action('admin_post_manual_order_sync', array($this, 'manual_order_sync'));
    }
    
    /**
     * 同步新订单到CRM
     */
    public function sync_new_order($order_id, $posted_data, $order) {
        
        // 获取订单对象
        if (!is_a($order, 'WC_Order')) {
            $order = wc_get_order($order_id);
        }
        
        // 检查是否应该同步此订单
        if (!$this->should_sync_order($order)) {
            $this->log_sync_operation('order', $order_id, 'skipped', '订单不符合同步条件');
            return;
        }
        
        // 获取客户信息
        $customer_email = $order->get_billing_email();
        $customer_data = array(
            'email' => $customer_email,
            'first_name' => $order->get_billing_first_name(),
            'last_name' => $order->get_billing_last_name(),
            'phone' => $order->get_billing_phone(),
            'company' => $order->get_billing_company(),
            'user_id' => $order->get_customer_id()
        );
        
        // 查找或创建CRM客户
        $customer_result = $this->crm_handler->find_customer_by_email($customer_email);
        
        if (!$customer_result['success']) {
            // 客户不存在,创建新客户
            $customer_result = $this->crm_handler->create_customer($customer_data);
            
            if (!$customer_result['success']) {
                $this->log_sync_operation('customer', $customer_email, 'failed', '创建客户失败: ' . $customer_result['error']);
                return;
            }
            
            $crm_customer_id = $customer_result['data']['customer']['id'];
            $this->log_sync_operation('customer', $customer_email, 'success', '客户创建成功,ID: ' . $crm_customer_id);
        } else {
            $crm_customer_id = $customer_result['customer']['id'];
        }
        
        // 准备订单数据
        $order_items = array();
        foreach ($order->get_items() as $item_id => $item) {
            $product = $item->get_product();
            
            // 获取定制化信息(假设存储在订单项meta中)
            $customizations = array();
            $item_meta = $item->get_meta_data();
            foreach ($item_meta as $meta) {
                if (strpos($meta->key, 'custom_') === 0) {
                    $customizations[$meta->key] = $meta->value;
                }
            }
            
            $order_items[] = array(
                'product_id' => $item->get_product_id(),
                'name' => $item->get_name(),
                'quantity' => $item->get_quantity(),
                'price' => $item->get_total() / $item->get_quantity(),
                'customizations' => $customizations
            );
        }
        
        $order_data = array(
            'customer_id' => $crm_customer_id,
            'order_number' => $order->get_order_number(),
            'total' => $order->get_total(),
            'wordpress_order_id' => $order_id,
            'items' => $order_items,
            'notes' => $order->get_customer_note()
        );
        
        // 创建CRM订单
        $order_result = $this->crm_handler->create_order($order_data);
        
        if ($order_result['success']) {
            // 保存CRM订单ID到WordPress订单meta
            $crm_order_id = $order_result['data']['order']['id'];
            $order->update_meta_data('_crm_order_id', $crm_order_id);
            $order->save();
            
            $this->log_sync_operation('order', $order_id, 'success', '订单同步成功,CRM订单ID: ' . $crm_order_id);
        } else {
            $this->log_sync_operation('order', $order_id, 'failed', '订单同步失败: ' . $order_result['error']);
        }
    }
    
    /**
     * 同步订单状态更新
     */
    public function sync_order_status($order_id, $old_status, $new_status, $order) {
        
        // 获取CRM订单ID
        $crm_order_id = $order->get_meta('_crm_order_id');
        
        if (empty($crm_order_id)) {
            return; // 未同步的订单,跳过
        }
        
        // 映射WooCommerce状态到CRM状态
        $status_map = array(
            'pending' => 'pending',
            'processing' => 'processing',
            'on-hold' => 'on_hold',
            'completed' => 'completed',
            'cancelled' => 'cancelled',
            'refunded' => 'refunded',
            'failed' => 'failed'
        );
        
        $crm_status = isset($status_map[$new_status]) ? $status_map[$new_status] : 'pending';
        
        // 更新CRM订单状态
        $update_data = array(
            'order' => array(
                'status' => $crm_status,
                'statusNotes' => "状态从 {$old_status} 更新为 {$new_status}"
            )
        );
        
        $response = $this->crm_handler->send_request("/api/v1/orders/{$crm_order_id}", $update_data, 'PUT');
        
        if ($response['success']) {
            $this->log_sync_operation('order_status', $order_id, 'success', "状态更新: {$old_status} → {$new_status}");
        } else {
            $this->log_sync_operation('order_status', $order_id, 'failed', '状态更新失败: ' . $response['error']);
        }
    }
    
    /**
     * 检查是否应该同步订单
     */
    private function should_sync_order($order) {
        // 排除特定支付方式的订单
        $excluded_gateways = array('cod', 'bacs');
        if (in_array($order->get_payment_method(), $excluded_gateways)) {
            return false;
        }
        
        // 只同步特定产品类型的订单
        $has_custom_product = false;
        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            if ($product && $product->get_meta('_is_custom_product')) {
                $has_custom_product = true;
                break;
            }
        }
        
        return $has_custom_product;
    }
    
    /**
     * 记录同步操作
     */
    private function log_sync_operation($entity_type, $entity_id, $status, $message = '') {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'custom_crm_sync_log';
        
        $wpdb->insert(
            $table_name,
            array(
                'operation_type' => 'auto_sync',
                'entity_type' => $entity_type,
                'entity_id' => $entity_id,
                'status' => $status,
                'message' => $message
            ),

WordPress小批量定制插件与CRM系统集成开发教程(续)

管理界面与设置页面

创建用户友好的管理界面是插件成功的关键。以下代码实现插件的设置页面和同步日志查看功能。

<?php
/**
 * 插件管理界面
 */

class CRM_Admin_Interface {
    
    public function add_admin_menu() {
        // 主菜单项
        add_menu_page(
            'CRM集成设置',
            'CRM集成',
            'manage_options',
            'custom-crm-integration',
            array($this, 'display_settings_page'),
            'dashicons-admin-generic',
            30
        );
        
        // 子菜单:设置
        add_submenu_page(
            'custom-crm-integration',
            'CRM设置',
            '设置',
            'manage_options',
            'custom-crm-integration',
            array($this, 'display_settings_page')
        );
        
        // 子菜单:同步日志
        add_submenu_page(
            'custom-crm-integration',
            '同步日志',
            '同步日志',
            'manage_options',
            'crm-sync-logs',
            array($this, 'display_sync_logs_page')
        );
        
        // 子菜单:手动同步
        add_submenu_page(
            'custom-crm-integration',
            '手动同步',
            '手动同步',
            'manage_options',
            'crm-manual-sync',
            array($this, 'display_manual_sync_page')
        );
    }
    
    /**
     * 显示设置页面
     */
    public function display_settings_page() {
        // 获取当前设置
        $settings = get_option('crm_integration_settings', array());
        
        ?>
        <div class="wrap">
            <h1>CRM集成设置</h1>
            
            <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                <input type="hidden" name="action" value="save_crm_settings">
                <?php wp_nonce_field('crm_settings_nonce', 'crm_settings_nonce_field'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="crm_api_url">CRM API地址</label>
                        </th>
                        <td>
                            <input type="url" id="crm_api_url" name="crm_api_url" 
                                   value="<?php echo esc_url($settings['api_url'] ?? ''); ?>" 
                                   class="regular-text" required>
                            <p class="description">请输入完整的CRM API基础URL,例如:https://api.yourcrm.com</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="crm_api_key">API密钥</label>
                        </th>
                        <td>
                            <input type="password" id="crm_api_key" name="crm_api_key" 
                                   value="<?php echo esc_attr($settings['api_key'] ?? ''); ?>" 
                                   class="regular-text" required>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="crm_api_secret">API密钥</label>
                        </th>
                        <td>
                            <input type="password" id="crm_api_secret" name="crm_api_secret" 
                                   value="<?php echo esc_attr($settings['api_secret'] ?? ''); ?>" 
                                   class="regular-text" required>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="sync_automatically">自动同步</label>
                        </th>
                        <td>
                            <input type="checkbox" id="sync_automatically" name="sync_automatically" 
                                   value="1" <?php checked(1, $settings['sync_automatically'] ?? 1); ?>>
                            <label for="sync_automatically">启用新订单自动同步到CRM</label>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="sync_customers">同步客户</label>
                        </th>
                        <td>
                            <input type="checkbox" id="sync_customers" name="sync_customers" 
                                   value="1" <?php checked(1, $settings['sync_customers'] ?? 1); ?>>
                            <label for="sync_customers">自动同步新客户到CRM</label>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="product_categories">同步的产品类别</label>
                        </th>
                        <td>
                            <?php
                            $product_categories = get_terms(array(
                                'taxonomy' => 'product_cat',
                                'hide_empty' => false,
                            ));
                            
                            $selected_categories = $settings['product_categories'] ?? array();
                            
                            foreach ($product_categories as $category) {
                                $checked = in_array($category->term_id, $selected_categories) ? 'checked' : '';
                                ?>
                                <p>
                                    <input type="checkbox" id="cat_<?php echo $category->term_id; ?>" 
                                           name="product_categories[]" 
                                           value="<?php echo $category->term_id; ?>" <?php echo $checked; ?>>
                                    <label for="cat_<?php echo $category->term_id; ?>">
                                        <?php echo esc_html($category->name); ?>
                                    </label>
                                </p>
                                <?php
                            }
                            ?>
                            <p class="description">只同步指定类别的产品订单</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="custom_field_mapping">自定义字段映射</label>
                        </th>
                        <td>
                            <textarea id="custom_field_mapping" name="custom_field_mapping" 
                                      rows="5" class="large-text"><?php 
                                echo esc_textarea($settings['custom_field_mapping'] ?? ''); 
                            ?></textarea>
                            <p class="description">
                                每行一个映射,格式:WordPress字段名:CRM字段名<br>
                                例如:billing_phone:phoneNumber
                            </p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button('保存设置'); ?>
            </form>
            
            <div class="card" style="margin-top: 20px;">
                <h2>API连接测试</h2>
                <p>
                    <button id="test-crm-connection" class="button button-secondary">
                        测试CRM连接
                    </button>
                    <span id="test-result" style="margin-left: 10px;"></span>
                </p>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            $('#test-crm-connection').click(function() {
                var button = $(this);
                var result = $('#test-result');
                
                button.prop('disabled', true).text('测试中...');
                result.text('').removeClass('error success');
                
                $.post(ajaxurl, {
                    action: 'test_crm_connection',
                    nonce: '<?php echo wp_create_nonce('test_crm_connection'); ?>',
                    api_url: $('#crm_api_url').val(),
                    api_key: $('#crm_api_key').val(),
                    api_secret: $('#crm_api_secret').val()
                }, function(response) {
                    if (response.success) {
                        result.text('✓ 连接成功').addClass('success');
                    } else {
                        result.text('✗ 连接失败: ' + response.data).addClass('error');
                    }
                    button.prop('disabled', false).text('测试CRM连接');
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * 显示同步日志页面
     */
    public function display_sync_logs_page() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'custom_crm_sync_log';
        
        // 分页参数
        $per_page = 20;
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $offset = ($current_page - 1) * $per_page;
        
        // 获取日志总数
        $total_items = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        
        // 获取日志数据
        $logs = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM $table_name ORDER BY sync_time DESC LIMIT %d OFFSET %d",
                $per_page,
                $offset
            ),
            ARRAY_A
        );
        
        ?>
        <div class="wrap">
            <h1>同步日志</h1>
            
            <div class="tablenav top">
                <div class="tablenav-pages">
                    <?php
                    $total_pages = ceil($total_items / $per_page);
                    echo paginate_links(array(
                        'base' => add_query_arg('paged', '%#%'),
                        'format' => '',
                        'prev_text' => '&laquo;',
                        'next_text' => '&raquo;',
                        'total' => $total_pages,
                        'current' => $current_page
                    ));
                    ?>
                </div>
            </div>
            
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>操作类型</th>
                        <th>实体类型</th>
                        <th>实体ID</th>
                        <th>状态</th>
                        <th>消息</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                        <tr>
                            <td colspan="6" style="text-align: center;">暂无同步日志</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td><?php echo esc_html($log['sync_time']); ?></td>
                                <td><?php echo esc_html($log['operation_type']); ?></td>
                                <td><?php echo esc_html($log['entity_type']); ?></td>
                                <td><?php echo esc_html($log['entity_id']); ?></td>
                                <td>
                                    <?php
                                    $status_class = '';
                                    switch ($log['status']) {
                                        case 'success':
                                            $status_class = 'status-success';
                                            break;
                                        case 'failed':
                                            $status_class = 'status-failed';
                                            break;
                                        case 'skipped':
                                            $status_class = 'status-skipped';
                                            break;
                                    }
                                    ?>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo esc_html($log['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html($log['message']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            
            <style>
            .status-badge {
                padding: 3px 8px;
                border-radius: 3px;
                font-size: 12px;
                font-weight: bold;
            }
            .status-success {
                background-color: #d4edda;
                color: #155724;
            }
            .status-failed {
                background-color: #f8d7da;
                color: #721c24;
            }
            .status-skipped {
                background-color: #fff3cd;
                color: #856404;
            }
            </style>
        </div>
        <?php
    }
    
    /**
     * 显示手动同步页面
     */
    public function display_manual_sync_page() {
        ?>
        <div class="wrap">
            <h1>手动同步</h1>
            
            <div class="card">
                <h2>同步特定订单</h2>
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                    <input type="hidden" name="action" value="manual_order_sync">
                    <?php wp_nonce_field('manual_sync_nonce', 'manual_sync_nonce_field'); ?>
                    
                    <p>
                        <label for="order_id">订单ID:</label>
                        <input type="number" id="order_id" name="order_id" min="1" required>
                    </p>
                    
                    <?php submit_button('同步此订单', 'primary', 'submit_single_order'); ?>
                </form>
            </div>
            
            <div class="card" style="margin-top: 20px;">
                <h2>批量同步</h2>
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                    <input type="hidden" name="action" value="bulk_order_sync">
                    <?php wp_nonce_field('bulk_sync_nonce', 'bulk_sync_nonce_field'); ?>
                    
                    <p>
                        <label for="start_date">开始日期:</label>
                        <input type="date" id="start_date" name="start_date" 
                               value="<?php echo date('Y-m-d', strtotime('-7 days')); ?>">
                        
                        <label for="end_date" style="margin-left: 20px;">结束日期:</label>
                        <input type="date" id="end_date" name="end_date" 
                               value="<?php echo date('Y-m-d'); ?>">
                    </p>
                    
                    <p>
                        <label for="order_status">订单状态:</label>
                        <select id="order_status" name="order_status">
                            <option value="">所有状态</option>
                            <option value="pending">待处理</option>
                            <option value="processing">处理中</option>
                            <option value="completed">已完成</option>
                            <option value="cancelled">已取消</option>
                        </select>
                    </p>
                    
                    <?php submit_button('批量同步订单', 'secondary', 'submit_bulk_sync'); ?>
                </form>
            </div>
            
            <div class="card" style="margin-top: 20px;">
                <h2>同步统计</h2>
                <?php
                global $wpdb;
                $table_name = $wpdb->prefix . 'custom_crm_sync_log';
                
                $stats = $wpdb->get_results("
                    SELECT status, COUNT(*) as count 
                    FROM $table_name 
                    WHERE entity_type = 'order' 
                    GROUP BY status
                ", ARRAY_A);
                
                if ($stats) {
                    echo '<ul>';
                    foreach ($stats as $stat) {
                        echo '<li>' . esc_html($stat['status']) . ': ' . intval($stat['count']) . '</li>';
                    }
                    echo '</ul>';
                }
                ?>
            </div>
        </div>
        <?php
    }
    
    /**
     * 保存设置
     */
    public function save_settings() {
        // 验证权限
        if (!current_user_can('manage_options')) {
            wp_die('权限不足');
        }
        
        // 验证nonce
        if (!isset($_POST['crm_settings_nonce_field']) || 
            !wp_verify_nonce($_POST['crm_settings_nonce_field'], 'crm_settings_nonce')) {
            wp_die('安全验证失败');
        }
        
        // 收集设置数据
        $settings = array(
            'api_url' => esc_url_raw($_POST['crm_api_url']),
            'api_key' => sanitize_text_field($_POST['crm_api_key']),
            'api_secret' => sanitize_text_field($_POST['crm_api_secret']),
            'sync_automatically' => isset($_POST['sync_automatically']) ? 1 : 0,
            'sync_customers' => isset($_POST['sync_customers']) ? 1 : 0,
            'product_categories' => isset($_POST['product_categories']) ? 
                array_map('intval', $_POST['product_categories']) : array(),
            'custom_field_mapping' => sanitize_textarea_field($_POST['custom_field_mapping'])
        );
        
        // 保存设置
        update_option('crm_integration_settings', $settings);
        
        // 重定向回设置页面
        wp_redirect(add_query_arg(
            array('page' => 'custom-crm-integration', 'updated' => 'true'),
            admin_url('admin.php')
        ));
        exit;
    }
}
?>

AJAX处理与API测试

添加AJAX处理功能,用于测试CRM连接和实时状态更新。

<?php
/**
 * AJAX处理程序
 */

class CRM_AJAX_Handler {
    
    public function __construct() {
        // 测试CRM连接
        add_action('wp_ajax_test_crm_connection', array($this, 'test_crm_connection'));
        
        // 获取同步状态
        add_action('wp_ajax_get_sync_status', array($this, 'get_sync_status'));
    }
    
    /**
     * 测试CRM连接
     */
    public function test_crm_connection() {
        // 验证nonce
        if (!check_ajax_referer('test_crm_connection', 'nonce', false)) {
            wp_die('安全验证失败', 403);
        }
        
        // 获取API参数
        $api_url = isset($_POST['api_url']) ? esc_url_raw($_POST['api_url']) : '';
        $api_key = isset($_POST['api_key']) ? sanitize_text_field($_POST['api_key']) : '';
        $api_secret = isset($_POST['api_secret']) ? sanitize_text_field($_POST['api_secret']) : '';
        
        if (empty($api_url) || empty($api_key) || empty($api_secret)) {
            wp_send_json_error('请填写完整的API信息');
        }
        
        // 创建临时CRM处理器
        $crm_handler = new CRM_API_Handler($api_url, $api_key, $api_secret);
        
        // 测试连接
        $response = $crm_handler->send_request('/api/v1/ping', array(), 'GET');
        
        if ($response['success']) {
            wp_send_json_success('CRM连接测试成功');
        } else {
            wp_send_json_error('连接失败: ' . ($response['error'] ?? '未知错误'));
        }
    }
    
    /**
     * 获取同步状态
     */
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5859.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部