首页 / 教程文章 / WordPress柔性供应链中的区块链存证应用开发教程

WordPress柔性供应链中的区块链存证应用开发教程

WordPress柔性供应链中的区块链存证应用开发教程

引言:供应链数字化的新趋势

随着全球供应链日益复杂,企业面临着产品溯源、防伪验证和透明度提升等挑战。传统供应链管理系统存在数据孤岛、信息篡改风险等问题。区块链技术以其去中心化、不可篡改和可追溯的特性,为供应链管理带来了革命性的解决方案。

本教程将指导您如何在WordPress环境中开发一个基于区块链的供应链存证应用,实现产品从原材料到终端消费者的全流程可信记录。

一、环境准备与基础配置

1.1 系统要求

  • WordPress 5.8+ 版本
  • PHP 7.4+ 版本
  • MySQL 5.7+ 或 MariaDB 10.3+
  • 以太坊测试网络访问权限(如Rinkeby或Goerli)
  • Web3.js库支持

1.2 安装必要插件

在WordPress后台安装以下插件:

  • Advanced Custom Fields(自定义字段管理)
  • Web3 Integration for WordPress(区块链连接)
  • REST API启用(WordPress默认包含)

1.3 区块链环境配置

// 在主题的functions.php中添加区块链配置
add_action('admin_init', 'setup_blockchain_config');

function setup_blockchain_config() {
    // 以太坊测试网络节点地址
    $eth_node_url = 'https://rinkeby.infura.io/v3/YOUR_INFURA_PROJECT_ID';
    
    // 智能合约地址(部署后更新)
    $contract_address = '0xYourContractAddressHere';
    
    // 存储配置到WordPress选项
    update_option('supply_chain_eth_node', $eth_node_url);
    update_option('supply_chain_contract_address', $contract_address);
    
    // 添加管理员配置页面
    add_menu_page(
        '区块链配置',
        '供应链区块链',
        'manage_options',
        'supply-chain-blockchain',
        'blockchain_config_page'
    );
}

function blockchain_config_page() {
    ?>
    <div class="wrap">
        <h1>供应链区块链配置</h1>
        <form method="post" action="options.php">
            <?php settings_fields('blockchain-settings-group'); ?>
            <table class="form-table">
                <tr>
                    <th>以太坊节点URL</th>
                    <td>
                        <input type="text" name="eth_node_url" value="<?php echo get_option('supply_chain_eth_node'); ?>" class="regular-text" />
                    </td>
                </tr>
                <tr>
                    <th>智能合约地址</th>
                    <td>
                        <input type="text" name="contract_address" value="<?php echo get_option('supply_chain_contract_address'); ?>" class="regular-text" />
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

二、智能合约开发与部署

2.1 供应链存证智能合约

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title SupplyChainVerification
 * @dev 供应链产品存证智能合约
 */
contract SupplyChainVerification {
    
    // 产品结构体
    struct Product {
        uint256 productId;
        string productName;
        address manufacturer;
        uint256 manufactureDate;
        string rawMaterialHash;
        string qualityInspectionHash;
        address[] supplyChainParticipants;
        mapping(uint256 => Transaction) transactions;
        uint256 transactionCount;
    }
    
    // 交易记录结构体
    struct Transaction {
        uint256 timestamp;
        address from;
        address to;
        string location;
        string conditionHash;
        string metadata;
    }
    
    // 事件定义
    event ProductCreated(uint256 indexed productId, address indexed manufacturer);
    event TransactionRecorded(uint256 indexed productId, uint256 indexed transactionId, address from, address to);
    
    // 产品ID到产品的映射
    mapping(uint256 => Product) private products;
    uint256 private productCounter;
    
    /**
     * @dev 创建新产品记录
     * @param _productName 产品名称
     * @param _rawMaterialHash 原材料哈希(IPFS或文件哈希)
     * @param _qualityInspectionHash 质检报告哈希
     */
    function createProduct(
        string memory _productName,
        string memory _rawMaterialHash,
        string memory _qualityInspectionHash
    ) public returns (uint256) {
        productCounter++;
        
        Product storage newProduct = products[productCounter];
        newProduct.productId = productCounter;
        newProduct.productName = _productName;
        newProduct.manufacturer = msg.sender;
        newProduct.manufactureDate = block.timestamp;
        newProduct.rawMaterialHash = _rawMaterialHash;
        newProduct.qualityInspectionHash = _qualityInspectionHash;
        newProduct.supplyChainParticipants.push(msg.sender);
        newProduct.transactionCount = 0;
        
        emit ProductCreated(productCounter, msg.sender);
        
        return productCounter;
    }
    
    /**
     * @dev 记录供应链交易
     * @param _productId 产品ID
     * @param _to 接收方地址
     * @param _location 交易地点
     * @param _conditionHash 产品状态哈希
     * @param _metadata 额外元数据
     */
    function recordTransaction(
        uint256 _productId,
        address _to,
        string memory _location,
        string memory _conditionHash,
        string memory _metadata
    ) public {
        require(_productId <= productCounter && _productId > 0, "产品不存在");
        require(products[_productId].manufacturer != address(0), "产品不存在");
        
        Product storage product = products[_productId];
        
        // 验证发送方是当前持有者
        if (product.transactionCount > 0) {
            uint256 lastTransactionId = product.transactionCount;
            require(product.transactions[lastTransactionId].to == msg.sender, "无权转移此产品");
        } else {
            require(product.manufacturer == msg.sender, "只有制造商可以发起首次交易");
        }
        
        uint256 transactionId = product.transactionCount + 1;
        
        product.transactions[transactionId] = Transaction({
            timestamp: block.timestamp,
            from: msg.sender,
            to: _to,
            location: _location,
            conditionHash: _conditionHash,
            metadata: _metadata
        });
        
        product.transactionCount = transactionId;
        
        // 添加新的参与者到列表
        bool participantExists = false;
        for (uint i = 0; i < product.supplyChainParticipants.length; i++) {
            if (product.supplyChainParticipants[i] == _to) {
                participantExists = true;
                break;
            }
        }
        
        if (!participantExists) {
            product.supplyChainParticipants.push(_to);
        }
        
        emit TransactionRecorded(_productId, transactionId, msg.sender, _to);
    }
    
    /**
     * @dev 获取产品信息
     * @param _productId 产品ID
     */
    function getProductInfo(uint256 _productId) public view returns (
        uint256 productId,
        string memory productName,
        address manufacturer,
        uint256 manufactureDate,
        string memory rawMaterialHash,
        string memory qualityInspectionHash,
        uint256 transactionCount
    ) {
        require(_productId <= productCounter && _productId > 0, "产品不存在");
        
        Product storage product = products[_productId];
        
        return (
            product.productId,
            product.productName,
            product.manufacturer,
            product.manufactureDate,
            product.rawMaterialHash,
            product.qualityInspectionHash,
            product.transactionCount
        );
    }
    
    /**
     * @dev 获取交易详情
     * @param _productId 产品ID
     * @param _transactionId 交易ID
     */
    function getTransactionInfo(uint256 _productId, uint256 _transactionId) public view returns (
        uint256 timestamp,
        address from,
        address to,
        string memory location,
        string memory conditionHash,
        string memory metadata
    ) {
        require(_productId <= productCounter && _productId > 0, "产品不存在");
        require(_transactionId <= products[_productId].transactionCount && _transactionId > 0, "交易不存在");
        
        Transaction storage transaction = products[_productId].transactions[_transactionId];
        
        return (
            transaction.timestamp,
            transaction.from,
            transaction.to,
            transaction.location,
            transaction.conditionHash,
            transaction.metadata
        );
    }
}

2.2 合约部署脚本

// deploy.js - 使用Hardhat部署合约
const hre = require("hardhat");

async function main() {
  // 获取合约工厂
  const SupplyChainVerification = await hre.ethers.getContractFactory("SupplyChainVerification");
  
  // 部署合约
  console.log("正在部署供应链存证合约...");
  const supplyChain = await SupplyChainVerification.deploy();
  await supplyChain.deployed();
  
  console.log("合约部署成功!地址:", supplyChain.address);
  
  // 验证合约(如果使用Etherscan)
  if (hre.network.name !== "hardhat") {
    console.log("等待区块确认...");
    await supplyChain.deployTransaction.wait(6);
    
    console.log("正在验证合约...");
    await hre.run("verify:verify", {
      address: supplyChain.address,
      constructorArguments: [],
    });
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

三、WordPress后端集成

3.1 自定义文章类型与字段

// 注册供应链产品自定义文章类型
add_action('init', 'register_supply_chain_product_cpt');

function register_supply_chain_product_cpt() {
    $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,
        'has_archive' => true,
        'menu_icon' => 'dashicons-products',
        'supports' => array('title', 'editor', 'thumbnail'),
        'show_in_rest' => true,
        'capability_type' => 'post',
    );
    
    register_post_type('supply_chain_product', $args);
}

// 使用ACF添加自定义字段
add_action('acf/init', 'register_supply_chain_fields');

function register_supply_chain_fields() {
    if (function_exists('acf_add_local_field_group')) {
        acf_add_local_field_group(array(
            'key' => 'group_supply_chain_product',
            'title' => '产品区块链信息',
            'fields' => array(
                array(
                    'key' => 'field_product_id',
                    'label' => '区块链产品ID',
                    'name' => 'blockchain_product_id',
                    'type' => 'number',
                    'instructions' => '区块链上存储的产品唯一标识',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_raw_material_hash',
                    'label' => '原材料哈希',
                    'name' => 'raw_material_hash',
                    'type' => 'text',
                    'instructions' => '原材料证明文件的哈希值',
                ),
                array(
                    'key' => 'field_quality_inspection',
                    'label' => '质检报告哈希',
                    'name' => 'quality_inspection_hash',
                    'type' => 'text',
                    'instructions' => '质量检验报告的哈希值',
                ),
                array(
                    'key' => 'field_manufacturer_address',
                    'label' => '制造商区块链地址',
                    'name' => 'manufacturer_address',
                    'type' => 'text',
                    'instructions' => '制造商的以太坊钱包地址',
                ),
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'supply_chain_product',
                    ),
                ),
            ),
        ));
    }
}

