WordPress文创插件实现柔性版税自动结算的详细教程
概述:为什么需要柔性版税结算系统
在数字文创产业蓬勃发展的今天,内容创作者面临着版税结算的复杂挑战。传统的固定比例分成模式已无法满足多样化的合作需求。柔性版税系统允许根据销量、时间、用户等级等多种因素动态调整分成比例,为创作者和平台提供更公平、灵活的收益分配方案。
本教程将指导您开发一个WordPress插件,实现智能化的柔性版税自动结算功能。通过这个系统,您可以设置多级分成规则,自动计算并分配销售收入,大大减少人工结算的工作量和错误率。
环境准备与插件基础结构
首先,我们需要创建插件的基本文件结构。在WordPress的wp-content/plugins目录下创建一个新文件夹,命名为flexible-royalty-system。
<?php
/**
* Plugin Name: 柔性版税自动结算系统
* Plugin URI: https://yourwebsite.com/
* Description: 为WordPress文创平台提供智能柔性版税结算功能
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: flexible-royalty
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FRS_VERSION', '1.0.0');
define('FRS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FRS_PLUGIN_URL', plugin_dir_url(__FILE__));
// 初始化插件
class Flexible_Royalty_System {
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('plugins_loaded', array($this, 'load_textdomain'));
}
public function activate() {
// 创建必要的数据库表
$this->create_tables();
// 设置默认选项
update_option('frs_version', FRS_VERSION);
}
public function deactivate() {
// 清理临时数据
// 注意:这里不删除数据表,保留结算记录
}
public function init() {
// 初始化代码将在这里添加
}
public function load_textdomain() {
load_plugin_textdomain('flexible-royalty', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
public function add_admin_menu() {
// 管理菜单代码将在这里添加
}
private function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'frs_royalty_rules';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
recipient_id bigint(20) NOT NULL,
royalty_type varchar(50) NOT NULL,
base_percentage decimal(5,2) DEFAULT 0.00,
variable_rules text,
conditions text,
start_date datetime DEFAULT '0000-00-00 00:00:00',
end_date datetime DEFAULT '0000-00-00 00:00:00',
is_active tinyint(1) DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id),
KEY recipient_id (recipient_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 创建结算记录表
$table_name = $wpdb->prefix . 'frs_settlements';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
order_id bigint(20) NOT NULL,
product_id bigint(20) NOT NULL,
recipient_id bigint(20) NOT NULL,
amount decimal(10,2) NOT NULL,
royalty_percentage decimal(5,2) NOT NULL,
calculated_amount decimal(10,2) NOT NULL,
settlement_status varchar(20) DEFAULT 'pending',
settlement_date datetime DEFAULT NULL,
notes text,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY order_id (order_id),
KEY recipient_id (recipient_id),
KEY settlement_status (settlement_status)
) $charset_collate;";
dbDelta($sql);
}
}
// 启动插件
Flexible_Royalty_System::get_instance();
?>
数据库设计与版税规则引擎
柔性版税系统的核心是规则引擎。我们需要设计一个能够处理复杂条件的规则系统。以下代码展示了规则处理的核心类:
<?php
/**
* 版税规则引擎
* 处理柔性版税计算逻辑
*/
class Royalty_Rule_Engine {
/**
* 计算订单的版税分配
*
* @param int $order_id 订单ID
* @param int $product_id 产品ID
* @param float $product_price 产品价格
* @return array 分配结果
*/
public function calculate_royalties($order_id, $product_id, $product_price) {
global $wpdb;
$results = array();
$table_name = $wpdb->prefix . 'frs_royalty_rules';
// 获取适用于此产品的所有有效版税规则
$rules = $wpdb->get_results($wpdb->prepare(
"SELECT * FROM $table_name
WHERE product_id = %d
AND is_active = 1
AND (start_date <= NOW() OR start_date = '0000-00-00 00:00:00')
AND (end_date >= NOW() OR end_date = '0000-00-00 00:00:00')",
$product_id
));
foreach ($rules as $rule) {
// 解析变量规则
$variable_rules = json_decode($rule->variable_rules, true);
$conditions = json_decode($rule->conditions, true);
// 检查条件是否满足
if ($this->check_conditions($order_id, $product_id, $conditions)) {
// 计算实际分成比例
$actual_percentage = $this->calculate_actual_percentage(
$rule->base_percentage,
$variable_rules,
$order_id,
$product_id
);
// 计算分配金额
$calculated_amount = $product_price * ($actual_percentage / 100);
$results[] = array(
'rule_id' => $rule->id,
'recipient_id' => $rule->recipient_id,
'base_percentage' => $rule->base_percentage,
'actual_percentage' => $actual_percentage,
'calculated_amount' => $calculated_amount,
'conditions_met' => true
);
// 记录到结算表
$this->record_settlement(
$order_id,
$product_id,
$rule->recipient_id,
$product_price,
$actual_percentage,
$calculated_amount
);
}
}
return $results;
}
/**
* 检查条件是否满足
*
* @param int $order_id 订单ID
* @param int $product_id 产品ID
* @param array $conditions 条件数组
* @return bool 是否满足条件
*/
private function check_conditions($order_id, $product_id, $conditions) {
if (empty($conditions)) {
return true;
}
foreach ($conditions as $condition) {
$condition_type = $condition['type'] ?? '';
$condition_value = $condition['value'] ?? '';
$condition_operator = $condition['operator'] ?? '=';
switch ($condition_type) {
case 'sales_count':
$actual_value = $this->get_product_sales_count($product_id);
break;
case 'total_revenue':
$actual_value = $this->get_product_total_revenue($product_id);
break;
case 'user_role':
$order = wc_get_order($order_id);
$customer_id = $order->get_customer_id();
$user = get_userdata($customer_id);
$actual_value = $user ? implode(',', $user->roles) : '';
break;
case 'purchase_date':
$order = wc_get_order($order_id);
$actual_value = $order->get_date_created()->date('Y-m-d');
break;
default:
$actual_value = '';
}
if (!$this->compare_values($actual_value, $condition_value, $condition_operator)) {
return false;
}
}
return true;
}
/**
* 计算实际分成比例
*
* @param float $base_percentage 基础比例
* @param array $variable_rules 变量规则
* @param int $order_id 订单ID
* @param int $product_id 产品ID
* @return float 实际比例
*/
private function calculate_actual_percentage($base_percentage, $variable_rules, $order_id, $product_id) {
$actual_percentage = $base_percentage;
if (empty($variable_rules)) {
return $actual_percentage;
}
foreach ($variable_rules as $rule) {
$rule_type = $rule['type'] ?? '';
$rule_value = $rule['value'] ?? 0;
$rule_effect = $rule['effect'] ?? 'add';
$rule_target = $rule['target'] ?? 'percentage';
switch ($rule_type) {
case 'sales_tier':
$sales_count = $this->get_product_sales_count($product_id);
if ($sales_count >= $rule_value) {
$actual_percentage = $this->apply_effect(
$actual_percentage,
$rule['adjustment'] ?? 0,
$rule_effect
);
}
break;
case 'revenue_tier':
$total_revenue = $this->get_product_total_revenue($product_id);
if ($total_revenue >= $rule_value) {
$actual_percentage = $this->apply_effect(
$actual_percentage,
$rule['adjustment'] ?? 0,
$rule_effect
);
}
break;
case 'time_based':
$order = wc_get_order($order_id);
$order_date = $order->get_date_created()->date('Y-m-d');
$start_date = $rule['start_date'] ?? '';
$end_date = $rule['end_date'] ?? '';
if ((empty($start_date) || $order_date >= $start_date) &&
(empty($end_date) || $order_date <= $end_date)) {
$actual_percentage = $this->apply_effect(
$actual_percentage,
$rule['adjustment'] ?? 0,
$rule_effect
);
}
break;
}
}
// 确保比例在0-100之间
return max(0, min(100, $actual_percentage));
}
/**
* 应用效果(增加或减少)
*/
private function apply_effect($current_value, $adjustment, $effect) {
if ($effect === 'add') {
return $current_value + $adjustment;
} elseif ($effect === 'subtract') {
return $current_value - $adjustment;
} elseif ($effect === 'multiply') {
return $current_value * $adjustment;
} else {
return $current_value;
}
}
/**
* 获取产品销量
*/
private function get_product_sales_count($product_id) {
global $wpdb;
// 这里简化处理,实际应用中需要更复杂的查询
$count = $wpdb->get_var($wpdb->prepare(
"SELECT SUM(oi.quantity)
FROM {$wpdb->prefix}woocommerce_order_items oi
JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim ON oi.order_item_id = oim.order_item_id
WHERE oim.meta_key = '_product_id' AND oim.meta_value = %d",
$product_id
));
return $count ? intval($count) : 0;
}
/**
* 记录结算信息
*/
private function record_settlement($order_id, $product_id, $recipient_id, $amount, $percentage, $calculated_amount) {
global $wpdb;
$table_name = $wpdb->prefix . 'frs_settlements';
$wpdb->insert(
$table_name,
array(
'order_id' => $order_id,
'product_id' => $product_id,
'recipient_id' => $recipient_id,
'amount' => $amount,
'royalty_percentage' => $percentage,
'calculated_amount' => $calculated_amount,
'settlement_status' => 'pending',
'created_at' => current_time('mysql')
),
array('%d', '%d', '%d', '%f', '%f', '%f', '%s', '%s')
);
}
}
?>
管理界面与规则配置
为了让用户方便地配置版税规则,我们需要创建一个直观的管理界面:
<?php
/**
* 管理界面类
* 提供版税规则配置界面
*/
class FRS_Admin_Interface {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_pages'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
}
public function add_admin_pages() {
// 主菜单
add_menu_page(
'柔性版税系统',
'版税结算',
'manage_options',
'frs-dashboard',
array($this, 'render_dashboard_page'),
'dashicons-money-alt',
30
);
// 子菜单
add_submenu_page(
'frs-dashboard',
'版税规则',
'规则管理',
'manage_options',
'frs-rules',
array($this, 'render_rules_page')
);
add_submenu_page(
'frs-dashboard',
'结算记录',
'结算记录',
'manage_options',
'frs-settlements',
array($this, 'render_settlements_page')
);
add_submenu_page(
'frs-dashboard',
'报表分析',
'报表分析',
'manage_options',
'frs-reports',
array($this, 'render_reports_page')
);
}
public function enqueue_admin_scripts($hook) {
if (strpos($hook, 'frs-') !== false) {
// 加载CSS
wp_enqueue_style(
'frs-admin-style',
FRS_PLUGIN_URL . 'assets/css/admin.css',
array(),
FRS_VERSION
);
// 加载JavaScript
wp_enqueue_script(
'frs-admin-script',
FRS_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'jquery-ui-sortable', 'jquery-ui-datepicker'),
FRS_VERSION,
true
);
// 加载日期选择器CSS
wp_enqueue_style(
'jquery-ui-style',
'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css'
);
// 本地化脚本
wp_localize_script('frs-admin-script', 'frs_admin', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('frs_admin_nonce'),
'confirm_delete' => __('确定要删除这条规则吗?', 'flexible-royalty')
));
}
}
public function render_dashboard_page() {
?>
<div class="wrap frs-dashboard">
<h1><?php _e('柔性版税结算系统', 'flexible-royalty'); ?></h1>
<div class="frs-stats-container">
<div class="frs-stat-card">
<h3><?php _e('待结算总额', 'flexible-royalty'); ?></h3>
<p class="stat-number"><?php echo $this->get_pending_total(); ?></p>
</div>
<div class="frs-stat-card">
<h3><?php _e('已结算总额', 'flexible-royalty'); ?></h3>
<p class="stat-number"><?php echo $this->get_settled_total(); ?></p>
</div>
<div class="frs-stat-card">
<h3><?php _e('活跃规则', 'flexible-royalty'); ?></h3>
<p class="stat-number"><?php echo $this->get_active_rules_count(); ?></p>
</div>
<div class="frs-stat-card">
<h3><?php _e('参与创作者', 'flexible-royalty'); ?></h3>
<p class="stat-number"><?php echo $this->get_creators_count(); ?></p>
</div>
</div>
<div class="frs-recent-activity">
活动', 'flexible-royalty'); ?></h2>
<?php $this->display_recent_activity(); ?>
</div>
</div>
<?php
}
public function render_rules_page() {
global $wpdb;
// 处理表单提交
if (isset($_POST['submit_rule']) && check_admin_referer('frs_save_rule', 'frs_rule_nonce')) {
$this->save_royalty_rule($_POST);
}
// 处理删除请求
if (isset($_GET['delete_rule']) && check_admin_referer('frs_delete_rule')) {
$this->delete_royalty_rule(intval($_GET['delete_rule']));
}
// 获取所有规则
$table_name = $wpdb->prefix . 'frs_royalty_rules';
$rules = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");
// 获取所有产品
$products = wc_get_products(array('limit' => -1));
// 获取所有用户(创作者)
$creators = get_users(array(
'role__in' => array('author', 'contributor', 'editor'),
'fields' => array('ID', 'display_name')
));
?>
<div class="wrap frs-rules">
<h1><?php _e('版税规则管理', 'flexible-royalty'); ?></h1>
<div class="frs-tabs">
<h2 class="nav-tab-wrapper">
<a href="#tab-rules-list" class="nav-tab nav-tab-active"><?php _e('规则列表', 'flexible-royalty'); ?></a>
<a href="#tab-add-rule" class="nav-tab"><?php _e('添加新规则', 'flexible-royalty'); ?></a>
</h2>
<div id="tab-rules-list" class="frs-tab-content active">
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e('ID', 'flexible-royalty'); ?></th>
<th><?php _e('产品', 'flexible-royalty'); ?></th>
<th><?php _e('创作者', 'flexible-royalty'); ?></th>
<th><?php _e('基础比例', 'flexible-royalty'); ?></th>
<th><?php _e('生效时间', 'flexible-royalty'); ?></th>
<th><?php _e('状态', 'flexible-royalty'); ?></th>
<th><?php _e('操作', 'flexible-royalty'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($rules as $rule):
$product = wc_get_product($rule->product_id);
$creator = get_userdata($rule->recipient_id);
?>
<tr>
<td><?php echo $rule->id; ?></td>
<td><?php echo $product ? $product->get_name() : '产品已删除'; ?></td>
<td><?php echo $creator ? $creator->display_name : '用户已删除'; ?></td>
<td><?php echo $rule->base_percentage; ?>%</td>
<td>
<?php
echo date('Y-m-d', strtotime($rule->start_date)) . ' ~ ' .
date('Y-m-d', strtotime($rule->end_date));
?>
</td>
<td>
<span class="frs-status-badge frs-status-<?php echo $rule->is_active ? 'active' : 'inactive'; ?>">
<?php echo $rule->is_active ? '活跃' : '停用'; ?>
</span>
</td>
<td>
<a href="?page=frs-rules&edit_rule=<?php echo $rule->id; ?>" class="button button-small">
<?php _e('编辑', 'flexible-royalty'); ?>
</a>
<a href="<?php echo wp_nonce_url('?page=frs-rules&delete_rule=' . $rule->id, 'frs_delete_rule'); ?>"
class="button button-small button-danger"
onclick="return confirm('确定要删除这条规则吗?');">
<?php _e('删除', 'flexible-royalty'); ?>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="tab-add-rule" class="frs-tab-content">
<form method="post" action="">
<?php wp_nonce_field('frs_save_rule', 'frs_rule_nonce'); ?>
<div class="frs-form-section">
<h3><?php _e('基本设置', 'flexible-royalty'); ?></h3>
<table class="form-table">
<tr>
<th scope="row">
<label for="product_id"><?php _e('选择产品', 'flexible-royalty'); ?></label>
</th>
<td>
<select name="product_id" id="product_id" required>
<option value=""><?php _e('请选择产品', 'flexible-royalty'); ?></option>
<?php foreach ($products as $product): ?>
<option value="<?php echo $product->get_id(); ?>">
<?php echo $product->get_name(); ?> (ID: <?php echo $product->get_id(); ?>)
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th scope="row">
<label for="recipient_id"><?php _e('创作者', 'flexible-royalty'); ?></label>
</th>
<td>
<select name="recipient_id" id="recipient_id" required>
<option value=""><?php _e('请选择创作者', 'flexible-royalty'); ?></option>
<?php foreach ($creators as $creator): ?>
<option value="<?php echo $creator->ID; ?>">
<?php echo $creator->display_name; ?>
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr>
<th scope="row">
<label for="base_percentage"><?php _e('基础分成比例 (%)', 'flexible-royalty'); ?></label>
</th>
<td>
<input type="number"
name="base_percentage"
id="base_percentage"
min="0"
max="100"
step="0.01"
required>
</td>
</tr>
<tr>
<th scope="row">
<label for="royalty_type"><?php _e('版税类型', 'flexible-royalty'); ?></label>
</th>
<td>
<select name="royalty_type" id="royalty_type">
<option value="fixed"><?php _e('固定比例', 'flexible-royalty'); ?></option>
<option value="variable"><?php _e('可变比例', 'flexible-royalty'); ?></option>
<option value="tiered"><?php _e('阶梯比例', 'flexible-royalty'); ?></option>
</select>
</td>
</tr>
</table>
</div>
<div class="frs-form-section">
<h3><?php _e('时间设置', 'flexible-royalty'); ?></h3>
<table class="form-table">
<tr>
<th scope="row">
<label for="start_date"><?php _e('开始日期', 'flexible-royalty'); ?></label>
</th>
<td>
<input type="text"
name="start_date"
id="start_date"
class="frs-datepicker">
</td>
</tr>
<tr>
<th scope="row">
<label for="end_date"><?php _e('结束日期', 'flexible-royalty'); ?></label>
</th>
<td>
<input type="text"
name="end_date"
id="end_date"
class="frs-datepicker">
</td>
</tr>
</table>
</div>
<div class="frs-form-section">
<h3><?php _e('条件设置', 'flexible-royalty'); ?></h3>
<div id="frs-conditions-container">
<!-- 条件将通过JavaScript动态添加 -->
</div>
<button type="button" id="add-condition" class="button">
<?php _e('添加条件', 'flexible-royalty'); ?>
</button>
</div>
<div class="frs-form-section">
<h3><?php _e('变量规则', 'flexible-royalty'); ?></h3>
<div id="frs-variable-rules-container">
<!-- 变量规则将通过JavaScript动态添加 -->
</div>
<button type="button" id="add-variable-rule" class="button">
<?php _e('添加变量规则', 'flexible-royalty'); ?>
</button>
</div>
<p class="submit">
<input type="submit"
name="submit_rule"
class="button button-primary"
value="<?php _e('保存规则', 'flexible-royalty'); ?>">
</p>
</form>
</div>
</div>
</div>
<script type="text/html" id="tmpl-frs-condition">
<div class="frs-condition-item">
<select name="conditions[{{data.index}}][type]" class="frs-condition-type">
<option value="sales_count"><?php _e('销量', 'flexible-royalty'); ?></option>
<option value="total_revenue"><?php _e('总收入', 'flexible-royalty'); ?></option>
<option value="user_role"><?php _e('用户角色', 'flexible-royalty'); ?></option>
<option value="purchase_date"><?php _e('购买日期', 'flexible-royalty'); ?></option>
</select>
<select name="conditions[{{data.index}}][operator]" class="frs-condition-operator">
<option value="=">=</option>
<option value="!=">!=</option>
<option value=">">></option>
<option value=">=">>=</option>
<option value="<"><</option>
<option value="<="><=</option>
</select>
<input type="text"
name="conditions[{{data.index}}][value]"
class="frs-condition-value"
placeholder="<?php _e('值', 'flexible-royalty'); ?>">
<button type="button" class="button button-small remove-condition">
<?php _e('删除', 'flexible-royalty'); ?>
</button>
</div>
</script>
<script type="text/html" id="tmpl-frs-variable-rule">
<div class="frs-variable-rule-item">
<select name="variable_rules[{{data.index}}][type]" class="frs-rule-type">
<option value="sales_tier"><?php _e('销量阶梯', 'flexible-royalty'); ?></option>
<option value="revenue_tier"><?php _e('收入阶梯', 'flexible-royalty'); ?></option>
<option value="time_based"><?php _e('时间基础', 'flexible-royalty'); ?></option>
</select>
<input type="number"
name="variable_rules[{{data.index}}][value]"
class="frs-rule-value"
placeholder="<?php _e('阈值', 'flexible-royalty'); ?>">
<select name="variable_rules[{{data.index}}][effect]" class="frs-rule-effect">
<option value="add"><?php _e('增加', 'flexible-royalty'); ?></option>
<option value="subtract"><?php _e('减少', 'flexible-royalty'); ?></option>
<option value="multiply"><?php _e('乘以', 'flexible-royalty'); ?></option>
</select>
<input type="number"
name="variable_rules[{{data.index}}][adjustment]"
class="frs-rule-adjustment"
placeholder="<?php _e('调整值', 'flexible-royalty'); ?>"
step="0.01">
<button type="button" class="button button-small remove-variable-rule">
<?php _e('删除', 'flexible-royalty'); ?>
</button>
</div>
</script>
<?php
}
private function save_royalty_rule($data) {
global $wpdb;
$table_name = $wpdb->prefix . 'frs_royalty_rules';
// 准备数据
$rule_data = array(
'product_id' => intval($data['product_id']),
'recipient_id' => intval($data['recipient_id']),
'royalty_type' => sanitize_text_field($data['royalty_type']),
'base_percentage' => floatval($data['base_percentage']),
'variable_rules' => json_encode($data['variable_rules'] ?? array()),
'conditions' => json_encode($data['conditions'] ?? array()),
'start_date' => !empty($data['start_date']) ? date('Y-m-d H:i:s', strtotime($data['start_date'])) : '0000-00-00 00:00:00',
'end_date' => !empty($data['end_date']) ? date('Y-m-d H:i:s', strtotime($data['end_date'])) : '0000-00-00 00:00:00',
'is_active' => isset($data['is_active']) ? 1 : 1
);
// 插入或更新
if (isset($data['rule_id']) && !empty($data['rule_id'])) {
$wpdb->update(
$table_name,
$rule_data,
array('id' => intval($data['rule_id']))
);
} else {
$wpdb->insert($table_name, $rule_data);
}
// 显示成功消息
add_settings_error(
'frs_messages',
'frs_message',
__('规则已保存成功!', 'flexible-royalty'),
'success'
);
}
}
?>
## 结算处理与自动支付集成
实现自动结算功能,支持多种支付方式:
<?php
/**
- 结算处理器
- 处理版税结算和支付
*/
class FRS_Settlement_Processor {
private $payment_gateways = array();
public function __construct() {
$this->init_payment_gateways();
// 注册定时任务
add_action('frs_daily_settlement', array($this, 'process_daily_settlements'));
// 注册手动结算钩子
add_action('admin_post_frs_process_settlement', array($this, 'process_manual_settlement'));
}
/**
* 初始化支付网关
*/
private function init_payment_gateways() {
// 支付宝网关
$this->payment_gateways['alipay'] = new FRS_Alipay_Gateway();
// 微信支付网关
$this->payment_gateways['wechat'] = new FRS_Wechat_Gateway();
// PayPal网关
$this->payment_gateways['paypal'] = new FRS_PayPal_Gateway();
// 银行转账网关
$this->payment_gateways['bank_transfer'] = new FRS_Bank_Transfer_Gateway();
// 允许其他插件添加网关
$this->payment_gateways = apply_filters('frs_payment_gateways', $this->payment_gateways);
}
/**
* 处理每日自动结算
*/
public function process_daily_settlements() {
global $wpdb;
$table_name = $wpdb->prefix . 'frs_settlements';
// 获取所有待结算的记录
$pending_settlements = $wpdb->get_results(
"SELECT s.*, u.user_email, u.display_name
FROM $table_name s
LEFT JOIN {$wpdb->users} u ON s.recipient_id = u.ID
WHERE s.settlement_status = 'pending'
AND s.calculated_amount > 0
ORDER BY s.created_at ASC"
);
if (empty($pending_settlements)) {
$this->log('没有待结算的记录');
return;
}
$this->log('开始处理结算,共 ' . count($pending_settlements) . ' 条记录');
// 按收款人分组
$grouped_settlements = array();
foreach ($pending_settlements as $settlement) {
$recipient_id = $settlement->recipient_id;
if (!isset($grouped_settlements[$recipient_id])) {
$grouped_settlements[$recipient_id] = array(
'user_info' => array(
'id' => $settlement->recipient_id,
'email' => $settlement->user_email,
'name' => $settlement->display_name
),
'settlements' => array(),
'total_amount' => 0
);
}
$grouped_settlements[$recipient_id]['settlements'][] = $settlement;
$grouped_settlements[$recipient_id]['total_amount'] += $settlement->calculated_amount;
}
