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.
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.
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);
}
}
woocommerce_payment_complete
to trigger the function when the payment is marked as complete.wc_get_order()
fetches all the order details, such as order ID, customer name, email, and items purchased.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.is_wp_error()
to log any potential issues.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,
],
]);