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

WordPress+WooCommerce支付完成后执行自定义代码及获取订单变量

在WooCommerce中实现支付完成后触发自定义动作并获取订单变量

一、支付完成后触发自定义动作(发送订单数据到API)

WooCommerce提供了两个核心钩子用于监听支付完成事件,可根据业务场景选择:

  • woocommerce_payment_complete:订单成功完成支付时立即触发(即便订单后续需要人工审核,只要支付环节完成就会执行)
  • woocommerce_order_status_completed:当订单状态正式变为completed时触发(适合要求订单完全闭环后再执行的场景)

实现代码示例

将以下代码添加到主题的functions.php文件或自定义插件中:

add_action('woocommerce_payment_complete', 'send_order_to_external_api', 10, 1);

function send_order_to_external_api($order_id) {
    // 获取WooCommerce订单对象
    $order = wc_get_order($order_id);
    if (!$order) return;

    // 组装API所需数据(可根据接口要求调整字段)
    $payload = array(
        'order_id'       => $order->get_id(),
        'customer_email' => $order->get_billing_email(),
        'total'          => $order->get_total(),
        'currency'       => $order->get_currency(),
        'items'          => array()
    );

    // 遍历订单商品,收集产品ID、数量等信息
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $payload['items'][] = array(
            'product_id' => $product->get_id(),
            'quantity'   => $item->get_quantity(),
            'name'       => $item->get_name(),
            'subtotal'   => $item->get_subtotal()
        );
    }

    // 发送POST请求到目标API
    $response = wp_remote_post('https://your-api-url.com/endpoint', array(
        'headers' => array('Content-Type' => 'application/json'),
        'body'    => json_encode($payload),
        'timeout' => 20
    ));

    // 可选:记录请求日志用于排查问题
    if (is_wp_error($response)) {
        error_log('API请求失败: ' . $response->get_error_message());
    } else {
        error_log('API请求成功,响应码: ' . wp_remote_retrieve_response_code($response));
    }
}

注意:替换https://your-api-url.com/endpoint为实际API地址,根据接口文档调整请求头和数据结构。

二、获取订单动态变量(产品ID、数量等)

通过wc_get_order($order_id)获取订单对象后,可调用WooCommerce内置方法提取各类订单数据:

常用数据获取方法

基础订单信息

  • 订单ID:$order->get_id()
  • 订单状态:$order->get_status()
  • 订单总价:$order->get_total()
  • 客户手机号:$order->get_billing_phone()
  • 订单创建时间:$order->get_date_created()->format('Y-m-d H:i:s')

商品明细数据

foreach ($order->get_items() as $item) {
    // 产品ID(可变产品会返回父ID)
    $product_id = $item->get_product_id();
    // 变体ID(仅可变产品有值)
    $variation_id = $item->get_variation_id();
    // 购买数量
    $quantity = $item->get_quantity();
    // 商品单项总价(不含税)
    $item_total = $item->get_total();
    // 获取产品对象,可提取SKU、库存等更多信息
    $product = $item->get_product();
    $sku = $product->get_sku();
}

地址与支付信息

  • 账单城市:$order->get_billing_city()
  • 支付方式名称:$order->get_payment_method_title()
  • 发货地址:$order->get_shipping_address_1()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:10:28