3.2 区块链交互类

// 区块链交互处理类
class BlockchainHandler {
    private $web3;
    private $contract;
    private $contract_address;
    
    public function __construct() {
        // 初始化Web3连接
        $this->init_web3();
    }
    
    private function init_web3() {
        // 从WordPress选项获取配置
        $node_url = get_option('supply_chain_eth_node');
        $this->contract_address = get_option('supply_chain_contract_address');
        
        // 这里需要集成Web3.php库
        // 实际项目中需要包含Web3.php库文件
        // $this->web3 = new Web3Web3(new Web3ProvidersHttpProvider($node_url));
        
        // 由于WordPress环境限制,这里使用模拟数据
        // 实际部署时需要正确配置Web3库
    }
    
    /**
     * 注册新产品到区块链
     */
    public function register_product($product_data) {
        $product_id = $product_data['product_id'];
        $product_name = $product_data['product_name'];
        $raw_material_hash = $product_data['raw_material_hash'];
        $quality_hash = $product_data['quality_inspection_hash'];
        
        // 这里应该是实际的智能合约调用
        // 示例:$tx_hash = $this->contract->send('createProduct', [$product_name, $raw_material_hash, $quality_hash]);
        
        // 模拟返回交易哈希
        $tx_hash = '0x' . bin2hex(random_bytes(32));
        
        // 记录到WordPress数据库
        update_post_meta($product_id, 'blockchain_tx_hash', $tx_hash);
        update_post_meta($product_id, 'blockchain_status', 'pending');
        
        return array(
            'success' => true,
            'tx_hash' => $tx_hash,
            'message' => '产品已提交到区块链网络'
        );
    }
    
