How to Send WooCommerce Order Details to an External API After Successful Payment

In WooCommerce, you may want to send order details to an external API after a successful payment for various purposes, such as syncing orders with a CRM, creating invoices, or updating an external inventory system.

Steps to Implement

1. Hook into the WooCommerce Payment Complete Action

WooCommerce provides a hook called woocommerce_payment_complete that triggers when an order's payment is marked as complete. This is the perfect hook to send order details to your external API.

2. Prepare Your Code

To implement the feature, we’ll write a custom function that retrieves the order data and sends it to the external API. You can add this code to your theme's functions.php file, a custom plugin, or a WooCommerce-specific plugin file.

Here is an exmple how to use it:

// Hook into WooCommerce after payment completion
add_action('woocommerce_payment_complete', 'send_order_details_to_external_api');

function send_order_details_to_external_api($order_id) {
    // Get the order object
    $order = wc_get_order($order_id);

    // Prepare order data to send to the external API
    $order_data = [
        'order_id'        => $order->get_id(),
        'customer_name'   => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
        'customer_email'  => $order->get_billing_email(),
        'total_amount'    => $order->get_total(),
        'currency'        => $order->get_currency(),
        'payment_method'  => $order->get_payment_method(),
        'order_items'     => [],
    ];

    // Loop through the order items to include product details
    foreach ($order->get_items() as $item_id => $item) {
        $product_name = $item->get_name(); // Get the product name
        $quantity     = $item->get_quantity(); // Get the quantity ordered
        $total        = $item->get_total(); // Get the total for the item

        $order_data['order_items'][] = [
            'product_name' => $product_name,
            'quantity'     => $quantity,
            'total'        => $total,
        ];
    }

    // External API endpoint
    $api_url = 'https://external-api.com/endpoint'; // Replace with your external API URL

    // Prepare the API request
    $response = wp_remote_post($api_url, [
        'method'    => 'POST',
        'body'      => json_encode($order_data),
        'headers'   => [
            'Content-Type' => 'application/json',
        ],
    ]);

    // Check for errors in the response
    if (is_wp_error($response)) {
        error_log('Error sending order data to API: ' . $response->get_error_message());
    } else {
        error_log('Order data successfully sent to external API for Order ID: ' . $order_id);
    }
}

3. Breakdown of Code

  • Hook into WooCommerce: We use woocommerce_payment_complete to trigger the function when the payment is marked as complete.
  • Retrieve Order Details: The function wc_get_order() fetches all the order details, such as order ID, customer name, email, and items purchased.
  • Prepare Data: We then prepare an array containing the required order data, including products, customer info, and totals.
  • Send Data to API: The wp_remote_post() function is used to send the data to the external API. It sends the request as a POST method with the application/json header.
  • Handle Response: We handle both success and error responses using is_wp_error() to log any potential issues.

4. Test the Integration

  • Ensure the external API is reachable and returns the expected response.
  • Test with a sandbox payment method or real transaction to confirm that the data is sent to the external API.

5. Security Considerations

  • Sanitize and Validate: Ensure the data being sent to the API is sanitized and validated, especially if it contains sensitive customer details.
  • API Authentication: If the external API requires authentication (such as an API key or token), be sure to add the necessary authentication headers securely.

For example, you can add an Authorization header to your wp_remote_post call:

$api_key = 'your_api_key';
$response = wp_remote_post($api_url, [
    'method'    => 'POST',
    'body'      => json_encode($order_data),
    'headers'   => [
        'Content-Type'   => 'application/json',
        'Authorization'  => 'Bearer ' . $api_key,
    ],
]);

מאמרים קשורים

Made with  by 1WebCenter.com

תפריט נגישות