Search

How to Integrate WooCommerce & an External Order Management System

Listen to this article

woocommerce-order-management-integrationWhat constitutes an e-Commerce store? You have products (of course), which are the core of your store. You have associated prices, taxes, payment gateways, sales, coupons and so on. For every purchase made, you have invoices and orders. In an e-Commerce store based on WordPress, your e-Commerce plugin would manage all of the said functionality. So, WooCommerce would manage all of this.

When you think about it, managing product information, such as description, pricing, sales, are the primary responsibilities of an e-Commerce plugin like WooCommerce. Whereas, invoices, order management, shipment tracking, become part of peripheral responsibilities. WooCommerce handles products well. You can set up various types of products (some using extensions), add sale banners, link related products, categorize and tag products, and manage purchases using various payment methods. It makes the task of a buyer real simple.

When it comes to admin activities, the task is a bit tricky, because your options are limited. Several WooCommerce store owners prefer integrating external services. For example, a client needed e-conomic, an external accounting system, to be integrated with WooCommerce. This was achievable, because e-conomic provided the needed API.

Similarly, if a system has a ready API, you could integrate it with the WooCommerce plugin. In this article, we’ll explore how to integrate an external order management system with WooCommerce.

[space]You might also like 6

Integrating WooCommerce with an Order Management System

When it comes to order management, the data which is part of a WooCommerce order, should be sent across to the external system. Let’s assume, that your Order Management system offers an API, which accepts order details (as listed below) and processes it.

Details which can be sent to the external system:

  • Customer e-mail (customer_email)
  • Customer Phone (customer_phone)
  • Billing Details
    • First Name (bill_firstname)
    • Last Name (bill_surname)
    • Address Line 1 (bill_address1)
    • Address Line 2 (bill_address2)
    • City (bill_city)
    • State (bill_state)
    • ZIP Code (bill_zip)
  • Shipping Details
    • First Name (ship_firstname)
    • Last Name (ship_surname)
    • Address Line 1 (ship_address1)
    • Address Line 2 (ship_address2)
    • City (ship_city)
    • State (ship_state)
    • ZIP Code (ship_zip)
  • Shipping Method (shipping_type)
  • Shipping Cost (shipping_cost)
  • Item SKU (item_sku)
  • Item Price (item_price)
  • Quantity (quantity)
  • Transaction ID/Key (transaction_key)
  • Coupon Code (coupon_code)

[space]

Send Order Details to an External System

To send details from WooCommerce to this external order management system, you have to use cURL. For this, use the below code, by adding it to functions.php of your theme or a custom plugin (recommended).

/* after an order has been processed, we will use the  'woocommerce_thankyou' hook, to add our function, to send the data */
add_action('woocommerce_thankyou', 'wdm_send_order_to_ext'); 
function wdm_send_order_to_ext( $order_id ){
    // get order object and order details
    $order = new WC_Order( $order_id ); 
    $email = $order->billing_email;
    $phone = $order->billing_phone;
    $shipping_type = $order->get_shipping_method();
    $shipping_cost = $order->get_total_shipping();

    // set the address fields
    $user_id = $order->user_id;
    $address_fields = array('country',
        'title',
        'first_name',
        'last_name',
        'company',
        'address_1',
        'address_2',
        'address_3',
        'address_4',
        'city',
        'state',
        'postcode');

    $address = array();
    if(is_array($address_fields)){
        foreach($address_fields as $field){
            $address['billing_'.$field] = get_user_meta( $user_id, 'billing_'.$field, true );
            $address['shipping_'.$field] = get_user_meta( $user_id, 'shipping_'.$field, true );
        }
    }
    
    // get coupon information (if applicable)
    $cps = array();
    $cps = $order->get_items( 'coupon' );
    
    $coupon = array();
    foreach($cps as $cp){
            // get coupon titles (and additional details if accepted by the API)
            $coupon[] = $cp['name'];
    }
    
    // get product details
    $items = $order->get_items();
    
    $item_name = array();
    $item_qty = array();
    $item_price = array();
    $item_sku = array();
        
    foreach( $items as $key => $item){
        $item_name[] = $item['name'];
        $item_qty[] = $item['qty'];
        $item_price[] = $item['line_total'];
        
        $item_id = $item['product_id'];
        $product = new WC_Product($item_id);
        $item_sku[] = $product->get_sku();
    }
    
    /* for online payments, send across the transaction ID/key. If the payment is handled offline, you could send across the order key instead */
    $transaction_key = get_post_meta( $order_id, '_transaction_id', true );
    $transaction_key = empty($transaction_key) ? $_GET['key'] : $transaction_key;   
    
    // set the username and password
    $api_username = 'testuser';
    $api_password = 'testpass';

    // to test out the API, set $api_mode as ‘sandbox’
    $api_mode = 'sandbox';
    if($api_mode == 'sandbox'){
        // sandbox URL example
        $endpoint = "http://sandbox.example.com/"; 
    }
    else{
        // production URL example
        $endpoint = "http://example.com/"; 
    }

        // setup the data which has to be sent
    $data = array(
            'apiuser' => $api_username,
            'apipass' => $api_password,
            'customer_email' => $email,
            'customer_phone' => $phone,
            'bill_firstname' => $address['billing_first_name'],
            'bill_surname' => $address['billing_last_name'],
            'bill_address1' => $address['billing_address_1'],
            'bill_address2' => $address['billing_address_2'],
            'bill_city' => $address['billing_city'],
            'bill_state' => $address['billing_state'],
            'bill_zip' => $address['billing_postcode'],
            'ship_firstname' => $address['shipping_first_name'],
            'ship_surname' => $address['shipping_last_name'],
            'ship_address1' => $address['shipping_address_1'],
            'ship_address2' => $address['shipping_address_2'],
            'ship_city' => $address['shipping_city'],
            'ship_state' => $address['shipping_state'],
            'ship_zip' => $address['shipping_postcode'],
            'shipping_type' => $shipping_type,
            'shipping_cost' => $shipping_cost,
            'item_sku' => implode(',', $item_sku), 
            'item_price' => implode(',', $item_price), 
            'quantity' => implode(',', $item_qty), 
            'transaction_key' => $transaction_key,
            'coupon_code' => implode( ",", $coupon )
        );

            // send API request via cURL
        $ch = curl_init();

        /* set the complete URL, to process the order on the external system. Let’s consider http://example.com/buyitem.php is the URL, which invokes the API */
        curl_setopt($ch, CURLOPT_URL, $endpoint."buyitem.php");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
        $response = curl_exec ($ch);
    
        curl_close ($ch);
        
        // the handle response    
        if (strpos($response,'ERROR') !== false) {
                print_r($response);
        } else {
                // success
        }
 }