    /**
     * 验证产品信息
     */
    public function verify_product($product_id) {
        // 从区块链获取产品信息
        // 示例:$product_info = $this->contract->call('getProductInfo', [$product_id]);
        
        // 模拟区块链返回数据
        $product_info = array(
            'productId' => $product_id,
            'productName' => get_the_title($product_id),
            'manufacturer' => get_post_meta($product_id, 'manufacturer_address', true),
            'manufactureDate' => time() - 86400 * 30, // 30天前
            'rawMaterialHash' => get_post_meta($product_id, 'raw_material_hash', true),
            'transactionCount' => 3
        );
        
        return $product_info;
    }
    
    /**
     * 记录供应链交易
     */
    public function record_transaction($transaction_data) {
        $product_id = $transaction_data['product_id'];
        $to_address = $transaction_data['to_address'];
        $location = $transaction_data['location'];
        $condition_hash = $transaction_data['condition_hash'];
        
        // 模拟区块链交易
        $tx_hash = '0x' . bin2hex(random_bytes(32));
        
        // 记录交易到数据库
        $transactions = get_post_meta($product_id, 'supply_chain_transactions', true);
        if (!is_array($transactions)) {
            $transactions = array();
        }
        
        $new_transaction = array(
            'timestamp' => current_time('timestamp'),
            'from' => $transaction_data['from_address'],
            'to' => $to_address,
            'location' => $location,
            'condition_hash' => $condition_hash,
            'tx_hash' => $tx_hash
        );
        
        $transactions[] = $new_transaction;
        update_post_meta($product_id, 'supply_chain_transactions', $transactions);
        
        return array(
            'success' => true,
            'tx_hash' => $tx_hash
        );
    }
}

四、前端用户界面开发

4.1 产品注册表单

// 短代码:产品注册表单
add_shortcode('product_registration_form', 'render_product_registration_form');

function render_product_registration_form() {
    ob_start();
    
    // 处理表单提交
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_product'])) {
        $result = handle_product_registration($_POST);
        if ($result['success']) {
            echo '<div class="notice notice-success"><p>' . $result['message'] . '</p></div>';
        } else {
            echo '<div class="notice notice-error"><p>' . $result['message'] . '</p></div>';
        }
    }
    ?>
    
    <div class="supply-chain-form">
        <h2>新产品区块链注册</h2>
        <form method="post" action="">
            <?php wp_nonce_field('register_product_action', 'product_nonce'); ?>
            
            <div class="form-group">
                <label for="product_name">产品名称 *</label>
                <input type="text" id="product_name" name="product_name" required class="regular-text">
            </div>
            
            <div class="form-group">
                <label for="product_description">产品描述</label>
                <textarea id="product_description" name="product_description" rows="4" class="large-text"></textarea>
            </div>
            
            <div class="form-group">
                <label for="raw_material_hash">原材料证明文件哈希 *</label>
                <input type="text" id="raw_material_hash" name="raw_material_hash" required class="regular-text">

文件后生成的哈希值</p>

        </div>
        
        <div class="form-group">
            <label for="quality_inspection_hash">质检报告哈希 *</label>
            <input type="text" id="quality_inspection_hash" name="quality_inspection_hash" required class="regular-text">
            <p class="description">上传质检报告后生成的哈希值</p>
        </div>
        
        <div class="form-group">
            <label for="manufacturer_address">制造商区块链地址 *</label>
            <input type="text" id="manufacturer_address" name="manufacturer_address" required class="regular-text">
            <p class="description">您的以太坊钱包地址(0x开头)</p>
        </div>
        
        <input type="submit" name="register_product" value="注册到区块链" class="button button-primary">
    </form>
</div>

<style>
.supply-chain-form {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    background: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}
.form-group input,
.form-group textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
.form-group .description {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}
</style>

<?php
return ob_get_clean();

}

function handle_product_registration($data) {

// 验证nonce
if (!wp_verify_nonce($data['product_nonce'], 'register_product_action')) {
    return array('success' => false, 'message' => '安全验证失败');
}

// 创建产品文章
$post_data = array(
    'post_title'   => sanitize_text_field($data['product_name']),
    'post_content' => sanitize_textarea_field($data['product_description']),
    'post_type'    => 'supply_chain_product',
    'post_status'  => 'publish'
);

$post_id = wp_insert_post($post_data);

if (is_wp_error($post_id)) {
    return array('success' => false, 'message' => '创建产品失败:' . $post_id->get_error_message());
}

// 保存自定义字段
update_post_meta($post_id, 'raw_material_hash', sanitize_text_field($data['raw_material_hash']));
update_post_meta($post_id, 'quality_inspection_hash', sanitize_text_field($data['quality_inspection_hash']));
update_post_meta($post_id, 'manufacturer_address', sanitize_text_field($data['manufacturer_address']));

// 调用区块链注册
$blockchain = new BlockchainHandler();
$blockchain_data = array(
    'product_id' => $post_id,
    'product_name' => sanitize_text_field($data['product_name']),
    'raw_material_hash' => sanitize_text_field($data['raw_material_hash']),
    'quality_inspection_hash' => sanitize_text_field($data['quality_inspection_hash'])
);

$result = $blockchain->register_product($blockchain_data);

if ($result['success']) {
    return array(
        'success' => true,
        'message' => '产品已成功注册!交易哈希:' . $result['tx_hash']
    );
} else {
    return array(
        'success' => false,
        'message' => '区块链注册失败:' . $result['message']
    );
}

}


### 4.2 产品溯源查询界面

// 短代码:产品溯源查询
add_shortcode('product_traceability', 'render_product_traceability');

