文章目录[隐藏]
WordPress小批量定制插件与支付接口集成教程
一、前言:为什么需要定制插件与支付集成
在WordPress网站运营中,我们常常遇到一些特殊需求,现有的通用插件无法完全满足。特别是当涉及到支付功能时,每个商家的需求都可能有所不同。本文将指导您如何创建一个WordPress定制插件,并集成支付接口,实现小批量的个性化需求。
本教程适合有一定PHP和WordPress开发基础的开发者,我们将创建一个简单的商品展示与支付插件,集成支付宝接口作为示例。
二、环境准备与插件基础结构
2.1 创建插件基本文件
首先,在WordPress的wp-content/plugins/目录下创建一个新文件夹,命名为custom-payment-plugin。在该文件夹中创建以下文件:
custom-payment-plugin/
├── custom-payment-plugin.php # 主插件文件
├── includes/
│ ├── class-products.php # 商品管理类
│ ├── class-payment.php # 支付处理类
│ └── class-shortcodes.php # 短代码类
├── templates/
│ ├── product-list.php # 商品列表模板
│ └── payment-form.php # 支付表单模板
└── assets/
├── css/
│ └── style.css # 样式文件
└── js/
└── script.js # 脚本文件
2.2 主插件文件配置
打开custom-payment-plugin.php文件,添加以下代码:
<?php
/**
* Plugin Name: 自定义支付插件
* Plugin URI: https://yourwebsite.com/
* Description: 自定义商品展示与支付集成插件
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: custom-payment
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('CUSTOM_PAYMENT_VERSION', '1.0.0');
define('CUSTOM_PAYMENT_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CUSTOM_PAYMENT_PLUGIN_URL', plugin_dir_url(__FILE__));
// 自动加载类文件
spl_autoload_register(function ($class_name) {
$prefix = 'Custom_Payment_';
$base_dir = CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/';
// 检查类是否使用我们的前缀
$len = strlen($prefix);
if (strncmp($prefix, $class_name, $len) !== 0) {
return;
}
// 获取相对类名
$relative_class = substr($class_name, $len);
// 替换命名空间分隔符为目录分隔符
$file = $base_dir . 'class-' . strtolower(str_replace('_', '-', $relative_class)) . '.php';
// 如果文件存在,则加载它
if (file_exists($file)) {
require $file;
}
});
// 初始化插件
function custom_payment_init() {
// 检查依赖
if (!class_exists('WC_Payment_Gateway')) {
add_action('admin_notices', function() {
echo '<div class="notice notice-error"><p>自定义支付插件需要WooCommerce。请先安装并激活WooCommerce插件。</p></div>';
});
return;
}
// 初始化各个类
if (is_admin()) {
new Custom_Payment_Products();
}
new Custom_Payment_Shortcodes();
new Custom_Payment_Payment();
}
add_action('plugins_loaded', 'custom_payment_init');
// 激活插件时创建数据库表
function custom_payment_activate() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'custom_products';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
description text,
price decimal(10,2) NOT NULL,
status tinyint(1) DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 添加默认商品示例
$wpdb->insert(
$table_name,
array(
'name' => '示例商品',
'description' => '这是一个示例商品描述',
'price' => 99.99,
'status' => 1
)
);
}
register_activation_hook(__FILE__, 'custom_payment_activate');
// 停用插件时清理
function custom_payment_deactivate() {
// 可以在这里添加清理代码,但通常保留数据
}
register_deactivation_hook(__FILE__, 'custom_payment_deactivate');
三、商品管理功能实现
3.1 创建商品管理类
在includes/class-products.php文件中添加以下代码:
<?php
/**
* 商品管理类
* 处理商品的增删改查操作
*/
class Custom_Payment_Products {
public function __construct() {
// 添加管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 处理表单提交
add_action('admin_post_add_custom_product', array($this, 'handle_add_product'));
add_action('admin_post_delete_custom_product', array($this, 'handle_delete_product'));
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
'自定义商品', // 页面标题
'自定义商品', // 菜单标题
'manage_options', // 权限
'custom-products', // 菜单slug
array($this, 'render_admin_page'), // 回调函数
'dashicons-cart', // 图标
30 // 位置
);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
// 获取所有商品
$products = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 1 ORDER BY id DESC");
?>
<div class="wrap">
<h1>自定义商品管理</h1>
<!-- 添加商品表单 -->
<h2>添加新商品</h2>
<form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="add_custom_product">
<?php wp_nonce_field('add_custom_product_nonce', 'product_nonce'); ?>
<table class="form-table">
<tr>
<th><label for="product_name">商品名称</label></th>
<td><input type="text" id="product_name" name="product_name" required class="regular-text"></td>
</tr>
<tr>
<th><label for="product_description">商品描述</label></th>
<td><textarea id="product_description" name="product_description" rows="4" class="large-text"></textarea></td>
</tr>
<tr>
<th><label for="product_price">价格</label></th>
<td><input type="number" id="product_price" name="product_price" step="0.01" min="0" required></td>
</tr>
</table>
<?php submit_button('添加商品'); ?>
</form>
<!-- 商品列表 -->
<h2>商品列表</h2>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>ID</th>
<th>商品名称</th>
<th>描述</th>
<th>价格</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php if ($products): ?>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo $product->id; ?></td>
<td><?php echo esc_html($product->name); ?></td>
<td><?php echo esc_html($product->description); ?></td>
<td>¥<?php echo number_format($product->price, 2); ?></td>
<td><?php echo $product->created_at; ?></td>
<td>
<form method="post" action="<?php echo admin_url('admin-post.php'); ?>" style="display:inline;">
<input type="hidden" name="action" value="delete_custom_product">
<input type="hidden" name="product_id" value="<?php echo $product->id; ?>">
<?php wp_nonce_field('delete_custom_product_nonce', 'product_nonce'); ?>
<button type="submit" class="button button-small button-secondary" onclick="return confirm('确定删除这个商品吗?')">删除</button>
</form>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="6">暂无商品</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<?php
}
/**
* 处理添加商品
*/
public function handle_add_product() {
// 验证nonce
if (!isset($_POST['product_nonce']) || !wp_verify_nonce($_POST['product_nonce'], 'add_custom_product_nonce')) {
wp_die('安全验证失败');
}
// 验证权限
if (!current_user_can('manage_options')) {
wp_die('权限不足');
}
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
// 获取并清理数据
$name = sanitize_text_field($_POST['product_name']);
$description = sanitize_textarea_field($_POST['product_description']);
$price = floatval($_POST['product_price']);
// 插入数据库
$result = $wpdb->insert(
$table_name,
array(
'name' => $name,
'description' => $description,
'price' => $price,
'status' => 1
),
array('%s', '%s', '%f', '%d')
);
if ($result) {
wp_redirect(admin_url('admin.php?page=custom-products&message=success'));
} else {
wp_redirect(admin_url('admin.php?page=custom-products&message=error'));
}
exit;
}
/**
* 处理删除商品
*/
public function handle_delete_product() {
// 验证nonce
if (!isset($_POST['product_nonce']) || !wp_verify_nonce($_POST['product_nonce'], 'delete_custom_product_nonce')) {
wp_die('安全验证失败');
}
// 验证权限
if (!current_user_can('manage_options')) {
wp_die('权限不足');
}
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
$product_id = intval($_POST['product_id']);
// 软删除:更新状态为0
$result = $wpdb->update(
$table_name,
array('status' => 0),
array('id' => $product_id),
array('%d'),
array('%d')
);
wp_redirect(admin_url('admin.php?page=custom-products&message=deleted'));
exit;
}
}
四、支付接口集成
4.1 创建支付处理类
在includes/class-payment.php文件中添加以下代码:
<?php
/**
* 支付处理类
* 集成支付宝支付接口
*/
class Custom_Payment_Payment {
private $alipay_config;
public function __construct() {
// 初始化支付宝配置
$this->alipay_config = array(
'app_id' => get_option('custom_payment_alipay_app_id', ''),
'merchant_private_key' => get_option('custom_payment_alipay_private_key', ''),
'alipay_public_key' => get_option('custom_payment_alipay_public_key', ''),
'gateway_url' => get_option('custom_payment_alipay_gateway', 'https://openapi.alipay.com/gateway.do'),
'charset' => 'UTF-8',
'sign_type' => 'RSA2',
'version' => '1.0',
);
// 添加支付处理端点
add_action('init', array($this, 'add_payment_endpoints'));
add_action('template_redirect', array($this, 'handle_payment_endpoints'));
// 添加支付回调处理
add_action('admin_post_nopriv_alipay_notify', array($this, 'handle_alipay_notify'));
add_action('admin_post_alipay_notify', array($this, 'handle_alipay_notify'));
// 添加设置页面
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_menu', array($this, 'add_settings_page'));
}
/**
* 添加支付相关端点
*/
public function add_payment_endpoints() {
add_rewrite_rule('^custom-payment/([^/]+)/?', 'index.php?custom_payment_action=$matches[1]', 'top');
add_rewrite_tag('%custom_payment_action%', '([^&]+)');
}
/**
* 处理支付端点
*/
public function handle_payment_endpoints() {
global $wp_query;
if (isset($wp_query->query_vars['custom_payment_action'])) {
$action = $wp_query->query_vars['custom_payment_action'];
switch ($action) {
case 'create-order':
$this->create_order();
break;
case 'payment-success':
$this->payment_success();
break;
case 'payment-failed':
$this->payment_failed();
break;
}
}
}
/**
* 创建订单
*/
private function create_order() {
// 验证nonce
if (!isset($_POST['payment_nonce']) || !wp_verify_nonce($_POST['payment_nonce'], 'custom_payment_nonce')) {
wp_die('安全验证失败');
}
// 获取商品信息
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
$product = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d AND status = 1", $product_id));
if (!$product) {
wp_die('商品不存在');
}
// 计算总价
$total_amount = $product->price * $quantity;
// 生成订单号
$out_trade_no = date('YmdHis') . mt_rand(1000, 9999);
// 保存订单到数据库
$order_table = $wpdb->prefix . 'custom_orders';
$wpdb->insert(
$order_table,
array(
'order_no' => $out_trade_no,
'product_id' => $product_id,
'quantity' => $quantity,
'total_amount' => $total_amount,
'status' => 'pending',
'created_at' => current_time('mysql'),
)
);
// 跳转到支付宝支付
$this->redirect_to_alipay($out_trade_no, $product->name, $total_amount);
}
/**
* 跳转到支付宝支付
*/
private function redirect_to_alipay($out_trade_no, $subject, $total_amount) {
// 支付宝支付参数
$params = array(
'app_id' => $this->alipay_config['app_id'],
'method' => 'alipay.trade.page.pay',
'charset' => $this->alipay_config['charset'],
'sign_type' => $this->alipay_config['sign_type'],
'timestamp' => date('Y-m-d H:i:s'),
'version' => '1.0',
'notify_url' => home_url('/wp-admin/admin-post.php?action=alipay_notify'),
'return_url' => home_url('/custom-payment/payment-success'),
'biz_content' => json_encode(array(
'out_trade_no' => $out_trade_no,
'product_code' => 'FAST_INSTANT_TRADE_PAY',
'total_amount' => $total_amount,
'subject' => $subject,
), JSON_UNESCAPED_UNICODE),
);
// 生成签名
$params['sign'] = $this->generate_signature($params);
// 跳转到支付宝
$gateway_url = $this->alipay_config['gateway_url'] . '?' . http_build_query($params);
wp_redirect($gateway_url);
exit;
}
/**
* 生成支付宝签名
*/
private function generate_signature($params) {
// 按字典序排序参数
ksort($params);
// 拼接待签名字符串
$string_to_be_signed = '';
foreach ($params as $k => $v) {
if ($v && $k != 'sign') {
$string_to_be_signed .= $k . '=' . $v . '&';
}
}
$string_to_be_signed = rtrim($string_to_be_signed, '&');
// 读取私钥文件
$private_key = $this->alipay_config['merchant_private_key'];
// 创建签名
$res = openssl_get_privatekey($private_key);
openssl_sign($string_to_be_signed, $signature, $res, OPENSSL_ALGO_SHA256);
openssl_free_key($res);
// 返回Base64编码的签名
return base64_encode($signature);
}
/**
* 处理支付宝异步通知
*/
public function handle_alipay_notify() {
// 获取支付宝POST数据
$data = $_POST;
// 验证签名
if (!$this->verify_signature($data)) {
echo 'fail';
exit;
}
// 验证交易状态
if ($data['trade_status'] != 'TRADE_SUCCESS') {
echo 'fail';
exit;
}
// 更新订单状态
global $wpdb;
$order_table = $wpdb->prefix . 'custom_orders';
$wpdb->update(
$order_table,
array(
'status' => 'completed',
'transaction_id' => $data['trade_no'],
'paid_at' => current_time('mysql'),
),
array('order_no' => $data['out_trade_no'])
);
// 记录支付日志
$log_table = $wpdb->prefix . 'custom_payment_logs';
$wpdb->insert(
$log_table,
array(
'order_no' => $data['out_trade_no'],
'transaction_id' => $data['trade_no'],
'amount' => $data['total_amount'],
'payment_data' => json_encode($data),
'created_at' => current_time('mysql'),
)
);
echo 'success';
exit;
}
/**
* 验证支付宝签名
*/
private function verify_signature($data) {
$sign = $data['sign'];
unset($data['sign']);
unset($data['sign_type']);
// 按字典序排序参数
ksort($data);
// 拼接待签名字符串
$string_to_be_signed = '';
foreach ($data as $k => $v) {
if ($v) {
$string_to_be_signed .= $k . '=' . $v . '&';
}
}
$string_to_be_signed = rtrim($string_to_be_signed, '&');
// 读取支付宝公钥
$public_key = $this->alipay_config['alipay_public_key'];
// 验证签名
$res = openssl_get_publickey($public_key);
$result = openssl_verify($string_to_be_signed, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
openssl_free_key($res);
return $result === 1;
}
/**
* 支付成功页面
*/
private function payment_success() {
// 获取订单号
$order_no = isset($_GET['out_trade_no']) ? sanitize_text_field($_GET['out_trade_no']) : '';
// 显示成功页面
include CUSTOM_PAYMENT_PLUGIN_DIR . 'templates/payment-success.php';
exit;
}
/**
* 支付失败页面
*/
private function payment_failed() {
include CUSTOM_PAYMENT_PLUGIN_DIR . 'templates/payment-failed.php';
exit;
}
/**
* 注册设置选项
*/
public function register_settings() {
register_setting('custom_payment_settings', 'custom_payment_alipay_app_id');
register_setting('custom_payment_settings', 'custom_payment_alipay_private_key');
register_setting('custom_payment_settings', 'custom_payment_alipay_public_key');
register_setting('custom_payment_settings', 'custom_payment_alipay_gateway');
}
/**
* 添加设置页面
*/
public function add_settings_page() {
add_submenu_page(
'custom-products',
'支付设置',
'支付设置',
'manage_options',
'custom-payment-settings',
array($this, 'render_settings_page')
);
}
/**
* 渲染设置页面
*/
public function render_settings_page() {
?>
<div class="wrap">
<h1>支付接口设置</h1>
<form method="post" action="options.php">
<?php settings_fields('custom_payment_settings'); ?>
<?php do_settings_sections('custom_payment_settings'); ?>
<table class="form-table">
<tr>
<th><label for="alipay_app_id">支付宝App ID</label></th>
<td>
<input type="text" id="alipay_app_id" name="custom_payment_alipay_app_id"
value="<?php echo esc_attr(get_option('custom_payment_alipay_app_id')); ?>"
class="regular-text">
<p class="description">在支付宝开放平台申请的APP ID</p>
</td>
</tr>
<tr>
<th><label for="alipay_private_key">商户私钥</label></th>
<td>
<textarea id="alipay_private_key" name="custom_payment_alipay_private_key"
rows="6" class="large-text"><?php echo esc_textarea(get_option('custom_payment_alipay_private_key')); ?></textarea>
<p class="description">商户私钥,用于生成签名</p>
</td>
</tr>
<tr>
<th><label for="alipay_public_key">支付宝公钥</label></th>
<td>
<textarea id="alipay_public_key" name="custom_payment_alipay_public_key"
rows="6" class="large-text"><?php echo esc_textarea(get_option('custom_payment_alipay_public_key')); ?></textarea>
<p class="description">支付宝公钥,用于验证签名</p>
</td>
</tr>
<tr>
<th><label for="alipay_gateway">网关地址</label></th>
<td>
<input type="text" id="alipay_gateway" name="custom_payment_alipay_gateway"
value="<?php echo esc_attr(get_option('custom_payment_alipay_gateway', 'https://openapi.alipay.com/gateway.do')); ?>"
class="regular-text">
<p class="description">支付宝网关地址,沙箱环境请使用:https://openapi.alipaydev.com/gateway.do</p>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
}
五、前端展示与短代码
5.1 创建短代码类
在includes/class-shortcodes.php文件中添加以下代码:
<?php
/**
* 短代码类
* 提供前端展示功能
*/
class Custom_Payment_Shortcodes {
public function __construct() {
// 注册短代码
add_shortcode('custom_products', array($this, 'render_products_shortcode'));
add_shortcode('custom_payment_form', array($this, 'render_payment_form_shortcode'));
// 注册样式和脚本
add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
}
/**
* 注册前端资源
*/
public function enqueue_assets() {
// 样式文件
wp_enqueue_style(
'custom-payment-style',
CUSTOM_PAYMENT_PLUGIN_URL . 'assets/css/style.css',
array(),
CUSTOM_PAYMENT_VERSION
);
// 脚本文件
wp_enqueue_script(
'custom-payment-script',
CUSTOM_PAYMENT_PLUGIN_URL . 'assets/js/script.js',
array('jquery'),
CUSTOM_PAYMENT_VERSION,
true
);
// 本地化脚本
wp_localize_script('custom-payment-script', 'custom_payment_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('custom_payment_nonce'),
));
}
/**
* 商品列表短代码
*/
public function render_products_shortcode($atts) {
// 解析短代码属性
$atts = shortcode_atts(array(
'category' => '',
'limit' => 10,
), $atts, 'custom_products');
// 获取商品数据
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
$products = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM $table_name WHERE status = 1 ORDER BY id DESC LIMIT %d", $atts['limit'])
);
// 加载模板
ob_start();
include CUSTOM_PAYMENT_PLUGIN_DIR . 'templates/product-list.php';
return ob_get_clean();
}
/**
* 支付表单短代码
*/
public function render_payment_form_shortcode($atts) {
// 解析短代码属性
$atts = shortcode_atts(array(
'product_id' => 0,
), $atts, 'custom_payment_form');
// 获取商品信息
global $wpdb;
$table_name = $wpdb->prefix . 'custom_products';
$product = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM $table_name WHERE id = %d AND status = 1", $atts['product_id'])
);
if (!$product) {
return '<p>商品不存在或已下架</p>';
}
// 加载模板
ob_start();
include CUSTOM_PAYMENT_PLUGIN_DIR . 'templates/payment-form.php';
return ob_get_clean();
}
}
5.2 创建商品列表模板
在templates/product-list.php文件中添加:
<div class="custom-products-list">
<h2>我们的商品</h2>
<?php if ($products): ?>
<div class="products-grid">
<?php foreach ($products as $product): ?>
<div class="product-item">
<h3><?php echo esc_html($product->name); ?></h3>
<p class="product-description"><?php echo esc_html($product->description); ?></p>
<p class="product-price">价格: ¥<?php echo number_format($product->price, 2); ?></p>
<!-- 支付表单 -->
<form method="post" action="<?php echo home_url('/custom-payment/create-order'); ?>" class="payment-form">
<input type="hidden" name="product_id" value="<?php echo $product->id; ?>">
<input type="hidden" name="quantity" value="1" id="quantity_<?php echo $product->id; ?>">
<?php wp_nonce_field('custom_payment_nonce', 'payment_nonce'); ?>
<div class="quantity-selector">
<label for="quantity_input_<?php echo $product->id; ?>">数量:</label>
<input type="number" id="quantity_input_<?php echo $product->id; ?>"
value="1" min="1" max="10"
onchange="document.getElementById('quantity_<?php echo $product->id; ?>').value = this.value;">
</div>
<button type="submit" class="payment-button">立即购买</button>
</form>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<p>暂无商品</p>
<?php endif; ?>
</div>
5.3 创建支付成功模板
在templates/payment-success.php文件中添加:
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>支付成功 - <?php bloginfo('name'); ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="payment-success-container">
<div class="success-message">
<div class="success-icon">✓</div>
<h1>支付成功!</h1>
<p>感谢您的购买,订单已处理完成。</p>
<?php if (!empty($order_no)): ?>
<div class="order-details">
<p><strong>订单号:</strong> <?php echo esc_html($order_no); ?></p>
<p>我们已收到您的付款,相关商品将会尽快处理。</p>
</div>
<?php endif; ?>
<div class="action-buttons">
<a href="<?php echo home_url(); ?>" class="button">返回首页</a>
<a href="<?php echo home_url('/my-account'); ?>" class="button secondary">查看订单</a>
</div>
</div>
</div>
<style>
.payment-success-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.success-message {
background: white;
padding: 40px;
border-radius: 10px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
max-width: 500px;
width: 100%;
}
.success-icon {
font-size: 60px;
color: #4CAF50;
margin-bottom: 20px;
}
.order-details {
background: #f9f9f9;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
text-align: left;
}
.action-buttons {
margin-top: 30px;
}
.button {
display: inline-block;
padding: 12px 30px;
background: #4CAF50;
color: white;
text-decoration: none;
border-radius: 5px;
margin: 0 10px;
transition: background 0.3s;
}
.button:hover {
background: #45a049;
}
.button.secondary {
background: #2196F3;
}
.button.secondary:hover {
background: #1976D2;
}
</style>
<?php wp_footer(); ?>
</body>
</html>
六、数据库表结构
在插件激活时,我们需要创建必要的数据库表。以下是完整的表结构:
-- 商品表
CREATE TABLE wp_custom_products (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
description text,
price decimal(10,2) NOT NULL,
status tinyint(1) DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
-- 订单表
CREATE TABLE wp_custom_orders (
id mediumint(9) NOT NULL AUTO_INCREMENT,
order_no varchar(50) NOT NULL,
product_id mediumint(9) NOT NULL,
quantity int NOT NULL DEFAULT 1,
total_amount decimal(10,2) NOT NULL,
status varchar(20) DEFAULT 'pending',
transaction_id varchar(100),
customer_email varchar(100),
customer_name varchar(100),
created_at datetime DEFAULT CURRENT_TIMESTAMP,
paid_at datetime,
PRIMARY KEY (id),
UNIQUE KEY order_no (order_no)
);
-- 支付日志表
CREATE TABLE wp_custom_payment_logs (
id mediumint(9) NOT NULL AUTO_INCREMENT,
order_no varchar(50) NOT NULL,
transaction_id varchar(100),
amount decimal(10,2) NOT NULL,
payment_data text,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
七、安全注意事项
7.1 输入验证与清理
// 所有用户输入都必须验证和清理
function validate_user_input($input) {
// 清理文本输入
$cleaned = sanitize_text_field($input);
// 验证数字
if (is_numeric($input)) {
$cleaned = intval($input);
}
// 验证邮箱
if (is_email($input)) {
$cleaned = sanitize_email($input);
}
return $cleaned;
}
// 使用nonce防止CSRF攻击
function generate_payment_nonce() {
return wp_create_nonce('custom_payment_nonce');
}
function verify_payment_nonce($nonce) {
return wp_verify_nonce($nonce, 'custom_payment_nonce');
}
7.2 SQL注入防护
// 使用prepare语句防止SQL注入
global $wpdb;
$product_id = intval($_GET['product_id']);
// 正确的方式
$product = $wpdb->get_row(
$wpdb->prepare("SELECT * FROM {$wpdb->prefix}custom_products WHERE id = %d AND status = %d",
$product_id, 1)
);
// 错误的方式(容易导致SQL注入)
$product = $wpdb->get_row("SELECT * FROM {$wpdb->prefix}custom_products WHERE id = $product_id");
八、插件优化与扩展建议
8.1 性能优化
// 使用缓存提高性能
function get_cached_products() {
$cache_key = 'custom_products_list';
