You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WooCommerce跨站支付集成?让Site B处理Site A的Stripe支付

跨WooCommerce站点支付集成:让Site A通过Site B的Stripe完成支付

环境概述

  • Site A:WooCommerce + WooCommerce Custom Payment Gateway Pro + AffiliateWP,产品无法直接对接Stripe
  • Site B:WooCommerce + 官方Stripe插件,支持Stripe支付

核心需求:用户在Site A提交订单后,跳转至Site B的Stripe支付流程完成付款,最终同步订单状态回Site A并触发AffiliateWP佣金计算。


核心实现步骤

一、Site B 配置(接收请求+处理支付)

1. 注册安全的REST API端点

在Site B的functions.php或自定义插件中添加代码,创建用于接收Site A订单数据的API端点,同时加入密钥验证防止恶意请求:

add_action('rest_api_init', function () {
    register_rest_route('siteb-payment/v1', '/create-session', [
        'methods' => 'POST',
        'callback' => 'siteb_create_stripe_session',
        'permission_callback' => function ($request) {
            // 验证共享API密钥
            $api_key = $request->get_header('X-SiteB-API-Key');
            if ($api_key !== 'YOUR_SHARED_SECRET_KEY') {
                return new WP_Error('invalid_key', '无效API密钥', ['status' => 403]);
            }
            return true;
        }
    ]);
});

2. 创建临时订单并生成Stripe支付会话

实现端点回调函数,接收Site A的订单数据,创建Site B临时订单并调用Stripe API生成支付链接:

function siteb_create_stripe_session($request) {
    $data = $request->get_json_params();
    
    // 校验必填参数
    if (!isset($data['siteA_order_id'], $data['total_amount'], $data['customer_email'])) {
        return new WP_Error('missing_params', '缺少必要参数', ['status' => 400]);
    }
    
    // 创建Site B临时订单
    $order_data = [
        'status' => 'pending',
        'customer_note' => '来自Site A的订单:' . $data['siteA_order_id'],
        'billing' => [
            'first_name' => $data['customer_first_name'],
            'last_name' => $data['customer_last_name'],
            'email' => $data['customer_email'],
            'phone' => $data['customer_phone']
        ],
        'line_items' => [[
            'product_id' => 0, // 可替换为Site B的虚拟产品ID
            'quantity' => 1,
            'total' => $data['total_amount']
        ]]
    ];
    
    $order = wc_create_order($order_data);
    if (!$order) {
        return new WP_Error('order_fail', '创建订单失败', ['status' => 500]);
    }
    
    // 标记Site A订单ID,用于后续同步
    $order->update_meta_data('_siteA_order_id', $data['siteA_order_id']);
    $order->save();
    
    // 生成Stripe支付会话
    $stripe = new \Stripe\StripeClient('sk_live_YOUR_STRIPE_SECRET');
    $session = $stripe->checkout->sessions->create([
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'usd', // 替换为实际货币代码
                'unit_amount' => $data['total_amount'] * 100, // 转换为分
                'product_data' => ['name' => 'Site A订单 #' . $data['siteA_order_id']]
            ],
            'quantity' => 1
        ]],
        'mode' => 'payment',
        'success_url' => 'https://siteB.com/payment-success?order_id=' . $order->get_id() . '&siteA_order=' . $data['siteA_order_id'],
        'cancel_url' => 'https://siteB.com/payment-cancel?order_id=' . $order->get_id() . '&siteA_order=' . $data['siteA_order_id']
    ]);
    
    return [
        'payment_url' => $session->url,
        'siteB_order_id' => $order->get_id()
    ];
}

3. 支付成功后同步状态到Site A

添加钩子,当Site B订单完成时,主动通知Site A更新订单状态:

add_action('woocommerce_order_status_completed', 'siteb_sync_to_sitea', 10, 1);

function siteb_sync_to_sitea($order_id) {
    $order = wc_get_order($order_id);
    $siteA_order_id = $order->get_meta('_siteA_order_id');
    
    if (!$siteA_order_id) return;
    
    // 准备同步数据
    $sync_data = [
        'siteA_order_id' => $siteA_order_id,
        'status' => 'completed',
        'transaction_id' => $order->get_transaction_id()
    ];
    
    // 生成签名验证
    $signature = hash_hmac('sha256', json_encode($sync_data), 'YOUR_SHARED_SECRET_KEY');
    
    // 发送请求到Site A
    wp_remote_post('https://siteA.com/wp-json/sitea-payment/v1/update-order', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-Signature' => $signature
        ],
        'body' => json_encode($sync_data),
        'sslverify' => true
    ]);
}