The above code is a very basic example. You can enhance it, based on the APIs available, or as per your requirements. Also, this can be used only to send order details from WooCommerce to an external system (and not vice versa). To send data back to WooCommerce, you will need to make use of additional API, the system provides.

[space]

Do you intend to use an external Order Management system with WooCommerce? Hope this article can get you started. If you have any doubts, you can write them to me, via the comment section below.

[freepik]

You might also like 6

Praveen Chauhan

Praveen Chauhan

22 Responses

  1. Can I use similar method to update order coming from external system into my woocommerce site – essentially I have a ecommerce store but also sell with other market place vendors who allow API integration… I need to write code so that when they take can order it should update my system as well…

    1. Hi Aaron,

      The key is to replace the endpoints (I’m sure you’ve done that), and to replace the data being sent (keys for $data), with values the API would accept.

  2. Hello,
    thanks for inspiration. But can I ask from where you filled the $address array? Because in my code I have problems with getting data which are stored in your $address variable.

  3. I have pasted the code at the bottom of my functions.php doc…what do I do now? Or is it good to go?

    I am trying to use Shopatron as the order management system and they have API’s but I cannot find anyone online with the same problem. I have downloaded a theme and woocommerce but am not sure where to go from here.

    1. Kelley,

      I’ve provided a template. What you’ll need to do, is replace the endpoints, and the data being sent (keys for $data), with values Shopatron’s API would accept.

  4. Hi

    I have been studying the code above. I have one question; I have a woocommerce site, and I got a airtme API from an external company..basically what the API does is to topup airtime, a user would buy airtime(in this case it will be a normal woocommerce product) and then from there I need the API to invoked, and then return to the site to checkout.

    I am not sure if this makes sense?

    Thanks in advance
    Katlego Ntimane

  5. I make dresses and sell them on my WooCommerce site. Now third party online retailers want to sell my goods and have ME drop-ship to their customers. I have found plugins to automatically send inventory update .csv files in cron nightly, and also to import orders. But the order import does not deduct from inventory, nor will it invoice or even charge a credit card. Any advice?

  6. I want to send Woocommerce subscription checkout and register(name, email, address, password..etc) details to external api at the time of checkout. Please suggest me any solution

  7. i delete phone no and city /state field from checkout page and in order mail not dispaly any shipping information.i dont know why this issue is genereate?

  8. Great resource! Thanks for the pointer..

    Is there as simple of a solution available for using an external database for items? Not importing a csv, but using an external item API to retrieve one or many items?

  9. So..
    I import the entire item table to load WC for the first time, and do periodic (daily late at night..) updates.

    Then, on an ongoing basis, what function could I then use to check external stock (multiple locations too!) for whether or not an item is available for sale.

    Oh yeah.. I’m a complete noob with WP & WooCommerce, but I have been a developer since 1985..

  10. I’d been trying to find a solution to hook up WooCommerce to a distributer of mine for hours, and this was what I needed to find! Thank you so much!

    I changed the trigger to woocommerce_order_status_completed. There’s a free plugin called WooCommerce autocomplete, which will then only trigger this function if payment was successful.

  11. I know that it has been a long time since you posted this, but I don’t seem to have access to the shipping item and the items data with your code.

  12. Hi Praveen,

    Hi want to send Variations as well, but I don’t think that you have not speak about that. So, it’s an excellent article, very clear !

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads