首页 / 教程文章 / WordPress文创数字资产柔性授权与交易插件开发教程

WordPress文创数字资产柔性授权与交易插件开发教程

WordPress文创数字资产柔性授权与交易插件开发教程

一、项目概述与需求分析

在数字文创产业蓬勃发展的今天,创作者需要一个灵活、安全的数字资产授权与交易解决方案。本教程将指导您开发一个WordPress插件,实现数字内容(如电子书、图片、音频等)的柔性授权管理和在线交易功能。

核心功能需求:

  1. 数字资产上传与管理
  2. 多层级授权模式(个人使用、商业使用、独家授权等)
  3. 安全交易与支付集成
  4. 授权证书生成与验证
  5. 销售数据统计与分析

二、插件基础结构搭建

首先,我们创建插件的基本框架:

<?php
/**
 * Plugin Name: 文创数字资产柔性授权与交易系统
 * Plugin URI: https://yourwebsite.com/
 * Description: 为WordPress网站提供数字资产授权管理与交易功能
 * Version: 1.0.0
 * Author: 您的名称
 * License: GPL v2 or later
 */

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

// 定义插件常量
define('DIGITAL_ASSET_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('DIGITAL_ASSET_PLUGIN_URL', plugin_dir_url(__FILE__));
define('DIGITAL_ASSET_VERSION', '1.0.0');

// 初始化插件
class DigitalAssetPlugin {
    
    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_plugin'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin'));
        
        // 初始化
        add_action('init', array($this, 'init_plugin'));
        
        // 管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 加载脚本和样式
        add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }
    
    public function activate_plugin() {
        // 创建必要的数据库表
        $this->create_database_tables();
        
        // 设置默认选项
        $this->set_default_options();
        
        // 刷新重写规则
        flush_rewrite_rules();
    }
    
    public function deactivate_plugin() {
        // 清理临时数据
        flush_rewrite_rules();
    }
    
    public function init_plugin() {
        // 注册自定义文章类型
        $this->register_digital_asset_post_type();
        
        // 注册短代码
        $this->register_shortcodes();
    }
    
    // 其他方法将在后续部分实现
}

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

三、数字资产自定义文章类型

创建专门用于管理数字资产的自定义文章类型:

// 在DigitalAssetPlugin类中添加以下方法

/**
 * 注册数字资产自定义文章类型
 */
public function register_digital_asset_post_type() {
    $labels = array(
        'name'               => '数字资产',
        'singular_name'      => '数字资产',
        'menu_name'          => '数字资产',
        'add_new'            => '添加新资产',
        'add_new_item'       => '添加新数字资产',
        'edit_item'          => '编辑数字资产',
        'new_item'           => '新数字资产',
        'view_item'          => '查看数字资产',
        'search_items'       => '搜索数字资产',
        'not_found'          => '未找到数字资产',
        'not_found_in_trash' => '回收站中无数字资产'
    );
    
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'digital-asset'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 20,
        'menu_icon'          => 'dashicons-media-document',
        'supports'           => array('title', 'editor', 'thumbnail', 'excerpt'),
        'show_in_rest'       => true // 支持Gutenberg编辑器
    );
    
    register_post_type('digital_asset', $args);
    
    // 注册自定义分类法:授权类型
    $this->register_license_taxonomy();
}

/**
 * 注册授权类型分类法
 */
private function register_license_taxonomy() {
    $labels = array(
        'name'              => '授权类型',
        'singular_name'     => '授权类型',
        'search_items'      => '搜索授权类型',
        'all_items'         => '所有授权类型',
        'parent_item'       => '父授权类型',
        'parent_item_colon' => '父授权类型:',
        'edit_item'         => '编辑授权类型',
        'update_item'       => '更新授权类型',
        'add_new_item'      => '添加新授权类型',
        'new_item_name'     => '新授权类型名称',
        'menu_name'         => '授权类型',
    );
    
    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'license-type'),
        'show_in_rest'      => true,
    );
    
    register_taxonomy('license_type', array('digital_asset'), $args);
}

四、资产元数据与授权管理

创建资产元数据框,用于设置价格、授权选项等:

// 在init_hooks方法中添加
add_action('add_meta_boxes', array($this, 'add_digital_asset_metaboxes'));
add_action('save_post_digital_asset', array($this, 'save_digital_asset_metadata'));

/**
 * 添加数字资产元数据框
 */
public function add_digital_asset_metaboxes() {
    add_meta_box(
        'digital_asset_pricing_meta',
        '定价与授权设置',
        array($this, 'render_pricing_metabox'),
        'digital_asset',
        'normal',
        'high'
    );
    
    add_meta_box(
        'digital_asset_file_meta',
        '数字文件管理',
        array($this, 'render_file_metabox'),
        'digital_asset',
        'normal',
        'high'
    );
}

/**
 * 渲染定价元数据框
 */
public function render_pricing_metabox($post) {
    // 添加安全验证
    wp_nonce_field('digital_asset_meta_save', 'digital_asset_meta_nonce');
    
    // 获取现有值
    $base_price = get_post_meta($post->ID, '_digital_asset_base_price', true);
    $personal_price = get_post_meta($post->ID, '_digital_asset_personal_price', true);
    $commercial_price = get_post_meta($post->ID, '_digital_asset_commercial_price', true);
    $exclusive_price = get_post_meta($post->ID, '_digital_asset_exclusive_price', true);
    
    ?>
    <div class="digital-asset-pricing">
        <p>
            <label for="base_price">基础价格 (默认授权):</label>
            <input type="number" step="0.01" min="0" id="base_price" 
                   name="digital_asset_base_price" 
                   value="<?php echo esc_attr($base_price ?: '0.00'); ?>" />
        </p>
        
        <p>
            <label for="personal_price">个人使用授权价格:</label>
            <input type="number" step="0.01" min="0" id="personal_price" 
                   name="digital_asset_personal_price" 
                   value="<?php echo esc_attr($personal_price ?: ''); ?>" />
            <span class="description">留空则使用基础价格</span>
        </p>
        
        <p>
            <label for="commercial_price">商业使用授权价格:</label>
            <input type="number" step="0.01" min="0" id="commercial_price" 
                   name="digital_asset_commercial_price" 
                   value="<?php echo esc_attr($commercial_price ?: ''); ?>" />
        </p>
        
        <p>
            <label for="exclusive_price">独家授权价格:</label>
            <input type="number" step="0.01" min="0" id="exclusive_price" 
                   name="digital_asset_exclusive_price" 
                   value="<?php echo esc_attr($exclusive_price ?: ''); ?>" />
        </p>
        
        <p>
            <label for="max_downloads">最大下载次数:</label>
            <input type="number" min="0" id="max_downloads" 
                   name="digital_asset_max_downloads" 
                   value="<?php echo esc_attr(get_post_meta($post->ID, '_digital_asset_max_downloads', true) ?: '5'); ?>" />
            <span class="description">0表示无限制</span>
        </p>
    </div>
    <?php
}

/**
 * 保存元数据
 */
public function save_digital_asset_metadata($post_id) {
    // 安全检查
    if (!isset($_POST['digital_asset_meta_nonce']) || 
        !wp_verify_nonce($_POST['digital_asset_meta_nonce'], 'digital_asset_meta_save')) {
        return;
    }
    
    // 检查自动保存
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // 检查权限
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // 保存价格数据
    $price_fields = array(
        'digital_asset_base_price',
        'digital_asset_personal_price',
        'digital_asset_commercial_price',
        'digital_asset_exclusive_price',
        'digital_asset_max_downloads'
    );
    
    foreach ($price_fields as $field) {
        if (isset($_POST[$field])) {
            update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
        }
    }
}

五、交易与支付处理系统

创建交易处理类,处理购买和授权流程:

// 创建新文件:includes/class-transaction-handler.php

<?php
class DigitalAssetTransactionHandler {
    
    private $db;
    
    public function __construct() {
        global $wpdb;
        $this->db = $wpdb;
    }
    
    /**
     * 处理购买请求
     * @param int $asset_id 资产ID
     * @param string $license_type 授权类型
     * @param int $user_id 用户ID
     * @return array 处理结果
     */
    public function process_purchase($asset_id, $license_type, $user_id = null) {
        // 验证资产
        $asset = get_post($asset_id);
        if (!$asset || $asset->post_type !== 'digital_asset') {
            return array(
                'success' => false,
                'message' => '无效的数字资产'
            );
        }
        
        // 获取用户ID
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        
        if (!$user_id) {
            return array(
                'success' => false,
                'message' => '请先登录'
            );
        }
        
        // 计算价格
        $price = $this->calculate_price($asset_id, $license_type);
        
        // 创建订单
        $order_id = $this->create_order(array(
            'asset_id' => $asset_id,
            'user_id' => $user_id,
            'license_type' => $license_type,
            'price' => $price,
            'status' => 'pending'
        ));
        
        // 处理支付(这里以模拟支付为例)
        $payment_result = $this->process_payment($order_id, $price);
        
        if ($payment_result['success']) {
            // 更新订单状态
            $this->update_order_status($order_id, 'completed');
            
            // 生成授权证书
            $license_key = $this->generate_license_key($asset_id, $user_id, $license_type);
            
            // 发送下载链接
            $this->send_download_link($user_id, $asset_id, $license_key);
            
            return array(
                'success' => true,
                'order_id' => $order_id,
                'license_key' => $license_key,
                'message' => '购买成功!'
            );
        }
        
        return array(
            'success' => false,
            'message' => '支付失败: ' . $payment_result['message']
        );
    }
    
    /**
     * 计算价格
     */
    private function calculate_price($asset_id, $license_type) {
        $base_price = get_post_meta($asset_id, '_digital_asset_base_price', true);
        
        switch ($license_type) {
            case 'personal':
                $price = get_post_meta($asset_id, '_digital_asset_personal_price', true);
                break;
            case 'commercial':
                $price = get_post_meta($asset_id, '_digital_asset_commercial_price', true);
                break;
            case 'exclusive':
                $price = get_post_meta($asset_id, '_digital_asset_exclusive_price', true);
                break;
            default:
                $price = $base_price;
        }
        
        return $price ?: $base_price;
    }
    
    /**
     * 创建订单
     */
    private function create_order($order_data) {
        $table_name = $this->db->prefix . 'digital_asset_orders';
        
        $this->db->insert($table_name, array(
            'asset_id' => $order_data['asset_id'],
            'user_id' => $order_data['user_id'],
            'license_type' => $order_data['license_type'],
            'price' => $order_data['price'],
            'status' => $order_data['status'],
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ));
        
        return $this->db->insert_id;
    }
    
    /**
     * 生成授权密钥
     */
    private function generate_license_key($asset_id, $user_id, $license_type) {
        $data = $asset_id . $user_id . $license_type . time();
        return 'LIC-' . strtoupper(md5($data));
    }
    
    /**
     * 模拟支付处理
     */
    private function process_payment($order_id, $amount) {
        // 这里应集成真实的支付网关
        // 例如:PayPal、Stripe、支付宝等
        
        // 模拟支付成功
        return array(
            'success' => true,
            'transaction_id' => 'TXN_' . uniqid(),
            'message' => '支付成功'
        );
    }
}
?>

六、前端展示与购买界面

创建短代码,在前端展示数字资产和购买选项:

// 在DigitalAssetPlugin类中添加短代码注册

/**
 * 注册短代码
 */
private function register_shortcodes() {
    add_shortcode('digital_asset_store', array($this, 'render_asset_store'));
    add_shortcode('digital_asset_detail', array($this, 'render_asset_detail'));
}

/**
 * 渲染资产商店
 */
public function render_asset_store($atts) {
    $atts = shortcode_atts(array(
        'category' => '',
        'limit' => 12,
        'columns' => 3
    ), $atts);
    
    // 查询数字资产
    $args = array(
        'post_type' => 'digital_asset',
        'posts_per_page' => intval($atts['limit']),
        'post_status' => 'publish'
    );
    
    if (!empty($atts['category'])) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'license_type',
                'field' => 'slug',
                'terms' => $atts['category']
            )
        );
    }
    
    $assets = new WP_Query($args);
    
    ob_start();
    
    if ($assets->have_posts()) {
        echo '<div class="digital-asset-store columns-' . esc_attr($atts['columns']) . '">';
        
        while ($assets->have_posts()) {
            $assets->the_post();
            $asset_id = get_the_ID();
            $base_price = get_post_meta($asset_id, '_digital_asset_base_price', true);
            ?>
            <div class="digital-asset-item">
                <div class="asset-thumbnail">
                    <?php if (has_post_thumbnail()) : ?>
                        <a href="<?php the_permalink(); ?>">
                            <?php the_post_thumbnail('medium'); ?>
                        </a>
                    <?php endif; ?>
                </div>
                
                <div class="asset-info">
                    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <div class="asset-excerpt"><?php the_excerpt(); ?></div>
                    
                    <div class="asset-pricing">
                        <span class="price">¥<?php echo number_format($base_price, 2); ?></span>
                        <a href="<?php echo add_query_arg('asset_id', $asset_id, get_permalink()); ?>" 
                           class="buy-button">
                            查看详情
                        </a>
                    </div>
                </div>
        <?php
    }
    
    echo '</div>';
    
    // 分页
    if ($assets->max_num_pages > 1) {
        echo '<div class="asset-pagination">';
        echo paginate_links(array(
            'total' => $assets->max_num_pages,
            'current' => max(1, get_query_var('paged'))
        ));
        echo '</div>';
    }
    
    wp_reset_postdata();
} else {
    echo '<p>暂无数字资产</p>';
}

return ob_get_clean();

}

/**

  • 渲染资产详情页
    */

public function render_asset_detail($atts) {

$asset_id = isset($_GET['asset_id']) ? intval($_GET['asset_id']) : get_the_ID();

if (!$asset_id || get_post_type($asset_id) !== 'digital_asset') {
    return '<p>无效的数字资产</p>';
}

$asset = get_post($asset_id);
$base_price = get_post_meta($asset_id, '_digital_asset_base_price', true);
$personal_price = get_post_meta($asset_id, '_digital_asset_personal_price', true);
$commercial_price = get_post_meta($asset_id, '_digital_asset_commercial_price', true);
$exclusive_price = get_post_meta($asset_id, '_digital_asset_exclusive_price', true);

ob_start();
?>
<div class="digital-asset-detail">
    <div class="asset-header">
        <h1><?php echo esc_html($asset->post_title); ?></h1>
        <div class="asset-meta">
            <span class="author">作者: <?php echo get_the_author_meta('display_name', $asset->post_author); ?></span>
            <span class="date">发布时间: <?php echo get_the_date('', $asset); ?></span>
        </div>
    </div>
    
    <div class="asset-content">
        <div class="asset-image">
            <?php if (has_post_thumbnail($asset_id)) : ?>
                <?php echo get_the_post_thumbnail($asset_id, 'large'); ?>
            <?php endif; ?>
        </div>
        
        <div class="asset-description">
            <?php echo apply_filters('the_content', $asset->post_content); ?>
        </div>
    </div>
    
    <div class="asset-licensing">
        <h3>选择授权类型</h3>
        
        <form id="digital-asset-purchase-form" method="post">
            <?php wp_nonce_field('digital_asset_purchase', 'purchase_nonce'); ?>
            <input type="hidden" name="asset_id" value="<?php echo $asset_id; ?>">
            
            <div class="license-options">
                <div class="license-option">
                    <input type="radio" id="license_personal" name="license_type" value="personal" checked>
                    <label for="license_personal">
                        <h4>个人使用授权</h4>
                        <p>仅限个人非商业用途</p>
                        <div class="license-price">
                            ¥<?php echo number_format($personal_price ?: $base_price, 2); ?>
                        </div>
                    </label>
                </div>
                
                <div class="license-option">
                    <input type="radio" id="license_commercial" name="license_type" value="commercial">
                    <label for="license_commercial">
                        <h4>商业使用授权</h4>
                        <p>可用于商业项目</p>
                        <div class="license-price">
                            ¥<?php echo number_format($commercial_price ?: $base_price * 2, 2); ?>
                        </div>
                    </label>
                </div>
                
                <div class="license-option">
                    <input type="radio" id="license_exclusive" name="license_type" value="exclusive">
                    <label for="license_exclusive">
                        <h4>独家授权</h4>
                        <p>获得独家使用权</p>
                        <div class="license-price">
                            ¥<?php echo number_format($exclusive_price ?: $base_price * 5, 2); ?>
                        </div>
                    </label>
                </div>
            </div>
            
            <div class="purchase-action">
                <button type="submit" class="purchase-button">
                    立即购买
                </button>
                <div class="license-terms">
                    <input type="checkbox" id="agree_terms" required>
                    <label for="agree_terms">我已阅读并同意<a href="#">授权协议</a></label>
                </div>
            </div>
        </form>
    </div>
    
    <div class="asset-specs">
        <h3>技术规格</h3>
        <ul>
            <li>文件格式: <?php echo esc_html(get_post_meta($asset_id, '_file_format', true) ?: '多种格式'); ?></li>
            <li>分辨率: <?php echo esc_html(get_post_meta($asset_id, '_resolution', true) ?: '可定制'); ?></li>
            <li>最大下载次数: <?php echo esc_html(get_post_meta($asset_id, '_digital_asset_max_downloads', true) ?: '5'); ?></li>
        </ul>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    $('#digital-asset-purchase-form').on('submit', function(e) {
        e.preventDefault();
        
        if (!$('#agree_terms').is(':checked')) {
            alert('请先同意授权协议');
            return;
        }
        
        var formData = $(this).serialize();
        
        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'POST',
            data: formData + '&action=process_digital_asset_purchase',
            beforeSend: function() {
                $('.purchase-button').prop('disabled', true).text('处理中...');
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.redirect_url;
                } else {
                    alert(response.message);
                    $('.purchase-button').prop('disabled', false).text('立即购买');
                }
            },
            error: function() {
                alert('请求失败,请重试');
                $('.purchase-button').prop('disabled', false).text('立即购买');
            }
        });
    });
});
</script>
<?php

return ob_get_clean();

}


## 七、AJAX处理与数据库操作

创建AJAX处理函数和数据库表结构:

// 在DigitalAssetPlugin类中添加AJAX处理

/**

  • 初始化AJAX处理
    */

private function init_ajax_handlers() {

add_action('wp_ajax_process_digital_asset_purchase', array($this, 'ajax_process_purchase'));
add_action('wp_ajax_nopriv_process_digital_asset_purchase', array($this, 'ajax_process_purchase'));

add_action('wp_ajax_generate_license_certificate', array($this, 'ajax_generate_certificate'));
add_action('wp_ajax_download_digital_asset', array($this, 'ajax_download_asset'));

}

/**

  • 创建数据库表
    */

private function create_database_tables() {

global $wpdb;

$charset_collate = $wpdb->get_charset_collate();
$table_prefix = $wpdb->prefix;

// 订单表
$orders_table = $table_prefix . 'digital_asset_orders';
$orders_sql = "CREATE TABLE IF NOT EXISTS $orders_table (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    asset_id bigint(20) NOT NULL,
    user_id bigint(20) NOT NULL,
    license_type varchar(50) NOT NULL,
    price decimal(10,2) NOT NULL,
    license_key varchar(100) NOT NULL,
    transaction_id varchar(100),
    status varchar(20) DEFAULT 'pending',
    download_count int(11) DEFAULT 0,
    max_downloads int(11) DEFAULT 5,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY asset_id (asset_id),
    KEY user_id (user_id),
    KEY license_key (license_key)
) $charset_collate;";

// 授权证书表
$licenses_table = $table_prefix . 'digital_asset_licenses';
$licenses_sql = "CREATE TABLE IF NOT EXISTS $licenses_table (
    id bigint(20) NOT NULL AUTO_INCREMENT,
    order_id bigint(20) NOT NULL,
    license_key varchar(100) NOT NULL,
    asset_id bigint(20) NOT NULL,
    user_id bigint(20) NOT NULL,
    license_type varchar(50) NOT NULL,
    valid_from date NOT NULL,
    valid_to date,
    is_active tinyint(1) DEFAULT 1,
    terms text,
    certificate_data longtext,
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY license_key (license_key),
    KEY order_id (order_id),
    KEY asset_id (asset_id),
    KEY user_id (user_id)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($orders_sql);
dbDelta($licenses_sql);

}

/**

  • AJAX处理购买请求
    */

public function ajax_process_purchase() {

// 验证nonce
if (!isset($_POST['purchase_nonce']) || 
    !wp_verify_nonce($_POST['purchase_nonce'], 'digital_asset_purchase')) {
    wp_send_json_error('安全验证失败');
}

// 验证用户
if (!is_user_logged_in()) {
    wp_send_json_error('请先登录');
}

$asset_id = intval($_POST['asset_id']);
$license_type = sanitize_text_field($_POST['license_type']);
$user_id = get_current_user_id();

// 实例化交易处理器
require_once DIGITAL_ASSET_PLUGIN_PATH . 'includes/class-transaction-handler.php';
$transaction_handler = new DigitalAssetTransactionHandler();

$result = $transaction_handler->process_purchase($asset_id, $license_type, $user_id);

if ($result['success']) {
    // 创建订单成功页面URL
    $order_page_id = get_option('digital_asset_order_page');
    $redirect_url = add_query_arg(array(
        'order_id' => $result['order_id'],
        'license_key' => $result['license_key']
    ), get_permalink($order_page_id));
    
    wp_send_json_success(array(
        'message' => $result['message'],
        'redirect_url' => $redirect_url
    ));
} else {
    wp_send_json_error($result['message']);
}

}

/**

  • 生成授权证书
    */

public function ajax_generate_certificate() {

$license_key = sanitize_text_field($_POST['license_key']);

global $wpdb;
$table_name = $wpdb->prefix . 'digital_asset_licenses';

$license = $wpdb->get_row($wpdb->prepare(
    "SELECT * FROM $table_name WHERE license_key = %s",
    $license_key
));

if (!$license) {
    wp_send_json_error('无效的授权密钥');
}

// 生成PDF证书
$certificate_data = $this->generate_pdf_certificate($license);

wp_send_json_success(array(
    'certificate' => $certificate_data,
    'download_url' => add_query_arg(array(
        'action' => 'download_certificate',
        'license_key' => $license_key,
        'nonce' => wp_create_nonce('download_certificate_' . $license_key)
    ), admin_url('admin-ajax.php'))
));

}

/**

  • 生成PDF证书
    */

