文章目录[隐藏]
WordPress柔性供应链API接口开发的详细教程
引言:为什么需要柔性供应链API
在当今快速变化的电商环境中,供应链的灵活性已成为企业成功的关键因素。WordPress作为全球最流行的内容管理系统,结合WooCommerce等电商插件,为中小型企业提供了强大的电商解决方案。然而,传统的供应链管理方式往往缺乏灵活性,无法适应市场需求的变化。
柔性供应链API接口的开发,能够帮助WordPress网站实现:
- 实时库存同步和更新
- 自动化订单处理
- 多供应商集成管理
- 动态定价和促销策略
- 物流跟踪和状态更新
本教程将详细介绍如何在WordPress中开发一个完整的柔性供应链API接口。
环境准备和基础配置
1. 开发环境搭建
首先,确保你的WordPress安装环境满足以下要求:
- WordPress 5.0或更高版本
- PHP 7.4或更高版本
- 启用REST API功能
- 安装并激活必要的插件(如WooCommerce)
2. 创建自定义插件
在wp-content/plugins目录下创建新文件夹flexible-supply-chain,并创建主插件文件:
<?php
/**
* Plugin Name: Flexible Supply Chain API
* Plugin URI: https://yourwebsite.com/
* Description: 柔性供应链API接口插件
* Version: 1.0.0
* Author: Your Name
* License: GPL v2 or later
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FSC_VERSION', '1.0.0');
define('FSC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FSC_PLUGIN_URL', plugin_dir_url(__FILE__));
// 初始化插件
add_action('plugins_loaded', 'fsc_init');
function fsc_init() {
// 检查WooCommerce是否激活
if (!class_exists('WooCommerce')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>柔性供应链API需要WooCommerce插件支持!</p></div>';
});
return;
}
// 加载必要文件
require_once FSC_PLUGIN_DIR . 'includes/class-api-manager.php';
require_once FSC_PLUGIN_DIR . 'includes/class-inventory-manager.php';
require_once FSC_PLUGIN_DIR . 'includes/class-order-manager.php';
// 初始化管理器
new FSC_API_Manager();
new FSC_Inventory_Manager();
new FSC_Order_Manager();
}
核心API接口开发
1. REST API路由注册
创建includes/class-api-manager.php文件:
<?php
/**
* API管理器类
* 负责注册和管理所有供应链API端点
*/
class FSC_API_Manager {
public function __construct() {
add_action('rest_api_init', array($this, 'register_routes'));
}
/**
* 注册所有API路由
*/
public function register_routes() {
// 库存管理端点
register_rest_route('fsc/v1', '/inventory/(?P<id>d+)', array(
'methods' => 'GET',
'callback' => array($this, 'get_inventory'),
'permission_callback' => array($this, 'check_api_permission'),
'args' => array(
'id' => array(
'validate_callback' => function($param) {
return is_numeric($param);
}
)
)
));
// 批量更新库存端点
register_rest_route('fsc/v1', '/inventory/batch-update', array(
'methods' => 'POST',
'callback' => array($this, 'batch_update_inventory'),
'permission_callback' => array($this, 'check_api_permission')
));
// 订单同步端点
register_rest_route('fsc/v1', '/orders/sync', array(
'methods' => 'POST',
'callback' => array($this, 'sync_orders'),
'permission_callback' => array($this, 'check_api_permission')
));
// 供应商信息端点
register_rest_route('fsc/v1', '/suppliers', array(
'methods' => 'GET',
'callback' => array($this, 'get_suppliers'),
'permission_callback' => array($this, 'check_api_permission')
));
}
/**
* API权限检查
*/
public function check_api_permission($request) {
// 获取API密钥
$api_key = $request->get_header('X-API-Key');
// 验证API密钥(实际应用中应从数据库或配置中获取)
$valid_keys = get_option('fsc_api_keys', array());
if (in_array($api_key, $valid_keys)) {
return true;
}
return new WP_Error(
'rest_forbidden',
'无效的API密钥',
array('status' => 403)
);
}
/**
* 获取库存信息
*/
public function get_inventory($request) {
$product_id = $request->get_param('id');
// 获取产品库存信息
$product = wc_get_product($product_id);
if (!$product) {
return new WP_Error(
'product_not_found',
'产品不存在',
array('status' => 404)
);
}
// 构建响应数据
$response = array(
'product_id' => $product_id,
'sku' => $product->get_sku(),
'name' => $product->get_name(),
'stock_quantity' => $product->get_stock_quantity(),
'stock_status' => $product->get_stock_status(),
'manage_stock' => $product->get_manage_stock(),
'backorders' => $product->get_backorders(),
'supplier_info' => get_post_meta($product_id, '_supplier_info', true),
'last_updated' => current_time('mysql')
);
return rest_ensure_response($response);
}
/**
* 批量更新库存
*/
public function batch_update_inventory($request) {
$inventory_data = $request->get_json_params();
$results = array();
if (empty($inventory_data) || !is_array($inventory_data)) {
return new WP_Error(
'invalid_data',
'无效的库存数据',
array('status' => 400)
);
}
foreach ($inventory_data as $item) {
$result = $this->update_single_inventory($item);
$results[] = $result;
}
return rest_ensure_response(array(
'message' => '批量更新完成',
'updated_count' => count($results),
'results' => $results
));
}
/**
* 更新单个产品库存
*/
private function update_single_inventory($item) {
// 验证必要字段
if (empty($item['product_id']) || !isset($item['quantity'])) {
return array(
'success' => false,
'message' => '缺少必要字段'
);
}
$product_id = intval($item['product_id']);
$quantity = intval($item['quantity']);
// 更新库存
$product = wc_get_product($product_id);
if (!$product) {
return array(
'success' => false,
'message' => '产品不存在'
);
}
// 更新库存数量
$product->set_stock_quantity($quantity);
// 如果有供应商信息,更新它
if (isset($item['supplier_info'])) {
update_post_meta($product_id, '_supplier_info', $item['supplier_info']);
}
// 保存产品
$product->save();
// 记录库存变更日志
$this->log_inventory_change($product_id, $quantity, $item);
return array(
'success' => true,
'product_id' => $product_id,
'new_quantity' => $quantity,
'message' => '库存更新成功'
);
}
/**
* 记录库存变更
*/
private function log_inventory_change($product_id, $quantity, $data) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'fsc_inventory_logs',
array(
'product_id' => $product_id,
'quantity' => $quantity,
'change_data' => maybe_serialize($data),
'changed_by' => 'api_sync',
'changed_at' => current_time('mysql')
)
);
}
}
2. 库存管理模块
创建includes/class-inventory-manager.php文件:
<?php
/**
* 库存管理器类
* 处理库存相关的业务逻辑
*/
class FSC_Inventory_Manager {
public function __construct() {
// 初始化数据库表
register_activation_hook(__FILE__, array($this, 'create_tables'));
// 添加库存预警钩子
add_action('woocommerce_low_stock', array($this, 'handle_low_stock'));
add_action('woocommerce_no_stock', array($this, 'handle_no_stock'));
}
/**
* 创建数据库表
*/
public function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'fsc_inventory_logs';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
quantity int(11) NOT NULL,
change_data longtext,
changed_by varchar(100),
changed_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id),
KEY changed_at (changed_at)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
/**
* 处理低库存预警
*/
public function handle_low_stock($product) {
$product_id = $product->get_id();
$stock_quantity = $product->get_stock_quantity();
// 获取供应商信息
$supplier_info = get_post_meta($product_id, '_supplier_info', true);
// 发送预警通知
$this->send_stock_alert($product_id, 'low', $stock_quantity, $supplier_info);
// 自动向供应商下单(如果配置了自动补货)
$this->auto_reorder($product_id, $supplier_info);
}
/**
* 处理无库存情况
*/
public function handle_no_stock($product) {
$product_id = $product->get_id();
// 更新产品状态
update_post_meta($product_id, '_stock_status', 'outofstock');
// 发送缺货通知
$this->send_stock_alert($product_id, 'out', 0, null);
}
/**
* 发送库存预警
*/
private function send_stock_alert($product_id, $type, $quantity, $supplier_info) {
$product = wc_get_product($product_id);
$product_name = $product->get_name();
$alert_types = array(
'low' => '低库存预警',
'out' => '缺货预警'
);
$subject = sprintf('[库存预警] %s - %s',
$alert_types[$type],
$product_name
);
$message = sprintf(
"产品名称: %sn产品ID: %dn当前库存: %dn预警类型: %sn时间: %s",
$product_name,
$product_id,
$quantity,
$alert_types[$type],
current_time('mysql')
);
if ($supplier_info && isset($supplier_info['email'])) {
$message .= sprintf("n供应商: %sn供应商邮箱: %s",
$supplier_info['name'],
$supplier_info['email']
);
}
// 发送邮件通知管理员
wp_mail(
get_option('admin_email'),
$subject,
$message
);
}
/**
* 自动补货逻辑
*/
private function auto_reorder($product_id, $supplier_info) {
// 检查是否启用自动补货
$auto_reorder = get_option('fsc_auto_reorder', 'no');
if ($auto_reorder !== 'yes' || empty($supplier_info)) {
return;
}
// 计算需要补货的数量
$product = wc_get_product($product_id);
$current_stock = $product->get_stock_quantity();
$reorder_level = get_post_meta($product_id, '_reorder_level', true) ?: 10;
$reorder_quantity = get_post_meta($product_id, '_reorder_quantity', true) ?: 50;
if ($current_stock <= $reorder_level) {
// 创建采购订单
$this->create_purchase_order($product_id, $reorder_quantity, $supplier_info);
}
}
}
订单同步和供应商管理
1. 订单管理器
创建includes/class-order-manager.php文件:
<?php
/**
* 订单管理器类
* 处理订单同步和供应商分配
*/
class FSC_Order_Manager {
public function __construct() {
// 订单状态变更钩子
add_action('woocommerce_order_status_changed', array($this, 'handle_order_status_change'), 10, 3);
// 添加供应商分配功能
add_action('add_meta_boxes', array($this, 'add_supplier_meta_box'));
add_action('save_post_shop_order', array($this, 'save_supplier_assignment'));
}
/**
* 同步订单到外部系统
*/
public function sync_orders($request) {
$order_data = $request->get_json_params();
if (empty($order_data)) {
return new WP_Error(
'no_data',
'没有订单数据',
array('status' => 400)
);
}
$results = array();
foreach ($order_data as $order_item) {
$result = $this->process_external_order($order_item);
$results[] = $result;
}
return rest_ensure_response(array(
'message' => '订单同步完成',
'synced_count' => count($results),
'results' => $results
));
}
/**
* 处理外部系统订单
*/
private function process_external_order($order_data) {
// 验证订单数据
$validation = $this->validate_order_data($order_data);
if (!$validation['valid']) {
return array(
'success' => false,
'message' => $validation['message'],
'order_id' => $order_data['order_id'] ?? 'unknown'
);
}
// 创建或更新订单
try {
$order = $this->create_update_order($order_data);
return array(
'success' => true,
'wordpress_order_id' => $order->get_id(),
'external_order_id' => $order_data['order_id'],
'message' => '订单处理成功'
);
} catch (Exception $e) {
return array(
'success' => false,
'message' => '订单创建失败: ' . $e->getMessage(),
'order_id' => $order_data['order_id']
);
}
}
/**
* 验证订单数据
*/
private function validate_order_data($data) {
$required_fields = array('order_id', 'customer_email', 'items');
foreach ($required_fields as $field) {
if (empty($data[$field])) {
return array(
'valid' => false,
'message' => "缺少必要字段: {$field}"
);
}
}
// 验证订单项
if (!is_array($data['items']) || empty($data['items'])) {
return array(
'valid' => false,
'message' => '订单项不能为空'
);
}
return array('valid' => true, 'message' => '');
}
/**
* 添加供应商分配元框
*/
public function add_supplier_meta_box() {
add_meta_box(
'fsc_supplier_assignment',
'供应商分配',
array($this, 'render_supplier_meta_box'),
'shop_order',
'side',
'high'
);
}
/**
* 渲染供应商分配界面
*/
public function render_supplier_meta_box($post) {
$order = wc_get_order($post->ID);
$assigned_supplier = $order->get_meta('_assigned_supplier', true);
// 获取所有供应商
$suppliers = $this->get_available_suppliers();
wp_nonce_field('fsc_supplier_assignment', 'fsc_supplier_nonce');
?>
<div class="supplier-assignment">
<label for="assigned_supplier">选择供应商:</label>
<select name="assigned_supplier" id="assigned_supplier" style="width:100%; margin-top:5px;">
<option value="">-- 未分配 --</option>
<?php foreach ($suppliers as $supplier_id => $supplier_name): ?>
<option value="<?php echo esc_attr($supplier_id); ?>"
2. 供应商管理API
继续在class-order-manager.php中添加供应商管理功能:
<?php selected($assigned_supplier, $supplier_id); ?>>
<?php echo esc_html($supplier_name); ?>
</option>
<?php endforeach; ?>
</select>
<?php if ($assigned_supplier): ?>
<div style="margin-top:10px; padding:10px; background:#f5f5f5;">
<strong>供应商信息:</strong><br>
<?php
$supplier_info = $this->get_supplier_details($assigned_supplier);
if ($supplier_info) {
echo '联系人:' . esc_html($supplier_info['contact']) . '<br>';
echo '电话:' . esc_html($supplier_info['phone']) . '<br>';
echo '邮箱:' . esc_html($supplier_info['email']);
}
?>
</div>
<?php endif; ?>
</div>
<?php
}
/**
* 保存供应商分配
*/
public function save_supplier_assignment($post_id) {
// 验证nonce
if (!isset($_POST['fsc_supplier_nonce']) ||
!wp_verify_nonce($_POST['fsc_supplier_nonce'], 'fsc_supplier_assignment')) {
return;
}
// 检查权限
if (!current_user_can('edit_post', $post_id)) {
return;
}
// 保存供应商分配
if (isset($_POST['assigned_supplier'])) {
$order = wc_get_order($post_id);
$order->update_meta_data('_assigned_supplier', sanitize_text_field($_POST['assigned_supplier']));
$order->save();
// 记录分配日志
$this->log_supplier_assignment($post_id, $_POST['assigned_supplier']);
}
}
/**
* 获取可用供应商列表
*/
private function get_available_suppliers() {
// 这里可以从数据库或外部API获取供应商列表
// 示例数据
return array(
'supplier_001' => '华东电子有限公司',
'supplier_002' => '华南包装材料厂',
'supplier_003' => '华北物流配送中心',
'supplier_004' => '西部原材料供应商'
);
}
/**
* 获取供应商详情
*/
private function get_supplier_details($supplier_id) {
$suppliers = array(
'supplier_001' => array(
'name' => '华东电子有限公司',
'contact' => '张经理',
'phone' => '13800138000',
'email' => 'zhang@example.com',
'address' => '上海市浦东新区'
),
// 其他供应商信息...
);
return isset($suppliers[$supplier_id]) ? $suppliers[$supplier_id] : false;
}
/**
* 处理订单状态变更
*/
public function handle_order_status_change($order_id, $old_status, $new_status) {
$order = wc_get_order($order_id);
// 当订单状态变为处理中时,通知供应商
if ($new_status === 'processing') {
$assigned_supplier = $order->get_meta('_assigned_supplier', true);
if ($assigned_supplier) {
$this->notify_supplier_new_order($order, $assigned_supplier);
}
}
// 当订单完成时,更新库存
if ($new_status === 'completed') {
$this->update_inventory_after_order($order);
}
}
/**
* 通知供应商新订单
*/
private function notify_supplier_new_order($order, $supplier_id) {
$supplier_info = $this->get_supplier_details($supplier_id);
if (!$supplier_info || empty($supplier_info['email'])) {
return;
}
$subject = sprintf('新订单通知 - 订单号: %s', $order->get_order_number());
$message = sprintf(
"尊敬的%s:nn您有一个新的订单需要处理:nn订单号:%sn订单金额:%sn下单时间:%snn订单包含以下商品:n",
$supplier_info['contact'],
$order->get_order_number(),
$order->get_total(),
$order->get_date_created()->format('Y-m-d H:i:s')
);
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$message .= sprintf(
"- %s × %dn",
$product ? $product->get_name() : $item->get_name(),
$item->get_quantity()
);
}
$message .= "n请及时处理此订单。nn此邮件由系统自动发送,请勿回复。";
// 发送邮件给供应商
wp_mail($supplier_info['email'], $subject, $message);
// 记录通知日志
$this->log_supplier_notification($order->get_id(), $supplier_id, 'new_order');
}
/**
* 订单完成后更新库存
*/
private function update_inventory_after_order($order) {
foreach ($order->get_items() as $item) {
$product = $item->get_product();
if ($product && $product->managing_stock()) {
$new_stock = $product->get_stock_quantity() - $item->get_quantity();
$product->set_stock_quantity($new_stock);
$product->save();
// 检查是否需要补货
if ($new_stock <= $product->get_low_stock_amount()) {
do_action('woocommerce_low_stock', $product);
}
}
}
}
/**
* 记录供应商分配日志
*/
private function log_supplier_assignment($order_id, $supplier_id) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'fsc_supplier_logs',
array(
'order_id' => $order_id,
'supplier_id' => $supplier_id,
'action' => 'assignment',
'details' => maybe_serialize(array(
'assigned_by' => get_current_user_id(),
'assigned_at' => current_time('mysql')
)),
'created_at' => current_time('mysql')
)
);
}
/**
* 记录供应商通知日志
*/
private function log_supplier_notification($order_id, $supplier_id, $notification_type) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'fsc_supplier_logs',
array(
'order_id' => $order_id,
'supplier_id' => $supplier_id,
'action' => 'notification_' . $notification_type,
'details' => maybe_serialize(array(
'notified_at' => current_time('mysql')
)),
'created_at' => current_time('mysql')
)
);
}
/**
* 获取供应商列表API回调
*/
public function get_suppliers($request) {
$suppliers = $this->get_available_suppliers();
$detailed_suppliers = array();
foreach ($suppliers as $id => $name) {
$details = $this->get_supplier_details($id);
if ($details) {
$detailed_suppliers[] = array_merge(
array('id' => $id),
$details
);
}
}
return rest_ensure_response(array(
'count' => count($detailed_suppliers),
'suppliers' => $detailed_suppliers
));
}
}
安全性和错误处理
1. API安全增强
创建includes/class-security-manager.php文件:
<?php
/**
* 安全管理器类
* 处理API安全、验证和错误处理
*/
class FSC_Security_Manager {
private $rate_limit_window = 3600; // 1小时
private $max_requests_per_hour = 1000;
public function __construct() {
// 初始化安全设置
add_action('init', array($this, 'init_security'));
}
/**
* 初始化安全设置
*/
public function init_security() {
// 创建API密钥管理页面
add_action('admin_menu', array($this, 'add_api_keys_page'));
// 注册设置
add_action('admin_init', array($this, 'register_api_settings'));
}
/**
* 添加API密钥管理页面
*/
public function add_api_keys_page() {
add_submenu_page(
'woocommerce',
'供应链API设置',
'供应链API',
'manage_options',
'fsc-api-settings',
array($this, 'render_api_keys_page')
);
}
/**
* 渲染API密钥管理页面
*/
public function render_api_keys_page() {
?>
<div class="wrap">
<h1>柔性供应链API设置</h1>
<form method="post" action="options.php">
<?php
settings_fields('fsc_api_settings_group');
do_settings_sections('fsc-api-settings');
submit_button();
?>
</form>
<hr>
<h2>API端点文档</h2>
<div class="api-docs">
<h3>可用端点:</h3>
<ul>
<li><strong>GET /wp-json/fsc/v1/inventory/{id}</strong> - 获取产品库存信息</li>
<li><strong>POST /wp-json/fsc/v1/inventory/batch-update</strong> - 批量更新库存</li>
<li><strong>POST /wp-json/fsc/v1/orders/sync</strong> - 同步外部订单</li>
<li><strong>GET /wp-json/fsc/v1/suppliers</strong> - 获取供应商列表</li>
</ul>
<h3>请求头要求:</h3>
<pre>X-API-Key: your_api_key_here
Content-Type: application/json</pre>
<h3>示例请求:</h3>
<pre>curl -X GET
-H "X-API-Key: your_api_key"
https://yourdomain.com/wp-json/fsc/v1/inventory/123</pre>
</div>
</div>
<?php
}
/**
* 注册API设置
*/
public function register_api_settings() {
register_setting('fsc_api_settings_group', 'fsc_api_keys');
register_setting('fsc_api_settings_group', 'fsc_rate_limit');
register_setting('fsc_api_settings_group', 'fsc_auto_reorder');
add_settings_section(
'fsc_api_main_section',
'API配置',
null,
'fsc-api-settings'
);
add_settings_field(
'fsc_api_keys',
'API密钥',
array($this, 'render_api_keys_field'),
'fsc-api-settings',
'fsc_api_main_section'
);
add_settings_field(
'fsc_rate_limit',
'API频率限制',
array($this, 'render_rate_limit_field'),
'fsc-api-settings',
'fsc_api_main_section'
);
add_settings_field(
'fsc_auto_reorder',
'自动补货',
array($this, 'render_auto_reorder_field'),
'fsc-api-settings',
'fsc_api_main_section'
);
}
/**
* 渲染API密钥字段
*/
public function render_api_keys_field() {
$api_keys = get_option('fsc_api_keys', array());
?>
<div id="api-keys-container">
<?php if (!empty($api_keys)): ?>
<?php foreach ($api_keys as $key): ?>
<div class="api-key-item" style="margin-bottom: 10px;">
<input type="text"
name="fsc_api_keys[]"
value="<?php echo esc_attr($key); ?>"
class="regular-text"
readonly>
<button type="button" class="button copy-api-key"
data-clipboard-text="<?php echo esc_attr($key); ?>">
复制
</button>
<button type="button" class="button remove-api-key">
删除
</button>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<button type="button" id="add-api-key" class="button">
+ 添加新API密钥
</button>
<script>
jQuery(document).ready(function($) {
// 添加新API密钥
$('#add-api-key').click(function() {
var newKey = generateApiKey();
var html = '<div class="api-key-item" style="margin-bottom: 10px;">' +
'<input type="text" name="fsc_api_keys[]" value="' + newKey + '" class="regular-text" readonly>' +
'<button type="button" class="button copy-api-key" data-clipboard-text="' + newKey + '">复制</button>' +
'<button type="button" class="button remove-api-key">删除</button>' +
'</div>';
$('#api-keys-container').append(html);
});
// 删除API密钥
$(document).on('click', '.remove-api-key', function() {
$(this).closest('.api-key-item').remove();
});
// 复制API密钥
$(document).on('click', '.copy-api-key', function() {
var copyText = $(this).data('clipboard-text');
navigator.clipboard.writeText(copyText).then(function() {
alert('API密钥已复制到剪贴板');
});
});
// 生成随机API密钥
function generateApiKey() {
return 'fsc_' + Math.random().toString(36).substr(2) +
Math.random().toString(36).substr(2);
}
});
</script>
<?php
}
/**
* 渲染频率限制字段
*/
public function render_rate_limit_field() {
$rate_limit = get_option('fsc_rate_limit', 1000);
?>
<input type="number"
name="fsc_rate_limit"
value="<?php echo esc_attr($rate_limit); ?>"
class="small-text">
<p class="description">每小时最大请求次数</p>
<?php
}
/**
* 渲染自动补货字段
*/
public function render_auto_reorder_field() {
$auto_reorder = get_option('fsc_auto_reorder', 'no');
?>
<label>
<input type="radio"
name="fsc_auto_reorder"
value="yes"
<?php checked($auto_reorder, 'yes'); ?>>
启用
</label>
<label style="margin-left: 20px;">
<input type="radio"
name="fsc_auto_reorder"
value="no"
<?php checked($auto_reorder, 'no'); ?>>
禁用
</label>
<?php
}
/**
* 增强的API权限检查
*/
public function enhanced_permission_check($request) {
// 检查API密钥
$api_key = $request->get_header('X-API-Key');
$valid_keys = get_option('fsc_api_keys', array());
if (empty($api_key) || !in_array($api_key, $valid_keys)) {
return new WP_Error(
'rest_forbidden',
'无效的API密钥',
array('status' => 403)
);
}
// 检查频率限制
if (!$this->check_rate_limit($api_key)) {
return new WP_Error(
'rate_limit_exceeded',
'API调用频率超限',
array('status' => 429)
);
}
// 检查IP白名单(可选)
if (!$this->check_ip_whitelist($request)) {
return new WP_Error(
'ip_not_allowed',
'IP地址不在白名单中',
array('status' => 403)
);
}
return true;
}
/**
* 检查频率限制
*/
private function check_rate_limit($api_key) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_api_logs';
$window_start = date('Y-m-d H:i:s', time() - $this->rate_limit_window);
$count = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $table_name
WHERE api_key = %s AND request_time > %s",
$api_key,
$window_start
));
$max_requests = get_option('fsc_rate_limit', $this->max_requests_per_hour);
return $count < $max_requests;
}
/**
* 记录API调用
*/
public function log_api_request($api_key, $endpoint, $status) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'fsc_api_logs',
array(
'api_key' => $api_key,
'endpoint' => $endpoint,
'ip_address' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'status_code' => $status,
'request_time' => current_time('mysql')
)