function render_product_traceability() {

ob_start();

$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;
$verification_result = null;

if ($product_id > 0) {
    $blockchain = new BlockchainHandler();
    $verification_result = $blockchain->verify_product($product_id);
}
?>

<div class="traceability-container">
    <h2>产品区块链溯源查询</h2>
    
    <div class="search-form">
        <form method="get" action="">
            <input type="text" name="product_id" placeholder="输入产品ID或扫描二维码" value="<?php echo esc_attr($product_id); ?>" required>
            <input type="submit" value="查询" class="button button-primary">
        </form>
    </div>
    
    <?php if ($verification_result): ?>
    <div class="verification-result">
        <h3>产品验证结果</h3>
        
        <div class="product-info">
            <h4>基本信息</h4>
            <table class="wp-list-table widefat fixed striped">
                <tr>
                    <th width="30%">产品ID</th>
                    <td><?php echo esc_html($verification_result['productId']); ?></td>
                </tr>
                <tr>
                    <th>产品名称</th>
                    <td><?php echo esc_html($verification_result['productName']); ?></td>
                </tr>
                <tr>
                    <th>制造商地址</th>
                    <td><code><?php echo esc_html($verification_result['manufacturer']); ?></code></td>
                </tr>
                <tr>
                    <th>生产日期</th>
                    <td><?php echo date('Y-m-d H:i:s', $verification_result['manufactureDate']); ?></td>
                </tr>
                <tr>
                    <th>原材料哈希</th>
                    <td><code><?php echo esc_html($verification_result['rawMaterialHash']); ?></code></td>
                </tr>
                <tr>
                    <th>交易次数</th>
                    <td><?php echo esc_html($verification_result['transactionCount']); ?> 次</td>
                </tr>
            </table>
        </div>
        
        <div class="supply-chain-timeline">
            <h4>供应链流转记录</h4>
            <?php
            $transactions = get_post_meta($product_id, 'supply_chain_transactions', true);
            if (is_array($transactions) && !empty($transactions)):
            ?>
            <div class="timeline">
                <?php foreach ($transactions as $index => $transaction): ?>
                <div class="timeline-item <?php echo $index % 2 == 0 ? 'left' : 'right'; ?>">
                    <div class="timeline-content">
                        <div class="timeline-header">
                            <span class="step">步骤 <?php echo $index + 1; ?></span>
                            <span class="date"><?php echo date('Y-m-d H:i:s', $transaction['timestamp']); ?></span>
                        </div>
                        <div class="timeline-body">
                            <p><strong>从:</strong> <code><?php echo esc_html($transaction['from']); ?></code></p>
                            <p><strong>到:</strong> <code><?php echo esc_html($transaction['to']); ?></code></p>
                            <p><strong>地点:</strong> <?php echo esc_html($transaction['location']); ?></p>
                            <p><strong>状态哈希:</strong> <code><?php echo esc_html($transaction['condition_hash']); ?></code></p>
                            <p><strong>交易哈希:</strong> <code><?php echo esc_html($transaction['tx_hash']); ?></code></p>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p>暂无流转记录</p>
            <?php endif; ?>
        </div>
        
        <div class="verification-status">
            <div class="status-badge verified">
                <span class="dashicons dashicons-yes-alt"></span>
                <span>区块链验证通过</span>
            </div>
            <p class="verification-note">
                此产品的所有信息已记录在以太坊区块链上,数据不可篡改,可追溯。
            </p>
        </div>
    </div>
    <?php elseif ($product_id > 0): ?>
    <div class="notice notice-error">
        <p>未找到产品ID为 <?php echo esc_html($product_id); ?> 的区块链记录</p>
    </div>
    <?php endif; ?>
</div>

<style>
.traceability-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}
.search-form {
    margin: 30px 0;
    text-align: center;
}
.search-form input[type="text"] {
    width: 300px;
    padding: 10px;
    font-size: 16px;
    margin-right: 10px;
}
.verification-result {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    margin-top: 20px;
}
.timeline {
    position: relative;
    padding: 20px 0;
}
.timeline::before {
    content: '';
    position: absolute;
    left: 50%;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #0073aa;
    transform: translateX(-50%);
}
.timeline-item {
    position: relative;
    margin-bottom: 30px;
    width: 45%;
}
.timeline-item.left {
    float: left;
    clear: left;
    text-align: right;
    padding-right: 30px;
}
.timeline-item.right {
    float: right;
    clear: right;
    padding-left: 30px;
}
.timeline-content {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 15px;
    position: relative;
}
.timeline-item.left .timeline-content::after {
    content: '';
    position: absolute;
    right: -10px;
    top: 20px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #dee2e6;
}
.timeline-item.right .timeline-content::after {
    content: '';
    position: absolute;
    left: -10px;
    top: 20px;
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #dee2e6;
}
.timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #dee2e6;
}
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 8px 15px;
    border-radius: 20px;
    font-weight: bold;
    margin: 20px 0;
}
.status-badge.verified {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}
.status-badge .dashicons {
    margin-right: 5px;
}
.verification-note {
    font-style: italic;
    color: #666;
    margin-top: 10px;
}
</style>

<?php
return ob_get_clean();

}


## 五、API接口开发

### 5.1 REST API端点

// 注册自定义REST API端点
add_action('rest_api_init', 'register_supply_chain_api_endpoints');

function register_supply_chain_api_endpoints() {

// 产品验证API
register_rest_route('supply-chain/v1', '/verify/(?P<id>d+)', array(
    'methods' => 'GET',
    'callback' => 'api_verify_product',
    'permission_callback' => '__return_true', // 公开访问
    'args' => array(
        'id' => array(
            'validate_callback' => function($param, $request, $key) {
                return is_numeric($param);
            }
        ),
    ),
));

// 记录交易API
register_rest_route('supply-chain/v1', '/record-transaction', array(
    'methods' => 'POST',
    'callback' => 'api_record_transaction',
    'permission_callback' => 'api_check_permission', // 需要API密钥
));

// 批量查询API
register_rest_route('supply-chain/v1', '/batch-verify', array(
    'methods' => 'POST',
    'callback' => 'api_batch_verify',
    'permission_callback' => '__return_true',
));

}