private function generate_pdf_certificate($license) {

// 这里应该集成PDF生成库,如TCPDF或mPDF
// 由于篇幅限制,这里返回HTML格式的证书

$asset = get_post($license->asset_id);
$user = get_userdata($license->user_id);

$html = '
<div class="license-certificate">
    <div class="certificate-header">
        <h1>数字资产授权证书</h1>
        <div class="certificate-id">证书编号: ' . $license->license_key . '</div>
    </div>
    
    <div class="certificate-body">
        <p>兹证明 <strong>' . esc_html($user->display_name) . '</strong> 已获得以下数字资产的合法授权:</p>
        
        <div class="asset-info">
            <h3>' . esc_html($asset->post_title) . '</h3>
            <p>授权类型: ' . $this->get_license_type_name($license->license_type) . '</p>
            <p>授权期限: ' . date('Y年m月d日', strtotime($license->valid_from)) . ' 至 ' . 
               ($license->valid_to ? date('Y年m月d日', strtotime($license->valid_to)) : '永久') . '</p>
        </div>
        
        <div class="license-terms">
            <h4>授权条款</h4>
            <p>' . nl2br(esc_html($license->terms)) . '</p>
        </div>
        
        <div class="signatures">
            <div class="issuer-signature">
                <p>发行方: ' . get_bloginfo('name') . '</p>
                <p>签发日期: ' . date('Y年m月d日') . '</p>
            </div>
        </div>
    </div>
    
    <div class="certificate-footer">
        <p>验证地址: ' . home_url('/verify-license?key=' . $license->license_key) . '</p>
    </div>
</div>';

return $html;

}


## 八、安全与验证系统

实现授权验证和下载保护:

/**

  • 验证授权密钥
    */

public function verify_license_key($license_key, $asset_id = null) {

global $wpdb;
$table_name = $wpdb->prefix . 'digital_asset_licenses';

$query = "SELECT * FROM $table_name WHERE license_key = %s AND is_active = 1";
$params = array($license_key);

if ($asset_id) {
    $query .= " AND asset_id = %d";
    $params[] = $asset_id;
}

$license = $wpdb->get_row($wpdb->prepare($query, $params));

if (!$license) {
    return false;
}

// 检查有效期
if ($license->valid_to && strtotime($license->valid_to) < current_time('timestamp')) {
    return false;
}

return $license;

}

/**

  • 安全下载文件
    */

public function secure_file_download($file_path, $license_key) {

// 验证授权
$license = $this->verify_license_key($license_key);
if (!$license) {
    wp_die('无效的授权或授权已过期');
}

// 检查下载次数限制
if ($license->max_downloads > 0 && $license->download_count >= $license->max_downloads) {
    wp_die('已达到最大下载次数');
}

// 更新下载计数
$this->increment_download_count($license->id);

// 发送文件
if (file_exists($file_path)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file_path));
    readfile($file_path);
    exit;
} else {
    wp_die('文件不存在');
}

}

/**

  • 增加下载计数
    */

private function increment_download_count($license_id) {

global $wpdb;
$table_name = $wpdb->prefix . 'digital_asset_licenses';

$wpdb->query($wpdb->prepare(
    "UPDATE $table_name SET download_count = download_count + 1 WHERE id = %d",
    $license_id
));

}

/**

  • 添加水印(针对图片资产)
    */

public function add_watermark_to_image($image_path, $license_key) {

// 获取授权信息
$license = $this->verify_license_key($license_key);

if (!$license || $license->license_type === 'personal') {
    // 个人授权添加水印
    $watermark_text = "个人使用授权 - " . $license_key;
    
    // 使用GD库添加水印
    $image = imagecreatefromstring(file_get_contents($image_path));
    $text_color = imagecolorallocatealpha($image, 255, 255, 255, 60);
    $font_size = 20;
    
    // 计算文字位置
    $text_box = imagettfbbox($font_size, 0, $this->get_font_path(), $watermark_text);
    $text_width = $text_box[2] - $text_box[0];
    $text_height = $text_box[7] - $text_box[1];
    
    $x = (imagesx($image) - $text_width) / 2;
    $y = (imagesy($image) - $text_height) / 2;
    
    // 添加文字水印
    imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->get_font_path(), $watermark_text);
    
    // 输出图像
    imagepng($image, $image_path . '_watermarked');
    imagedestroy($image);
    
    return $image_path . '_watermarked';
}

return $image_path;

}

本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6184.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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