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

PHP实现WooCommerce下单后即时获取订单并推送至外部服务器

How to Send WooCommerce Order Data as XML via POST to External Server After Order Placement

Got it, let's break this down into actionable steps—this is a common integration request, and I've built similar workflows a few times. Here's how to make it work reliably:

1. Pick the Right WooCommerce Hook

First, you need to trigger the code at the right moment. Two main hooks to choose from:

  • woocommerce_new_order: Runs immediately when an order is created (even if payment is pending). Use this if you need the data as soon as the order is submitted, regardless of payment status.
  • woocommerce_order_status_completed: Runs only when the order is marked "completed" (usually after successful payment). Better if you only want to send confirmed, paid orders.

I'll use woocommerce_new_order in the example, but you can swap it if needed.

2. Full Code Implementation

Add this code to your child theme's functions.php file, or use a custom plugin (recommended for better maintainability):

add_action('woocommerce_new_order', 'send_woocommerce_order_to_external_server', 10, 1);

function send_woocommerce_order_to_external_server($order_id) {
    // Get the order object
    $order = wc_get_order($order_id);
    if (!$order) return;

    // 1. Extract order data you need
    $order_data = array(
        'order_number' => $order->get_order_number(),
        'order_date' => $order->get_date_created()->format('Y-m-d H:i:s'),
        'customer_email' => $order->get_billing_email(),
        'customer_name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
        'total' => $order->get_total(),
        'currency' => $order->get_currency(),
        'items' => array()
    );

    // Add line items to the data array
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        $order_data['items'][] = array(
            'product_name' => $item->get_name(),
            'product_sku' => $product ? $product->get_sku() : '',
            'quantity' => $item->get_quantity(),
            'price' => $item->get_subtotal()
        );
    }

    // 2. Convert order data to XML
    $xml = new SimpleXMLElement('<order/>');
    array_to_xml($order_data, $xml);
    $xml_string = $xml->asXML();

    // 3. Send XML via POST request
    $external_url = 'https://your-external-server.com/receive-order.php'; // Replace with your server URL
    $response = wp_remote_post($external_url, array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=utf-8'
        ),
        'body' => $xml_string,
        'timeout' => 15, // Adjust timeout as needed
        'sslverify' => true // Set to false only if you're testing with a self-signed cert (not recommended for production)
    ));

    // 4. Log results for debugging
    if (is_wp_error($response)) {
        error_log('Failed to send order ' . $order_id . ': ' . $response->get_error_message());
    } else {
        error_log('Order ' . $order_id . ' sent successfully. Response code: ' . wp_remote_retrieve_response_code($response));
        // Optional: Log the full response body if needed
        // error_log('Response body: ' . wp_remote_retrieve_body($response));
    }
}

// Helper function to convert array to XML
function array_to_xml($data, &$xml) {
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            if (!is_numeric($key)) {
                $subnode = $xml->addChild("$key");
                array_to_xml($value, $subnode);
            } else {
                $subnode = $xml->addChild("item");
                array_to_xml($value, $subnode);
            }
        } else {
            $xml->addChild("$key", htmlspecialchars($value));
        }
    }
}

3. Key Notes & Customizations

  • Adjust Data Fields: Modify the $order_data array to include any other order details you need (shipping address, payment method, etc.—check WooCommerce's WC_Order documentation for all available methods).
  • XML Structure: The array_to_xml helper will create a nested XML structure matching your array. If you need a specific XML schema, you can manually build the XML string instead of using the helper.
  • Error Handling: The code logs errors to WordPress's debug log (enable debug mode in wp-config.php with define('WP_DEBUG', true); and define('WP_DEBUG_LOG', true); to see these logs).
  • Security: Never disable sslverify in production—make sure your external server has a valid SSL certificate.
  • Performance: If your external server is slow, consider offloading this task to a background job (using something like WP Cron or a queue system) so it doesn't slow down the order confirmation page for users.

4. Testing the Setup

  • Create a test order in your WooCommerce store.
  • Check your WordPress debug log (usually in wp-content/debug.log) to confirm the request was sent.
  • Use a tool like Postman or a mock server to verify that the XML is received correctly with all the data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:17:10