首页 / 应用软件 / 一步步教你,在WordPress中集成支付网关功能

一步步教你,在WordPress中集成支付网关功能

一步步教你,在WordPress中集成支付网关功能 引言:为什么需要在WordPress中集成支付功能? 在当今数字化时代,网站不再仅仅是信息展示平台,更是商业交易的重要渠道。无论是电子商务网站、会员制内容平台,还是在线服务预约系统,支付功能都是不可或缺的核心组…

一步步教你,在WordPress中集成支付网关功能

引言:为什么需要在WordPress中集成支付功能?

在当今数字化时代,网站不再仅仅是信息展示平台,更是商业交易的重要渠道。无论是电子商务网站、会员制内容平台,还是在线服务预约系统,支付功能都是不可或缺的核心组件。WordPress作为全球最流行的内容管理系统,其强大的扩展性使得开发者能够通过代码二次开发实现各种支付网关的集成。

本文将详细指导您如何在WordPress中通过代码开发集成支付网关功能,实现安全、可靠的在线支付解决方案。我们将以支付宝和Stripe为例,展示完整的代码实现过程,并提供详细的代码注释,帮助您理解每一步的实现原理。

准备工作:环境配置与安全考虑

在开始编码之前,我们需要做好以下准备工作:

  1. 开发环境配置:确保您拥有一个本地或测试环境的WordPress安装,建议使用WordPress 5.0以上版本。
  2. 支付网关账户

    • 支付宝:需要企业支付宝账户并开通即时到账或电脑网站支付功能
    • Stripe:注册Stripe开发者账户获取API密钥
  3. 安全措施

    • 使用SSL证书确保数据传输安全
    • 妥善保管API密钥,不要硬编码在代码中
    • 实现支付结果验证机制,防止伪造支付通知
  4. 代码结构规划:我们将创建一个独立的插件来实现支付功能,确保与主题分离,便于维护和迁移。

第一步:创建支付插件基础结构

首先,我们创建一个名为"Custom-Payment-Gateway"的插件,建立基本文件结构:

<?php
/**
 * Plugin Name: 自定义支付网关
 * Plugin URI: https://yourwebsite.com/
 * Description: 为WordPress网站添加支付宝和Stripe支付功能
 * 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__));

// 初始化插件
add_action('plugins_loaded', 'custom_payment_init');

function custom_payment_init() {
    // 检查WooCommerce是否存在(如果需要在WooCommerce中集成)
    if (class_exists('WC_Payment_Gateway')) {
        // 包含支付网关类文件
        require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/class-alipay-gateway.php';
        require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/class-stripe-gateway.php';
        
        // 注册支付网关到WooCommerce
        add_filter('woocommerce_payment_gateways', 'add_custom_payment_gateways');
    }
    
    // 注册自定义支付处理钩子
    add_action('init', 'register_custom_payment_endpoints');
}

/**
 * 添加自定义支付网关到WooCommerce
 * @param array $gateways 现有支付网关数组
 * @return array 更新后的支付网关数组
 */
function add_custom_payment_gateways($gateways) {
    $gateways[] = 'WC_Alipay_Gateway';
    $gateways[] = 'WC_Stripe_Gateway';
    return $gateways;
}

/**
 * 注册自定义支付端点
 */
function register_custom_payment_endpoints() {
    // 支付宝异步通知端点
    add_rewrite_rule('^alipay-notify/?$', 'index.php?alipay_notify=1', 'top');
    add_rewrite_rule('^alipay-return/?$', 'index.php?alipay_return=1', 'top');
    
    // Stripe支付结果端点
    add_rewrite_rule('^stripe-webhook/?$', 'index.php?stripe_webhook=1', 'top');
    
    // 注册查询变量
    add_filter('query_vars', function($vars) {
        $vars[] = 'alipay_notify';
        $vars[] = 'alipay_return';
        $vars[] = 'stripe_webhook';
        return $vars;
    });
    
    // 处理支付端点请求
    add_action('template_redirect', 'handle_payment_endpoints');
}

/**
 * 处理支付端点请求
 */
function handle_payment_endpoints() {
    // 处理支付宝异步通知
    if (get_query_var('alipay_notify')) {
        require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/alipay-notify-handler.php';
        exit;
    }
    
    // 处理支付宝同步返回
    if (get_query_var('alipay_return')) {
        require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/alipay-return-handler.php';
        exit;
    }
    
    // 处理Stripe Webhook
    if (get_query_var('stripe_webhook')) {
        require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/stripe-webhook-handler.php';
        exit;
    }
}
?>

第二步:实现支付宝支付网关

接下来,我们创建支付宝支付网关类。首先创建文件 includes/class-alipay-gateway.php

<?php
/**
 * 支付宝支付网关类
 * 继承WooCommerce支付网关基类
 */

if (!class_exists('WC_Payment_Gateway')) {
    return;
}

class WC_Alipay_Gateway extends WC_Payment_Gateway {
    
    /**
     * 构造函数,初始化支付网关
     */
    public function __construct() {
        $this->id = 'alipay'; // 支付网关ID
        $this->icon = CUSTOM_PAYMENT_PLUGIN_URL . 'assets/alipay-logo.png'; // 支付图标
        $this->has_fields = false; // 不需要自定义支付字段
        $this->method_title = '支付宝支付';
        $this->method_description = '通过支付宝进行安全支付';
        
        // 初始化设置字段
        $this->init_form_fields();
        $this->init_settings();
        
        // 获取设置值
        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description');
        $this->enabled = $this->get_option('enabled');
        $this->app_id = $this->get_option('app_id');
        $this->merchant_private_key = $this->get_option('merchant_private_key');
        $this->alipay_public_key = $this->get_option('alipay_public_key');
        
        // 保存设置
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        
        // 注册支付结果处理
        add_action('woocommerce_api_wc_alipay_gateway', array($this, 'handle_alipay_response'));
    }
    
    /**
     * 初始化设置表单字段
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => '启用/禁用',
                'type' => 'checkbox',
                'label' => '启用支付宝支付',
                'default' => 'no'
            ),
            'title' => array(
                'title' => '标题',
                'type' => 'text',
                'description' => '支付时用户看到的标题',
                'default' => '支付宝支付',
                'desc_tip' => true
            ),
            'description' => array(
                'title' => '描述',
                'type' => 'textarea',
                'description' => '支付方式描述',
                'default' => '通过支付宝安全支付'
            ),
            'app_id' => array(
                'title' => 'APP ID',
                'type' => 'text',
                'description' => '支付宝开放平台APP ID'
            ),
            'merchant_private_key' => array(
                'title' => '商户私钥',
                'type' => 'textarea',
                'description' => '商户私钥,用于签名'
            ),
            'alipay_public_key' => array(
                'title' => '支付宝公钥',
                'type' => 'textarea',
                'description' => '支付宝公钥,用于验证签名'
            )
        );
    }
    
    /**
     * 处理支付
     * @param int $order_id 订单ID
     * @return array 支付结果
     */
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);
        
        // 构建支付宝请求参数
        $params = $this->build_alipay_params($order);
        
        // 生成签名
        $params['sign'] = $this->generate_signature($params);
        
        // 构建表单自动提交到支付宝
        $form_html = $this->build_alipay_form($params);
        
        return array(
            'result' => 'success',
            'redirect' => '',
            'form_html' => $form_html
        );
    }
    
    /**
     * 构建支付宝请求参数
     * @param WC_Order $order 订单对象
     * @return array 支付宝请求参数
     */
    private function build_alipay_params($order) {
        return array(
            'app_id' => $this->app_id,
            'method' => 'alipay.trade.page.pay',
            'format' => 'JSON',
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'notify_url' => home_url('/alipay-notify/'),
            'return_url' => home_url('/alipay-return/'),
            'biz_content' => json_encode(array(
                'out_trade_no' => $order->get_order_number(),
                'product_code' => 'FAST_INSTANT_TRADE_PAY',
                'total_amount' => $order->get_total(),
                'subject' => '订单支付 - ' . $order->get_order_number(),
                'body' => '商品描述',
                'timeout_express' => '30m'
            ))
        );
    }
    
    /**
     * 生成签名
     * @param array $params 待签名参数
     * @return string 签名结果
     */
    private function generate_signature($params) {
        // 参数排序
        ksort($params);
        
        // 拼接参数字符串
        $string_to_sign = '';
        foreach ($params as $key => $value) {
            if ($key != 'sign' && $value != '') {
                $string_to_sign .= $key . '=' . $value . '&';
            }
        }
        $string_to_sign = rtrim($string_to_sign, '&');
        
        // 使用商户私钥签名
        $private_key = "-----BEGIN RSA PRIVATE KEY-----n" .
                      wordwrap($this->merchant_private_key, 64, "n", true) .
                      "n-----END RSA PRIVATE KEY-----";
        
        openssl_sign($string_to_sign, $signature, $private_key, OPENSSL_ALGO_SHA256);
        
        return base64_encode($signature);
    }
    
    /**
     * 构建支付宝支付表单
     * @param array $params 支付参数
     * @return string 表单HTML
     */
    private function build_alipay_form($params) {
        $form = '<form id="alipay_submit" name="alipay_submit" action="https://openapi.alipay.com/gateway.do" method="POST">';
        foreach ($params as $key => $value) {
            $form .= '<input type="hidden" name="' . esc_attr($key) . '" value="' . esc_attr($value) . '">';
        }
        $form .= '</form>';
        $form .= '<script>document.forms["alipay_submit"].submit();</script>';
        
        return $form;
    }
    
    /**
     * 处理支付宝返回结果
     */
    public function handle_alipay_response() {
        // 获取支付宝返回参数
        $params = $_POST;
        
        // 验证签名
        if ($this->verify_signature($params)) {
            $out_trade_no = $params['out_trade_no'];
            $trade_status = $params['trade_status'];
            
            // 根据交易状态更新订单
            $order = wc_get_order($out_trade_no);
            
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                // 支付成功
                $order->payment_complete();
                $order->add_order_note('支付宝支付成功,交易号:' . $params['trade_no']);
                
                // 重定向到感谢页面
                wp_redirect($this->get_return_url($order));
                exit;
            } else {
                // 支付失败
                $order->update_status('failed', '支付宝支付失败:' . $trade_status);
                wc_add_notice('支付失败,请重试', 'error');
                wp_redirect(wc_get_checkout_url());
                exit;
            }
        } else {
            // 签名验证失败
            wc_add_notice('支付验证失败', 'error');
            wp_redirect(wc_get_checkout_url());
            exit;
        }
    }
    
    /**
     * 验证支付宝签名
     * @param array $params 支付宝返回参数
     * @return bool 验证结果
     */
    private function verify_signature($params) {
        $sign = $params['sign'];
        unset($params['sign']);
        unset($params['sign_type']);
        
        // 参数排序
        ksort($params);
        
        // 拼接参数字符串
        $string_to_sign = '';
        foreach ($params as $key => $value) {
            if ($value != '') {
                $string_to_sign .= $key . '=' . $value . '&';
            }
        }
        $string_to_sign = rtrim($string_to_sign, '&');
        
        // 使用支付宝公钥验证签名
        $public_key = "-----BEGIN PUBLIC KEY-----n" .
                     wordwrap($this->alipay_public_key, 64, "n", true) .
                     "n-----END PUBLIC KEY-----";
        
        return openssl_verify($string_to_sign, base64_decode($sign), $public_key, OPENSSL_ALGO_SHA256) === 1;
    }
}
?>

第三步:实现Stripe支付网关

创建Stripe支付网关类文件 includes/class-stripe-gateway.php

<?php
/**
 * Stripe支付网关类
 */

if (!class_exists('WC_Payment_Gateway')) {
    return;
}

class WC_Stripe_Gateway extends WC_Payment_Gateway {
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->id = 'stripe';
        $this->icon = CUSTOM_PAYMENT_PLUGIN_URL . 'assets/stripe-logo.png';
        $this->has_fields = true; // 需要自定义支付字段(信用卡信息)
        $this->method_title = 'Stripe支付';
        $this->method_description = '通过Stripe接受信用卡支付';
        
        // 初始化设置
        $this->init_form_fields();
        $this->init_settings();
        
        // 获取设置值
        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description');
        $this->enabled = $this->get_option('enabled');
        $this->testmode = 'yes' === $this->get_option('testmode');
        $this->publishable_key = $this->testmode ? $this->get_option('test_publishable_key') : $this->get_option('live_publishable_key');
        $this->secret_key = $this->testmode ? $this->get_option('test_secret_key') : $this->get_option('live_secret_key');
        
        // 保存设置
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        
        // 加载Stripe JS库
        add_action('wp_enqueue_scripts', array($this, 'payment_scripts'));
    }
    
    /**
     * 初始化设置表单字段
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => '启用/禁用',
                'type' => 'checkbox',
                'label' => '启用Stripe支付',
                'default' => 'no'
            ),
            'title' => array(
                'title' => '标题',
                'type' => 'text',
                'description' => '支付时用户看到的标题',
                'default' => '信用卡支付 (Stripe)',
                'desc_tip' => true
            ),
            'description' => array(
                'title' => '描述',
                'type' => 'textarea',
                'description' => '支付方式描述',
                'default' => '使用信用卡安全支付'
            ),
            'testmode' => array(
                'title' => '测试模式',
                'type' => 'checkbox',
                'label' => '启用测试模式',
                'default' => 'yes',
                'description' => '测试模式下使用测试API密钥'
            ),
            'test_publishable_key' => array(
                'title' => '测试Publishable Key',
                'type' => 'text'
            ),
            'test_secret_key' => array(
                'title' => '测试Secret Key',
                'type' => 'password'
            ),
            'live_publishable_key' => array(
                'title' => '正式Publishable Key',
                'type' => 'text'
            ),
            'live_secret_key' => array(
                'title' => '正式Secret Key',
                'type' => 'password'
            )
        );
    }
    
    /**
     * 加载支付脚本
     */
    public function payment_scripts() {

$this->is_available()) {

        return;
    }

    // 加载Stripe.js
    wp_enqueue_script('stripe-js', 'https://js.stripe.com/v3/', array(), null, true);
    
    // 加载自定义支付脚本
    wp_enqueue_script(
        'stripe-payment',
        CUSTOM_PAYMENT_PLUGIN_URL . 'assets/js/stripe-payment.js',
        array('jquery', 'stripe-js'),
        CUSTOM_PAYMENT_VERSION,
        true
    );
    
    // 传递参数到JavaScript
    wp_localize_script('stripe-payment', 'stripe_params', array(
        'publishable_key' => $this->publishable_key,
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('stripe-payment-nonce')
    ));
}

/**
 * 支付字段(信用卡表单)
 */
public function payment_fields() {
    echo '<div class="stripe-credit-card-form">';
    
    if ($this->description) {
        echo wpautop(wp_kses_post($this->description));
    }
    
    // 信用卡表单
    echo '
    <div class="form-row">
        <label for="stripe-card-element">信用卡信息</label>
        <div id="stripe-card-element" class="stripe-card-element">
            <!-- Stripe Card Element will be inserted here -->
        </div>
        <div id="stripe-card-errors" role="alert" class="stripe-card-errors"></div>
    </div>
    
    <div class="form-row">
        <label for="stripe-card-name">持卡人姓名</label>
        <input id="stripe-card-name" type="text" placeholder="姓名" class="stripe-card-name">
    </div>';
    
    echo '</div>';
}

/**
 * 验证支付字段
 * @return bool 验证结果
 */
public function validate_fields() {
    // 前端验证已在JavaScript中完成
    // 这里可以进行额外的后端验证
    return true;
}

/**
 * 处理支付
 * @param int $order_id 订单ID
 * @return array 支付结果
 */
public function process_payment($order_id) {
    $order = wc_get_order($order_id);
    
    try {
        // 初始化Stripe
        StripeStripe::setApiKey($this->secret_key);
        
        // 创建支付意向
        $intent = StripePaymentIntent::create([
            'amount' => $this->get_stripe_amount($order->get_total()),
            'currency' => strtolower(get_woocommerce_currency()),
            'description' => '订单 #' . $order->get_order_number(),
            'metadata' => [
                'order_id' => $order_id,
                'customer_ip' => $order->get_customer_ip_address()
            ],
            'payment_method_types' => ['card'],
        ]);
        
        // 保存支付意向ID到订单
        $order->update_meta_data('_stripe_payment_intent_id', $intent->id);
        $order->save();
        
        // 返回支付结果
        return [
            'result' => 'success',
            'redirect' => $this->get_return_url($order),
            'intent_id' => $intent->id,
            'client_secret' => $intent->client_secret
        ];
        
    } catch (StripeExceptionApiErrorException $e) {
        wc_add_notice('支付处理错误: ' . $e->getMessage(), 'error');
        return [
            'result' => 'fail',
            'redirect' => ''
        ];
    }
}

/**
 * 转换金额为Stripe格式(分/美分)
 * @param float $amount 金额
 * @return int Stripe格式金额
 */
private function get_stripe_amount($amount) {
    $currency = get_woocommerce_currency();
    
    // 处理零小数货币
    $zero_decimal_currencies = ['JPY', 'KRW', 'VND'];
    if (in_array($currency, $zero_decimal_currencies)) {
        return absint($amount);
    }
    
    // 其他货币转换为分/美分
    return absint(wc_format_decimal($amount, 2) * 100);
}

/**
 * 处理Stripe Webhook
 */
public static function handle_webhook() {
    $payload = @file_get_contents('php://input');
    $event = null;
    
    try {
        // 验证Webhook签名
        $signature_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $endpoint_secret = get_option('woocommerce_stripe_webhook_secret');
        
        $event = StripeWebhook::constructEvent(
            $payload, $signature_header, $endpoint_secret
        );
    } catch(UnexpectedValueException $e) {
        // 无效的payload
        http_response_code(400);
        exit();
    } catch(StripeExceptionSignatureVerificationException $e) {
        // 无效的签名
        http_response_code(400);
        exit();
    }
    
    // 处理事件
    switch ($event->type) {
        case 'payment_intent.succeeded':
            self::handle_payment_intent_succeeded($event->data->object);
            break;
            
        case 'payment_intent.payment_failed':
            self::handle_payment_intent_failed($event->data->object);
            break;
            
        case 'charge.refunded':
            self::handle_charge_refunded($event->data->object);
            break;
    }
    
    http_response_code(200);
}

/**
 * 处理支付成功事件
 * @param object $payment_intent 支付意向对象
 */
private static function handle_payment_intent_succeeded($payment_intent) {
    $order_id = $payment_intent->metadata->order_id;
    
    if ($order_id) {
        $order = wc_get_order($order_id);
        
        if ($order && !$order->is_paid()) {
            // 更新订单状态
            $order->payment_complete();
            $order->add_order_note('Stripe支付成功,交易ID: ' . $payment_intent->id);
            
            // 保存交易ID
            $order->update_meta_data('_stripe_transaction_id', $payment_intent->id);
            $order->save();
        }
    }
}

/**
 * 处理支付失败事件
 * @param object $payment_intent 支付意向对象
 */
private static function handle_payment_intent_failed($payment_intent) {
    $order_id = $payment_intent->metadata->order_id;
    
    if ($order_id) {
        $order = wc_get_order($order_id);
        
        if ($order && !$order->is_paid()) {
            $order->update_status('failed', 'Stripe支付失败: ' . $payment_intent->last_payment_error->message);
        }
    }
}

}
?>


## 第四步:创建支付处理脚本

创建Stripe前端支付脚本 `assets/js/stripe-payment.js`:

/**

  • Stripe支付前端处理脚本
    */