function api_verify_product($request) {

$product_id = $request['id'];

// 检查产品是否存在
$product = get_post($product_id);
if (!$product || $product->post_type !== 'supply_chain_product') {
    return new WP_Error('not_found', '产品不存在', array('status' => 404));
}

$blockchain = new BlockchainHandler();
$verification_result = $blockchain->verify_product($product_id);

// 获取交易记录
$transactions = get_post_meta($product_id, 'supply_chain_transactions', true);

$response = array(
    'success' => true,
    'data' => array(
        'product' => array(
            'id' => $product_id,
            'name' => $product->post_title,
            'description' => $product->post_content,
            'blockchain_info' => $verification_result,
            'transactions' => is_array($transactions) ? $transactions : array(),
            'verification_timestamp' => current_time('timestamp'),
            'verification_status' => 'verified'
        )
    )
);

return rest_ensure_response($response);

}

function api_record_transaction($request) {

$parameters = $request->get_json_params();

// 验证必要参数
$required_params = array('product_id', 'from_address', 'to_address', 'location', 'api_key');
foreach ($required_params as $param) {
    if (!isset($parameters[$param]) || empty($parameters[$param])) {
        return new WP_Error('missing_param', "缺少必要参数: $param", array('status' => 400));
    }
}

// 验证API密钥
$valid_api_key = get_option('supply_chain_api_key', '');
if ($parameters['api_key'] !== $valid_api_key) {
    return new WP_Error('invalid_api_key', '无效的API密钥', array('status' => 401));
}

$blockchain = new BlockchainHandler();

$transaction_data = array(
    'product_id' => intval($parameters['product_id']),
    'from_address' => sanitize_text_field($parameters['from_address']),
    'to_address' => sanitize_text_field($parameters['to_address']),
    'location' => sanitize_text_field($parameters['location']),
    'condition_hash' => isset($parameters['condition_hash']) ? sanitize_text_field($parameters['condition_hash']) : '',
    'metadata' => isset($parameters['metadata']) ? sanitize_textarea_field($parameters['metadata']) : ''
);

$result = $blockchain->record_transaction($transaction_data);

if ($result['success']) {
    $response = array(
        'success' => true,
        'message' => '交易记录成功',
        'transaction_hash' => $result['tx_hash'],
        'timestamp' => current_time('timestamp')
    );
} else {
    $response = array(
        'success' => false,
        'message' => '交易记录失败',
        'error' => $result['message']
    );
}

return rest_ensure_response($response);

}

function api_batch_verify($request) {

$parameters = $request->get_json_params();

if (!isset($parameters['product_ids']) || !is_array($parameters['product_ids'])) {
    return new WP_Error('invalid_params', '需要产品ID数组', array('status' => 400));
}

$results = array();
$blockchain = new BlockchainHandler();

foreach ($parameters['product_ids'] as $product_id) {
    $product_id = intval($product_id);
    $product = get_post($product_id);
    
    if ($product && $product->post_type === 'supply_chain_product') {
        $verification_result = $blockchain->verify_product($product_id);
        $results[] = array(
            'product_id' => $product_id,
            'product_name' => $product->post_title,
            'verified' => true,
            'blockchain_data' => $verification_result
        );
    } else {
        $results[] = array(
            'product_id' => $product_id,
            'verified' => false,
            'error' => '产品不存在'
        );
    }
}

return rest_ensure_response(array(
    'success' => true,
    'count' => count($results),
    'results' => $results
));

}

function api_check_permission($request) {

// 这里可以实现更复杂的权限检查
// 例如检查API密钥、用户角色等
return true;

}


### 5.2 Web3.js前端交互

// supply-chain-web

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

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

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