文章目录[隐藏]
WordPress小批量定制插件与ERP系统深度集成教程
概述:为什么需要WordPress与ERP系统集成
在当今数字化商业环境中,企业网站与后台管理系统的高效协同至关重要。WordPress作为全球最流行的内容管理系统,承载着企业的在线展示、电商交易和客户互动功能。而ERP(企业资源计划)系统则负责管理企业的核心业务流程,包括库存、订单、财务和客户关系等。
将WordPress与ERP系统深度集成,可以实现:
- 实时同步产品库存和价格信息
- 自动处理订单并更新物流状态
- 统一客户数据管理
- 提高运营效率,减少人工错误
- 提供更一致的用户体验
本教程将指导您开发一个小批量定制插件,实现WordPress与ERP系统的深度集成。
环境准备与基础配置
1. 开发环境要求
<?php
/**
* WordPress插件基础配置
* 文件:erp-integration-config.php
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('ERP_INTEGRATION_VERSION', '1.0.0');
define('ERP_INTEGRATION_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ERP_INTEGRATION_PLUGIN_URL', plugin_dir_url(__FILE__));
// ERP系统API配置
$erp_config = array(
'api_url' => 'https://your-erp-system.com/api/v1',
'api_key' => 'your_api_key_here',
'api_secret' => 'your_api_secret_here',
'sync_interval' => 300, // 同步间隔时间(秒)
'debug_mode' => true // 调试模式
);
// 存储配置到WordPress选项
add_option('erp_integration_config', $erp_config);
?>
2. 插件基础结构
创建插件主文件 erp-integration.php:
<?php
/**
* Plugin Name: ERP系统深度集成
* Plugin URI: https://yourwebsite.com/
* Description: WordPress与ERP系统深度集成插件
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: erp-integration
*/
// 安全检查
if (!defined('ABSPATH')) {
exit;
}
// 加载配置文件
require_once plugin_dir_path(__FILE__) . 'erp-integration-config.php';
// 初始化插件
class ERP_Integration_Plugin {
private $erp_api;
public function __construct() {
// 初始化ERP API连接
$this->erp_api = new ERP_API_Handler();
// 注册WordPress钩子
$this->register_hooks();
// 初始化管理界面
if (is_admin()) {
new ERP_Admin_Interface();
}
}
private function register_hooks() {
// 产品同步钩子
add_action('erp_sync_products', array($this, 'sync_products'));
// 订单同步钩子
add_action('save_post_shop_order', array($this, 'sync_order_to_erp'), 10, 3);
// 库存更新钩子
add_action('woocommerce_product_set_stock', array($this, 'update_erp_stock'));
// 定期同步任务
if (!wp_next_scheduled('erp_daily_sync')) {
wp_schedule_event(time(), 'hourly', 'erp_daily_sync');
}
add_action('erp_daily_sync', array($this, 'daily_sync_tasks'));
}
// 其他方法将在后续部分实现
}
?>
ERP API通信模块开发
1. API处理器类
<?php
/**
* ERP API处理器
* 文件:erp-api-handler.php
*/
class ERP_API_Handler {
private $api_url;
private $api_key;
private $api_secret;
public function __construct() {
$config = get_option('erp_integration_config');
$this->api_url = $config['api_url'];
$this->api_key = $config['api_key'];
$this->api_secret = $config['api_secret'];
}
/**
* 发送API请求到ERP系统
* @param string $endpoint API端点
* @param array $data 请求数据
* @param string $method 请求方法
* @return array 响应数据
*/
public function send_request($endpoint, $data = array(), $method = 'GET') {
$url = $this->api_url . '/' . $endpoint;
// 准备请求头
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->generate_auth_token(),
'X-API-Key' => $this->api_key
);
// 准备请求参数
$args = array(
'method' => $method,
'headers' => $headers,
'timeout' => 30,
'sslverify' => false // 根据实际情况调整
);
// 添加请求体(如果是POST或PUT)
if (in_array($method, array('POST', 'PUT', 'PATCH')) && !empty($data)) {
$args['body'] = json_encode($data);
}
// 发送请求
$response = wp_remote_request($url, $args);
// 处理响应
if (is_wp_error($response)) {
$this->log_error('API请求失败: ' . $response->get_error_message());
return array('success' => false, 'error' => $response->get_error_message());
}
$body = wp_remote_retrieve_body($response);
$decoded = json_decode($body, true);
return array(
'success' => true,
'data' => $decoded,
'status_code' => wp_remote_retrieve_response_code($response)
);
}
/**
* 生成认证令牌
* @return string 认证令牌
*/
private function generate_auth_token() {
$timestamp = time();
$signature = hash_hmac('sha256', $this->api_key . $timestamp, $this->api_secret);
return base64_encode($this->api_key . ':' . $timestamp . ':' . $signature);
}
/**
* 记录错误日志
* @param string $message 错误信息
*/
private function log_error($message) {
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log('[ERP集成错误] ' . $message);
}
// 同时存储到自定义日志文件
$log_file = ERP_INTEGRATION_PLUGIN_DIR . 'logs/error.log';
$log_entry = date('Y-m-d H:i:s') . ' - ' . $message . PHP_EOL;
file_put_contents($log_file, $log_entry, FILE_APPEND);
}
}
?>
产品数据同步功能
1. 从ERP同步产品到WordPress
<?php
/**
* 产品同步功能
* 文件:product-sync.php
*/
class Product_Sync_Handler {
private $erp_api;
public function __construct($erp_api) {
$this->erp_api = $erp_api;
}
/**
* 同步所有产品
*/
public function sync_all_products() {
// 从ERP获取产品列表
$response = $this->erp_api->send_request('products', array(), 'GET');
if (!$response['success']) {
return false;
}
$erp_products = $response['data']['products'];
$synced_count = 0;
foreach ($erp_products as $erp_product) {
if ($this->sync_single_product($erp_product)) {
$synced_count++;
}
}
return $synced_count;
}
/**
* 同步单个产品
* @param array $erp_product ERP产品数据
* @return bool 同步是否成功
*/
private function sync_single_product($erp_product) {
// 检查产品是否已存在
$existing_product_id = $this->find_product_by_sku($erp_product['sku']);
// 准备产品数据
$product_data = array(
'post_title' => $erp_product['name'],
'post_content' => $erp_product['description'],
'post_status' => 'publish',
'post_type' => 'product'
);
// 创建或更新产品
if ($existing_product_id) {
$product_data['ID'] = $existing_product_id;
$product_id = wp_update_post($product_data);
} else {
$product_id = wp_insert_post($product_data);
}
if (is_wp_error($product_id)) {
return false;
}
// 更新产品元数据
$this->update_product_metadata($product_id, $erp_product);
return true;
}
/**
* 通过SKU查找产品
* @param string $sku 产品SKU
* @return int|false 产品ID或false
*/
private function find_product_by_sku($sku) {
global $wpdb;
$query = $wpdb->prepare(
"SELECT post_id FROM {$wpdb->postmeta}
WHERE meta_key = '_sku' AND meta_value = %s
LIMIT 1",
$sku
);
$product_id = $wpdb->get_var($query);
return $product_id ? (int)$product_id : false;
}
/**
* 更新产品元数据
* @param int $product_id WordPress产品ID
* @param array $erp_product ERP产品数据
*/
private function update_product_metadata($product_id, $erp_product) {
// 基础信息
update_post_meta($product_id, '_sku', $erp_product['sku']);
update_post_meta($product_id, '_price', $erp_product['price']);
update_post_meta($product_id, '_regular_price', $erp_product['price']);
update_post_meta($product_id, '_stock', $erp_product['stock_quantity']);
update_post_meta($product_id, '_manage_stock', 'yes');
update_post_meta($product_id, '_stock_status',
$erp_product['stock_quantity'] > 0 ? 'instock' : 'outofstock');
// 分类信息
if (!empty($erp_product['categories'])) {
$this->sync_product_categories($product_id, $erp_product['categories']);
}
// 产品图片
if (!empty($erp_product['images'])) {
$this->sync_product_images($product_id, $erp_product['images']);
}
// 自定义字段
if (!empty($erp_product['custom_fields'])) {
foreach ($erp_product['custom_fields'] as $key => $value) {
update_post_meta($product_id, $key, $value);
}
}
}
}
?>
订单同步与处理
1. WordPress订单同步到ERP
<?php
/**
* 订单同步功能
* 文件:order-sync.php
*/
class Order_Sync_Handler {
private $erp_api;
public function __construct($erp_api) {
$this->erp_api = $erp_api;
}
/**
* 同步订单到ERP系统
* @param int $order_id WordPress订单ID
* @param WP_Post $post 订单对象
* @param bool $update 是否更新
*/
public function sync_order_to_erp($order_id, $post, $update) {
// 只同步新订单或状态改变的订单
if (!$update || $post->post_status == 'auto-draft') {
return;
}
// 获取订单对象
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// 准备ERP订单数据
$erp_order_data = $this->prepare_erp_order_data($order);
// 发送到ERP系统
$response = $this->erp_api->send_request('orders', $erp_order_data, 'POST');
if ($response['success']) {
// 记录同步状态
update_post_meta($order_id, '_erp_sync_status', 'synced');
update_post_meta($order_id, '_erp_order_id', $response['data']['order_id']);
update_post_meta($order_id, '_erp_sync_time', current_time('mysql'));
} else {
update_post_meta($order_id, '_erp_sync_status', 'failed');
update_post_meta($order_id, '_erp_sync_error', $response['error']);
}
}
/**
* 准备ERP订单数据
* @param WC_Order $order WooCommerce订单对象
* @return array ERP系统所需的订单数据
*/
private function prepare_erp_order_data($order) {
// 基础订单信息
$order_data = array(
'order_number' => $order->get_order_number(),
'order_date' => $order->get_date_created()->date('Y-m-d H:i:s'),
'status' => $order->get_status(),
'currency' => $order->get_currency(),
'total' => $order->get_total(),
'customer_note' => $order->get_customer_note()
);
// 客户信息
$order_data['customer'] = array(
'id' => $order->get_customer_id(),
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone()
);
// 账单地址
$order_data['billing_address'] = array(
'address_1' => $order->get_billing_address_1(),
'address_2' => $order->get_billing_address_2(),
'city' => $order->get_billing_city(),
'state' => $order->get_billing_state(),
'postcode' => $order->get_billing_postcode(),
'country' => $order->get_billing_country()
);
// 配送地址
$order_data['shipping_address'] = array(
'address_1' => $order->get_shipping_address_1(),
'address_2' => $order->get_shipping_address_2(),
'city' => $order->get_shipping_city(),
'state' => $order->get_shipping_state(),
'postcode' => $order->get_shipping_postcode(),
'country' => $order->get_shipping_country()
);
// 订单商品
$items = array();
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$items[] = array(
'product_id' => $item->get_product_id(),
'sku' => $product ? $product->get_sku() : '',
'name' => $item->get_name(),
'quantity' => $item->get_quantity(),
'price' => $item->get_total(),
'variation_id' => $item->get_variation_id()
);
}
$order_data['items'] = $items;
// 配送信息
$order_data['shipping'] = array(
'method' => $order->get_shipping_method(),
'cost' => $order->get_shipping_total()
);
return $order_data;
}
/**
* 从ERP同步订单状态更新
*/
public function sync_order_status_from_erp() {
// 获取需要同步的订单
$response = $this->erp_api->send_request('orders/pending-sync', array(), 'GET');
if (!$response['success']) {
return false;
}
$updated_count = 0;
foreach ($response['data']['orders'] as $erp_order) {
// 通过ERP订单ID查找WordPress订单
$order_id = $this->find_order_by_erp_id($erp_order['erp_order_id']);
if ($order_id) {
$order = wc_get_order($order_id);
// 更新订单状态
if ($order && $order->get_status() != $erp_order['status']) {
$order->update_status($erp_order['status']);
$updated_count++;
}
// 更新物流信息
if (!empty($erp_order['tracking_info'])) {
update_post_meta($order_id, '_tracking_number', $erp_order['tracking_info']['number']);
update_post_meta($order_id, '_tracking_provider', $erp_order['tracking_info']['provider']);
update_post_meta($order_id, '_tracking_link', $erp_order['tracking_info']['link']);
}
}
}
return $updated_count;
}
}
?>
管理界面与配置
1. 插件管理界面
<?php
/**
* 管理界面
* 文件:admin-interface.php
*/
class ERP_Admin_Interface {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
'ERP集成设置',
'ERP集成',
'manage_options',
erp-integration',
array($this, 'display_settings_page'),
'dashicons-admin-generic',
30
);
add_submenu_page(
'erp-integration',
'同步设置',
'同步设置',
'manage_options',
'erp-sync-settings',
array($this, 'display_sync_settings_page')
);
add_submenu_page(
'erp-integration',
'日志查看',
'日志查看',
'manage_options',
'erp-logs',
array($this, 'display_logs_page')
);
}
/**
* 显示设置页面
*/
public function display_settings_page() {
?>
<div class="wrap">
<h1>ERP系统集成设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('erp_integration_settings');
do_settings_sections('erp-integration');
submit_button();
?>
</form>
<div class="erp-status-card">
<h3>系统状态</h3>
<?php $this->display_system_status(); ?>
</div>
</div>
<?php
}
/**
* 注册设置
*/
public function register_settings() {
register_setting('erp_integration_settings', 'erp_integration_config');
// API设置部分
add_settings_section(
'erp_api_section',
'API连接设置',
array($this, 'api_section_callback'),
'erp-integration'
);
add_settings_field(
'api_url',
'API地址',
array($this, 'api_url_callback'),
'erp-integration',
'erp_api_section'
);
add_settings_field(
'api_key',
'API密钥',
array($this, 'api_key_callback'),
'erp-integration',
'erp_api_section'
);
// 同步设置部分
add_settings_section(
'erp_sync_section',
'同步设置',
array($this, 'sync_section_callback'),
'erp-integration'
);
add_settings_field(
'sync_interval',
'同步间隔(秒)',
array($this, 'sync_interval_callback'),
'erp-integration',
'erp_sync_section'
);
add_settings_field(
'auto_sync',
'自动同步',
array($this, 'auto_sync_callback'),
'erp-integration',
'erp_sync_section'
);
}
/**
* 显示系统状态
*/
private function display_system_status() {
$config = get_option('erp_integration_config');
$last_sync = get_option('erp_last_sync_time', '从未同步');
echo '<table class="widefat">';
echo '<tr><td>API连接状态:</td><td>' . $this->check_api_connection() . '</td></tr>';
echo '<tr><td>最后同步时间:</td><td>' . $last_sync . '</td></tr>';
echo '<tr><td>同步产品数量:</td><td>' . $this->get_synced_product_count() . '</td></tr>';
echo '<tr><td>同步订单数量:</td><td>' . $this->get_synced_order_count() . '</td></tr>';
echo '</table>';
// 手动同步按钮
echo '<div class="sync-buttons" style="margin-top: 20px;">';
echo '<button type="button" class="button button-primary" onclick="syncProducts()">同步产品</button>';
echo '<button type="button" class="button button-secondary" onclick="syncOrders()">同步订单</button>';
echo '<button type="button" class="button" onclick="syncAll()">同步全部</button>';
echo '</div>';
// JavaScript函数
?>
<script>
function syncProducts() {
jQuery.post(ajaxurl, {
action: 'erp_sync_products',
nonce: '<?php echo wp_create_nonce("erp_sync_nonce"); ?>'
}, function(response) {
alert(response.data.message);
location.reload();
});
}
function syncOrders() {
jQuery.post(ajaxurl, {
action: 'erp_sync_orders',
nonce: '<?php echo wp_create_nonce("erp_sync_nonce"); ?>'
}, function(response) {
alert(response.data.message);
location.reload();
});
}
function syncAll() {
jQuery.post(ajaxurl, {
action: 'erp_sync_all',
nonce: '<?php echo wp_create_nonce("erp_sync_nonce"); ?>'
}, function(response) {
alert(response.data.message);
location.reload();
});
}
</script>
<?php
}
/**
* 检查API连接
*/
private function check_api_connection() {
$erp_api = new ERP_API_Handler();
$response = $erp_api->send_request('health', array(), 'GET');
if ($response['success']) {
return '<span style="color: green;">✓ 连接正常</span>';
} else {
return '<span style="color: red;">✗ 连接失败: ' . $response['error'] . '</span>';
}
}
}
?>
## 高级功能:实时库存同步
### 1. Webhook处理器
<?php
/**
- Webhook处理器
- 文件:webhook-handler.php
*/
class ERP_Webhook_Handler {
public function __construct() {
add_action('rest_api_init', array($this, 'register_webhook_routes'));
}
/**
* 注册Webhook路由
*/
public function register_webhook_routes() {
register_rest_route('erp-integration/v1', '/webhook/stock-update', array(
'methods' => 'POST',
'callback' => array($this, 'handle_stock_update'),
'permission_callback' => array($this, 'verify_webhook_signature')
));
register_rest_route('erp-integration/v1', '/webhook/order-update', array(
'methods' => 'POST',
'callback' => array($this, 'handle_order_update'),
'permission_callback' => array($this, 'verify_webhook_signature')
));
}
/**
* 处理库存更新Webhook
*/
public function handle_stock_update(WP_REST_Request $request) {
$data = $request->get_json_params();
if (empty($data['sku']) || !isset($data['stock_quantity'])) {
return new WP_REST_Response(array(
'success' => false,
'message' => '缺少必要参数'
), 400);
}
// 根据SKU查找产品
$product_id = wc_get_product_id_by_sku($data['sku']);
if (!$product_id) {
return new WP_REST_Response(array(
'success' => false,
'message' => '未找到对应产品'
), 404);
}
// 更新库存
$product = wc_get_product($product_id);
$product->set_stock_quantity($data['stock_quantity']);
$product->save();
// 记录日志
$this->log_webhook('stock_update', $data);
return new WP_REST_Response(array(
'success' => true,
'message' => '库存更新成功',
'product_id' => $product_id
), 200);
}
/**
* 处理订单更新Webhook
*/
public function handle_order_update(WP_REST_Request $request) {
$data = $request->get_json_params();
if (empty($data['order_number']) || empty($data['status'])) {
return new WP_REST_Response(array(
'success' => false,
'message' => '缺少必要参数'
), 400);
}
// 根据订单号查找订单
$order_id = $this->find_order_by_number($data['order_number']);
if (!$order_id) {
return new WP_REST_Response(array(
'success' => false,
'message' => '未找到对应订单'
), 404);
}
// 更新订单状态
$order = wc_get_order($order_id);
$order->update_status($data['status']);
// 更新物流信息
if (!empty($data['tracking_info'])) {
update_post_meta($order_id, '_tracking_number', $data['tracking_info']['number']);
update_post_meta($order_id, '_tracking_provider', $data['tracking_info']['provider']);
update_post_meta($order_id, '_tracking_link', $data['tracking_info']['link']);
// 发送物流通知邮件
$this->send_tracking_email($order, $data['tracking_info']);
}
// 记录日志
$this->log_webhook('order_update', $data);
return new WP_REST_Response(array(
'success' => true,
'message' => '订单更新成功',
'order_id' => $order_id
), 200);
}
/**
* 验证Webhook签名
*/
public function verify_webhook_signature(WP_REST_Request $request) {
$config = get_option('erp_integration_config');
$signature = $request->get_header('X-ERP-Signature');
if (empty($signature)) {
return false;
}
$payload = $request->get_body();
$expected_signature = hash_hmac('sha256', $payload, $config['webhook_secret']);
return hash_equals($expected_signature, $signature);
}
/**
* 记录Webhook日志
*/
private function log_webhook($type, $data) {
$log_entry = array(
'timestamp' => current_time('mysql'),
'type' => $type,
'data' => $data,
'ip' => $_SERVER['REMOTE_ADDR']
);
$log_file = ERP_INTEGRATION_PLUGIN_DIR . 'logs/webhooks.log';
file_put_contents($log_file, json_encode($log_entry) . PHP_EOL, FILE_APPEND);
}
}
?>
## 错误处理与日志系统
### 1. 增强的错误处理器
<?php
/**
- 错误处理与日志系统
- 文件:error-handler.php
*/
class ERP_Error_Handler {
private static $instance = null;
private $log_dir;
private function __construct() {
$this->log_dir = ERP_INTEGRATION_PLUGIN_DIR . 'logs/';
$this->ensure_log_directory();
// 注册错误处理函数
set_error_handler(array($this, 'handle_error'));
register_shutdown_function(array($this, 'handle_shutdown'));
}
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 确保日志目录存在
*/
private function ensure_log_directory() {
if (!file_exists($this->log_dir)) {
wp_mkdir_p($this->log_dir);
// 创建.htaccess保护日志文件
$htaccess_content = "Order deny,allownDeny from all";
file_put_contents($this->log_dir . '.htaccess', $htaccess_content);
}
}
/**
* 处理PHP错误
*/
public function handle_error($errno, $errstr, $errfile, $errline) {
// 只处理特定级别的错误
if (!(error_reporting() & $errno)) {
return false;
}
$error_types = array(
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSE',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE_ERROR',
E_CORE_WARNING => 'CORE_WARNING',
E_COMPILE_ERROR => 'COMPILE_ERROR',
E_COMPILE_WARNING => 'COMPILE_WARNING',
E_USER_ERROR => 'USER_ERROR',
E_USER_WARNING => 'USER_WARNING',
E_USER_NOTICE => 'USER_NOTICE',
E_STRICT => 'STRICT',
E_RECOVERABLE_ERROR => 'RECOVERABLE_ERROR',
E_DEPRECATED => 'DEPRECATED',
E_USER_DEPRECATED => 'USER_DEPRECATED'
);
$error_type = isset($error_types[$errno]) ? $error_types[$errno] : 'UNKNOWN';
$log_message = sprintf(
"[%s] %s: %s in %s on line %d",
date('Y-m-d H:i:s'),
$error_type,
$errstr,
$errfile,
$errline
);
$this->write_log('errors.log', $log_message);
// 根据错误级别决定是否继续执行
if (in_array($errno, array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR))) {
$this->send_error_notification($log_message);
}
return true;
}
/**
* 处理脚本终止
*/
public function handle_shutdown() {
$error = error_get_last();
if ($error && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))) {
$log_message = sprintf(
"[%s] SHUTDOWN: %s in %s on line %d",
date('Y-m-d H:i:s'),
$error['message'],
$error['file'],
$error['line']
);
$this->write_log('shutdown.log', $log_message);
$this->send_error_notification($log_message);
}
}
/**
* 写入日志文件
*/
public function write_log($filename, $message) {
$log_file = $this->log_dir . $filename;
file_put_contents($log_file, $message . PHP_EOL, FILE_APPEND);
}
/**
* 发送错误通知
*/
private function send_error_notification($message) {
$admin_email = get_option('admin_email');
$site_name = get_bloginfo('name');
$subject = sprintf('[%s] ERP集成插件发生严重错误', $site_name);
$body = sprintf(
"网站: %sn时间: %sn错误信息:n%snn请立即检查。",
$site_name,
date('Y-m-d H:i:s'),
$message
);
wp_mail($admin_email, $subject, $body);
}
/**
* 记录API请求日志
*/
public function log_api_request($endpoint, $method, $request_data, $response, $status_code) {
$log_entry = array(
'timestamp' => current_time('mysql'),
'endpoint' => $endpoint,
'method' => $method,
'request' => $request_data,
'response' => $response,
'status_code' => $status_code,
'duration' => microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']
);
$this->write_log('api_requests.log', json_encode($log_entry));
}
}
?>
## 插件优化与性能考虑
### 1. 缓存机制实现
<?php
/**
- 缓存机制
- 文件:cache-manager.php
*/
class ERP_Cache_Manager {
private $cache_group = 'erp_integration';
private $cache_expiration = 3600; // 1小时
public function __construct() {
// 初始化缓存表
$this->init_cache_table();
}
/**
* 初始化缓存表
*/
private function init_cache_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'erp_cache';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
cache_key varchar(255) NOT NULL,
cache_value longtext NOT NULL,
expiration datetime NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY cache_key (cache_key),
KEY expiration (expiration)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
/**
* 设置缓存
*/
public function set($key, $value, $expiration = null) {
global $wpdb;
if ($expiration === null) {
$expiration = $this->cache_expiration;
}
$expiration_time = date('Y-m-d H:i:s', time() + $expiration);
$serialized_value = maybe_serialize($value);
$table_name = $wpdb->prefix . 'erp_cache';
$wpdb->replace(
$table_name,
array(
'cache_key' => $key,
'cache_value' => $serialized_value,
'expiration' => $expiration_time
),
array('%s', '%s', '%s')
);
// 同时设置WordPress对象缓存
wp_cache_set($key, $value, $this->cache_group, $expiration);
}
/**
* 获取缓存
*/
public function get($key) {
// 先尝试从对象缓存获取
$cached = wp_cache_get($key, $this->cache