二、Site A 配置(发送订单数据+处理回调)

1. 自定义支付网关的跳转逻辑

通过钩子修改WooCommerce Custom Payment Gateway Pro的跳转行为,将订单数据发送至Site B:

add_filter('woocommerce_custom_payment_gateway_pro_redirect_url', 'sitea_redirect_to_siteb', 10, 2);

function sitea_redirect_to_siteb($redirect_url, $order) {
    // 整理订单数据
    $order_data = [
        'siteA_order_id' => $order->get_id(),
        'total_amount' => $order->get_total(),
        'customer_first_name' => $order->get_billing_first_name(),
        'customer_last_name' => $order->get_billing_last_name(),
        'customer_email' => $order->get_billing_email(),
        'customer_phone' => $order->get_billing_phone()
    ];
    
    // 生成签名验证
    $signature = hash_hmac('sha256', json_encode($order_data), 'YOUR_SHARED_SECRET_KEY');
    
    // 发送请求到Site B
    $response = wp_remote_post('https://siteB.com/wp-json/siteb-payment/v1/create-session', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-SiteB-API-Key' => 'YOUR_SHARED_SECRET_KEY',
            'X-Signature' => $signature
        ],
        'body' => json_encode($order_data),
        'sslverify' => true
    ]);
    
    if (is_wp_error($response)) {
        wc_add_notice('支付网关连接失败', 'error');
        return wc_get_checkout_url();
    }
    
    $response_data = json_decode(wp_remote_retrieve_body($response), true);
    if (isset($response_data['payment_url'])) {
        return $response_data['payment_url'];
    } else {
        wc_add_notice('创建支付会话失败', 'error');
        return wc_get_checkout_url();
    }
}

2. 注册订单状态更新端点

创建用于接收Site B同步请求的端点,更新Site A订单状态并触发AffiliateWP佣金:

add_action('rest_api_init', function () {
    register_rest_route('sitea-payment/v1', '/update-order', [
        'methods' => 'POST',
        'callback' => 'sitea_update_order_status',
        'permission_callback' => function ($request) {
            // 验证签名
            $signature = $request->get_header('X-Signature');
            $data = $request->get_json_params();
            $expected_signature = hash_hmac('sha256', json_encode($data), 'YOUR_SHARED_SECRET_KEY');
            
            if ($signature !== $expected_signature) {
                return new WP_Error('invalid_signature', '无效签名', ['status' => 403]);
            }
            return true;
        }
    ]);
});

function sitea_update_order_status($request) {
    $data = $request->get_json_params();
    $order = wc_get_order($data['siteA_order_id']);
    
    if (!$order) {
        return new WP_Error('order_not_found', '订单不存在', ['status' => 404]);
    }
    
    // 更新订单状态
    $order->update_status('completed', '通过Site B完成Stripe支付');
    $order->set_transaction_id($data['transaction_id']);
    $order->save();
    
    // 触发AffiliateWP佣金计算
    if (function_exists('affwp_add_commission')) {
        affwp_add_commission([
            'amount' => $order->get_total(),
            'reference' => $order->get_id(),
            'status' => 'unpaid'
        ]);
    }
    
    return ['status' => 'success'];
}

关键安全措施

  1. 共享密钥:所有API请求必须使用预约定的共享密钥进行签名验证,防止数据篡改
  2. HTTPS传输:确保两个站点均使用HTTPS,避免敏感数据泄露
  3. 权限控制:API端点仅允许POST请求,且验证请求来源的合法性
  4. 参数校验:严格校验所有传入的订单数据,防止非法参数导致错误

测试与调试建议

  1. 使用Stripe测试密钥和测试卡号(如4242 4242 4242 4242)进行支付测试
  2. 开启WordPress错误日志,排查API请求中的异常
  3. 在Site B的临时订单中添加自定义字段,方便跟踪来自Site A的订单
  4. 测试支付失败、取消等场景,确保订单状态同步正常

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:05:14