jQuery(document).ready(function($) {

// 初始化Stripe
const stripe = Stripe(stripe_params.publishable_key);
const elements = stripe.elements();

// 创建信用卡元素
const cardElement = elements.create('card', {
    style: {
        base: {
            fontSize: '16px',
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    }
});

// 挂载信用卡元素
cardElement.mount('#stripe-card-element');

// 实时验证错误
cardElement.addEventListener('change', function(event) {
    const displayError = document.getElementById('stripe-card-errors');
    if (event.error) {
        displayError.textContent = event.error.message;
    } else {
        displayError.textContent = '';
    }
});

// 处理表单提交
$('form.checkout').on('checkout_place_order_stripe', function(e) {
    e.preventDefault();
    
    const $form = $(this);
    const $submitButton = $form.find('#place_order');
    
    // 禁用提交按钮防止重复提交
    $submitButton.prop('disabled', true).val('处理中...');
    
    // 获取持卡人姓名
    const cardName = $('#stripe-card-name').val();
    
    if (!cardName) {
        $('#stripe-card-errors').text('请输入持卡人姓名');
        $submitButton.prop('disabled', false).val('下订单');
        return false;
    }
    
    // 创建支付方法
    stripe.createPaymentMethod({
        type: 'card',
        card: cardElement,
        billing_details: {
            name: cardName
        }
    }).then(function(result) {
        if (result.error) {
            // 显示错误
            $('#stripe-card-errors').text(result.error.message);
            $submitButton.prop('disabled', false).val('下订单');
        } else {
            // 发送支付方法到服务器
            $.ajax({
                url: stripe_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'stripe_create_payment_intent',
                    payment_method_id: result.paymentMethod.id,
                    order_id: $form.find('#order_id').val(),
                    nonce: stripe_params.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // 确认支付
                        stripe.confirmCardPayment(response.data.client_secret, {
                            payment_method: result.paymentMethod.id
                        }).then(function(confirmResult) {
                            if (confirmResult.error) {
                                $('#stripe-card-errors').text(confirmResult.error.message);
                                $submitButton.prop('disabled', false).val('下订单');
                            } else {
                                // 支付成功,提交表单
                                $form.submit();
                            }
                        });
                    } else {
                        $('#stripe-card-errors').text(response.data.message);
                        $submitButton.prop('disabled', false).val('下订单');
                    }
                }
            });
        }
    });
    
    return false;
});

});


## 第五步:创建支付结果处理页面

创建支付宝异步通知处理文件 `includes/alipay-notify-handler.php`:

<?php
/**

  • 支付宝异步通知处理
    */

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

exit;

}

// 获取POST数据
$post_data = $_POST;

// 验证签名
require_once CUSTOM_PAYMENT_PLUGIN_DIR . 'includes/class-alipay-gateway.php';
$gateway = new WC_Alipay_Gateway();

if ($gateway->verify_signature($post_data)) {

// 获取订单信息
$out_trade_no = $post_data['out_trade_no'];
$trade_no = $post_data['trade_no'];
$trade_status = $post_data['trade_status'];

// 获取订单
$order = wc_get_order($out_trade_no);

if ($order) {
    // 检查订单是否已处理
    if (!$order->is_paid()) {
        switch ($trade_status) {
            case 'TRADE_SUCCESS':
            case 'TRADE_FINISHED':
                // 支付成功
                $order->payment_complete();
                $order->add_order_note('支付宝支付成功,交易号:' . $trade_no);
                
                // 更新订单元数据
                $order->update_meta_data('_alipay_transaction_id', $trade_no);
                $order->save();
                break;
                
            case 'TRADE_CLOSED':
                // 交易关闭
                $order->update_status('cancelled', '支付宝交易已关闭');
                break;
                
            default:
                // 其他状态
                break;
        }
    }
}

// 返回成功响应给支付宝
echo 'success';

} else {

// 签名验证失败
echo 'fail';

}
?>


## 第六步:创建管理界面和工具函数

创建工具函数文件 `includes/functions.php`:

<?php
/**

  • 支付工具函数
    */

/**

  • 记录支付日志
  • @param string $message 日志消息
  • @param string $level 日志级别
    */

function custom_payment_log($message, $level = 'info') {

$log_file = CUSTOM_PAYMENT_PLUGIN_DIR . 'logs/payment.log';

// 创建日志目录
$log_dir = dirname($log_file);
if (!file_exists($log_dir)) {
    wp_mkdir_p($log_dir);
}

// 格式化日志消息
$timestamp = current_time('mysql');
$log_message = sprintf("[%s] %s: %sn", $timestamp, strtoupper($level), $message);

// 写入日志文件
file_put_contents($log_file, $log_message, FILE_APPEND | LOCK_EX);

}

/**

  • 验证IP地址是否来自支付宝
  • @param string $ip 要验证的IP地址
  • @return bool 验证结果
    */

function is_alipay_ip($ip) {

$alipay_ips = [
    '110.75.128.0/19',
    '110.75.160.0/19',
    '110.75.192.0/19',
    '110.76.0.0/18',
    '110.76.64.0/18',
    '110.76.128.0/18',
    '110.76.192.0/19',
    '121.0.16.0/20',
    '121.0.24.0/21',
    '121.0.32.0/19',
    '121.0.64.0/18',
    '121.0.128.0/17',
    '121.1.0.0/16',
    '121.2.0.0/17',
    '121.2.128.0/17',
    '121.3.0.0/16',
    '121.4.0.0/15',
    '121.8.0.0/13',
    '121.16.0.0/12',
    '121.32.0.0/13',
    '121.40.0.0/14',
    '121.46.0.0/18',
    '121.46.64.0/19',
    '121.46.128.0/17',
    '121.47.0.0/16',
    '121.48.0.0/15',
    '121.50.8.0/21',
    '121.51.0.0/16',
    '121.52.0.0/15',
    '121.54.0.0/15',
    '121.56.0.0/13',
    '121.64.0.0/14',
    '121.68.0.0/14',
    '121.72.0.0/13',
    '121.80.0.0/14',
    '121.84.0.0/14',
    '121.88.0.0/16',
    '121.89.0.0/16',
    '121.90.0.0/15',
    '121.92.0.0/16',
    '121.93.0.0/16',
    '121.94.0.0/15',
    '121.96.0.0/15',
    '121.98.0.0/16',
    '121.99.0.0/16',
    '121.100.0.0/16',
    '121.101.0.0/18',
    '121.101.64.0/18',
    '121.101.128.0/17',
    '121.102.0.0/16',
    '121.103.0.0/16',
    '121.104.0.0/14',
    '121.108.0.0/14',
    '121.112.0.0/13',
    '121.120.0.0/14',
    '121.124.0.0/15',
    '121.126.0.0/16',
    '121.127.0.0/16',
    '121.128.0.0/10',
    '121.192.0.0/13',
    '121.200.0.0/14',
    '121.204.0.0/14',
    '121.208.0.0/12',
    '121.224.0.0/12',
    '121.240.0.0/13',
    '121.248.0.0/14',
    '121.252.0.0/15',
    '121.254.0.0/16',
    '122.0.64.0/18',
    '122.0.128.0/17',
    '122.4.0.0/14',
    '122.8.0.0/15',
    '122.10.0.0/17',
    '122.10.128.0/17',
    '122.11.0.0/17',
    '122.12.0.0/15',
    '122.14.0.0/16',
    '122.48.0.0/16',
    '122.49.0.0/18',
    '122.51.0.0/16',
    '122.64.0.0/11',
    '122.96.0.0/15',
    '122.102.0.0/20',
    '122.102.64.0/19',
    '122.112.0.0/14',
    '122.119.0.0/16',
    '122.128.100.0/22',
    '122.128.
本文来自网络投稿,不代表本站点的立场,转载请注明出处:https://www.gongxiangcang.com/5062.html

溯源库®作者

漳州柔性供应链服务有限公司 小批量订单定制化服务商( 投稿邮箱:vip@jiaochengku.com)
上一篇
下一篇

为您推荐

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@suyuanku.com

工作时间:周一至周五,9:00-17:30,节假日休息
关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部