Friday, March 29, 2024

Using the WooCommerce Rest API

WooCommerce is popular a free eCommerce plugin for selling just about anything in WordPress. Currently about 30 percent of all online stores are powered by Woocommerce. On strong selling feature is the hundreds of free WordPress extensions available for it. Another is its API, which allows the programmatic reading, creating, updating, and deleting of stored Woocommerce data using the JSON format. In today’s article, we’ll be exploring how to fetch various Woocommerce product components using the the WooCommerce-REST-API-Client-Library.

Connecting to the API

Being a RESTful Web API, all product details are fetched via a URL such as “http://www.example.com/wc-api/v1/orders”. However, the Woocommerce Rest API requires us to authenticate ourselves by providing the API Consumer Key as the username and the API Consumer Secret as the password. How you supply these parameters depends on whether you are accessing the API over HTTPS or regular HTTP. In the case of HTTPS, The API uses HTTP Basic Auth:

curl https://www.example.com/wc-api/v3/orders \
    -u consumer_key:consumer_secret

If you don’t want to purchase a certificate for SSL, you must use something called OAuth 1.0a “one-legged” authentication. This is a standard that ensures that your credentials cannot be intercepted. It’s a pretty complicated process that I won’t bore you with here! Suffice to say, if you choose to access the API over HTTP, you may want to use a standard OAuth 1.0a library to handle the authentication.

Another approach is to use the WooCommerce-REST-API-Client-Library. It’s a collection of classes abstracts the REST API so that you call its methods just as you would on any class. Here’s some code that retrieves the client object:

function get_wc_api_client() {
    // Include the client library
    require_once 'woocommerce-api.php';

    $consumer_key = 'ck_74abbbd83348c96bfcdf99ac8cdb92ccd88314f2';

    $consumer_secret = 'cs_be37bc5dfb445fbad4402fbad28030a76414fbc9';
   
    $store_url = 'http://mysite.com/'; // Add the home URL to the store you want to connect to here

    $options = array(
            'debug'           => true,
            'return_as_array' => false,
            'validate_url'    => false,
            'timeout'         => 30,
            'ssl_verify'      => false,
    );

    return new WC_API_Client( $store_url, $consumer_key, $consumer_secret, $options );
}

The above options are quite useful; here is what each of them do:

  • debug (default false) – set to true to add request/response information to the returned data. This is useful for troubleshooting errors.

  • return_as_array (default false) – all methods return data as a stdClass by default, but you can set this option to true to return data as an associative array instead.

  • validate_url (default false) – set this to true to verify that the URL provided has a valid, parsable WooCommerce API index, and optionally force SSL when supported.

  • timeout (default 30) – set this to control the HTTP timeout for requests.

  • ssl_verify (default true) – set this to false if you don’t want to perform SSL peer verification for every request.

Class Breakdown

Version two contains a lot of additional functionality over version one. So much so, that methods are now organized into separate classes by common functionality for products, customers, orders, etc…

woo

Most of the above classes have a get() function. These may accept an ID to fetch a specific product or be omitted to get all products. The second argument is an array of acceptable Woocommerce endpoint args, like “filter[]”:

public function get( $id = null, $args = array() ) {

  $this->set_request_args( array(
         'method' => 'GET',
         'path'   => $id,
         'params' => $args,
  ) );
 
  return $this->do_request();
}

Fetching Products

Let’s invoke the product class’s get() function to retrieve all of the products for a store:

$products = $client->products->get();

That returns an array of products. Unlike the Woocommerce REST API, the client get() function either returns a stdClass object or as an associative array, depending on the value of the return_as_array option. If you still want JSON output, you just have to run the object(s) through json_encode(). That will produce something like the following for each product:

{
  "product": {
    "title": "Premium Quality",
    "type": "simple",
    "regular_price": "21.99",
    "description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.",
    "short_description": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.",
    "categories": [
      9,
      14
    ],
    "images": [
      {
        "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg",
        "position": 0
      },
      {
        "src": "http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg",
        "position": 1
      }
    ]
  }
}

Conclusion

I find the Woocommerce Rest API and Woocommerce Rest API Client v2 to be a great pairing. In the next installment, I’d like to show you how to utilize the Woocommerce API classes to fetch extended product attributes.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured