WooCommerce REST API Client Library

10 February

WooCommerce REST API Client Library

With WooCommerce 2.1 now out and about, it brings with it an array of new features and changes. One of these new features is the all new WooCommerce REST API.

The WooCommerce REST API comes bundled with WooCommerce 2.1+ and allows you all sorts of API calls to interact with your WooCommerce store data. You can get access to your Order, Customer, Coupon, Product and Reporting data all through the API.

Having it be a new API interacting with it can sometimes be a difficult task, that is why most software with API’s offer some sort of API Client Library which makes interacting with the API a breeze.

I have been spending quite a lot of time playing around and testing the API since its first commit into WooCommerce core and due to this built quite an easy to use and extendable API Client Library that I used to test and later on refined to make available to the public for use.

The WooCommerce REST API has two authentication methods, one legged oAuth 1.1, and Basic HTTP authentication, the method being used is all dependent on whether your WooCommerce store has a valid SSL certificate and if you have secure checkout enabled. I have developed the WooCommerce REST API Client Library to support both methods as the WooCommerce REST API require you to use oAuth when you have no valid SSL certificate and Basic authentication when you have secure checkout enabled with a valid SSL certificate.

Enabling the WooCommerce REST API

In order to enable the WooCommerce REST API and to start using it you will need to enable it in your WooCommerce settings.

This can be done by going to WooCommerce -> Settings -> General tab in the WordPress admin area, and then making sure the Enable the REST API option is checked. This should be checked by default.

Generating API Keys

In order to access data through the WooCommerce REST API you will require a Consumer Key and Secret. This is used to authenticate the API calls and to ensure that the call being made can access the data it is trying to access.

API Consumer Keys and Secrets are tied to users, which allows WooCommerce to restrict access to certain data based on the user role, so for instance if you set up the user to only have access to products and they try to access orders with their API details they will not be able to.

To generate API details head to either Users -> All Users or Users -> Your Profile in the WordPress admin area. If you followed the Users -> All Users path you will need to search for the user you want to generate API credentials for and edit it.

Once you are on the edit profile page, scroll down to the bottom of the page, there should be a checkbox to generate API Keys, check this and save the profile. Once the page refreshes, if you scroll down again there will be a Consumer Key and Consumer Password listed, and if you are a site admin you will also have the option to select read/write access.

Communicating with the WooCommerce REST API

Once you have the Consumer Key and Consumer Secret you are now ready to start interacting with the WooCommerce REST API.

This is where the WooCommerce REST API Client Library comes into play, you can now head to the WooCommerce REST API Client Library page on GitHub and download the PHP client library from there.

Once you have downloaded the PHP client library you will find a couple of file, the important one here is class-wc-api-client.php, this is the file you will need to use to be able to make use of the client library and make calls to the WooCommerce REST API. There is also a folder called example which shows you how to interact with the client library in order to make calls to your WooCommerce store.

Using the WooCommerce REST API Client Library

If the example code provided with the client library is not enough and the documentation listed on the GitHub page does not explain it well enough here is a quick intro on how to get started using the client library with the WooCommerce REST API.

Connecting to the REST API
In order to connect to the REST API of your store you will need to have the URL to your store as well as your Consumer Key and Consumer Secret ready. Use the following PHP code to include the client library and access the WooCommerce REST API of your store. Be sure to use https if you have secure checkout enabled on your site.

Making a call to the REST API
Once the client library has been initiated you can use the api object to make calls to the WooCommerce REST API, all the calls will return the data in JSON decoded format.

And that is it, for more documentation on all the available function calls, and how to call custom API endpoints added through extensions etc please see the README.md file on the GitHub page

Contributions are welcome, if you spot a bug or would like to add an enhancement feel free to fork and send a pull request.

Tags: , ,

About this site

This site is hosted on Digital Ocean's super fast SSD based cloud servers. Sign up for your own Digital Ocean server and get $10 free credit. Set up a super fast WordPress site with just a couple of clicks.

Subscribe to my newsletter to receive the latest WooCommerce tutorials and news in your inbox. I promise I won't spam, I hate it as much as anyone else out there.

71 Responses to “WooCommerce REST API Client Library”

  1. Kathy 2014/03/03 at 15:44 #

    Hi Gerhard,

    I’m trying to wrap my head around this. Could you clarify something for me? The API Client Library is for building something on a 3rd party site to interact with your store? Whereas, if I want to handle notifications from a 3rd party site I you should extend the WC_API_Resource class?

    Thanks,
    -Kathy

    • Gerhard 2014/03/04 at 10:46 #

      Hi Kathy

      Yes this is exactly what this is for, for interacting with the WooCommerce API, if you want to build a custom API listener have a look at how the payment gateways do it.

      Eg.

      // This will trigger on http://example.com/wc-api/custom_api_call/
      add_action( 'woocommerce_api_custom_api_call', 'check_custom_api_call' );
      function check_custom_api_call() {
      // Do your API call stuff here
      }

      • Kathy 2014/03/04 at 11:05 #

        Awesome! Thanks Gerhard. That actually looks 100x simpler than what I was envisioning with end-points and much closer to what I had done previously.

      • John 2015/01/30 at 19:49 #

        Hi Gerhard,

        I’ve read this a couple of times and trying to understand, can I use this to add an API to my woocommerce payment gateway? If the payment gateway in woocommerce doesn’t have a certain API that is a newer feature so it wasn’t put in, could I somehow add that API? Even if I had to make some changes or edits and such, I feel like it has to be possible. The payment gateway has their published API’s on their site with instructions, tutorials and the code for each. I know this is an older post, so hopefully you still get this1

        Thanks,

        John

  2. craig r 2014/03/03 at 18:57 #

    I feel like you should be given a little more credit for this than you have received. When I saw ‘no comments yet’ I was truly surprised. I was expecting a million stupid questions. :) . Anyways, thanks for working on this. It looks like it will be pretty cool.

    Thanks,
    Craig

    • Gerhard 2014/03/04 at 10:43 #

      Hi Craig, thank you very much.

  3. SimonR 2014/03/04 at 10:36 #

    Hello, I want to use the API, but my results always: {“errors”:[{“code”:”404″,”message”:”cURL HTTP error 404″}]}

    I created the keys and the url is http://localhost:81/wordpress/ . I enabled the RestAPI checkbox. Must i install more … ?

  4. August 2014/03/05 at 18:26 #

    Hey Gerhard. This is awesome. Thanks for the article.

    One question: when using get_order( $order_id ) in the API, does this call give access to any downloadable files that were attached to the order?

    I have a shop setup where I’ll need to give access to a third-party site to only specific orders, but I’d like for them to be able to get the same downloadable files from the original order. Is this possible with the current API?

    • Gerhard 2014/03/07 at 07:45 #

      Hi August

      At present no, however there is a open github issue on the WooCommerce github repo that is requesting an endpoint to get downloadable data from an order. This is something that WooCommerce will have to implement first before you can get access to that data.

  5. Kelowna 2014/03/07 at 04:28 #

    I’m trying to access my woocommerce store on a server from my local host and set up everything in the example php file and got:

    stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 0 [message] => cURL HTTP error 0 ) ) )

    Any idea?

    • Gerhard 2014/03/07 at 07:43 #

      Hi Kelowna

      Under Settings -> Permalink, make sure it is not set to default. The REST API require permalinks to be enabled so try setting it to something like Day and name.

  6. Kelowna 2014/03/07 at 22:11 #

    Hey Gerhard,
    It is set to Day and Name and that is what I receive :( Any other possibility for that sort of error?
    thanks,
    –k

  7. Sivabalan 2014/03/27 at 11:31 #

    I got the error “stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 404 [message] => cURL HTTP error 404 ) ) )”. Idownloaded the code and replaced the keys. But i did get anything. Please help me

  8. Cesar 2014/04/01 at 21:26 #

    Hey Gerhard,

    Thank you very much for the article and congratulations for the work made.

    I am trying to work with your samples, and so far I am getting all products, but I would like to know how I can do to get the cart, login a user and finally process a payment.

    Any information or advice that you can provide in the subject would be very appreciated.

    Best,

    Cesar

    • Gerhard 2014/06/18 at 08:23 #

      Hi Cesar, sorry for the late response, however the API cannot be used to add items to a cart and process a payment. It is only meant to give you access to your WooCommerce store data from a 3rd party site/service/app.

      • Cesar 2014/06/18 at 16:47 #

        Thank you for your answer Gerhard.

        We found a different way to work with the Woocommerce classes inside jQuery Mobile to be able to add items to cart and process payment.

        Keep the good work.

        Best,

        Cesar

      • Kathy 2014/06/18 at 16:58 #

        Hi Gerhard, At WordCamp Chicago I heard there was a “create order” function in the works. Will you be posting about that any time soon? cheers!

  9. Keesjan 2014/04/15 at 09:39 #

    Hi Gerahard,
    is it possible to share woocommerce user-email name and passwords via the api with another application in a secure way?

  10. Christophe 2014/04/16 at 21:39 #

    I wish Woocommerce also added an API function to create coupons; seems there are only functions to get coupons at the moment.

    Nice work on the library though!

  11. Christophe 2014/04/16 at 22:07 #

    And seems you are involved in bringing this coupon functionality out as well. :-) Thanks!

    https://github.com/woothemes/woocommerce/pull/5044

    • Gerhard 2014/09/09 at 12:39 #

      Hi Christophe, that is correct I implemented the coupons PUT/POST/DELETE functionality that is due to be released with WC 2.2 in the next week or so :)

  12. babu lal 2014/05/09 at 09:27 #

    i ’m trying to access my woocommerce store on a server from my local host and set up everything in the example php file and got:

    stdClass Object
    (
    [errors] => Array
    (
    [0] => stdClass Object
    (
    [code] => 404
    [message] => cURL HTTP error 404
    )

    )

    )

    Any idea?

  13. Craig 2014/06/20 at 07:42 #

    Hi, is it possible to use the api to select products based on one or more assigned categories? Cheers Craig.

  14. Paul Singleton 2014/06/21 at 12:22 #

    Hi Gerhard,

    The direction of the Rest API seems to be guided towards store manager roles for backend analysis.

    I want to also contribute towards the Rest API, but wanted to ask if you think that this could be also designed to allow apps to call the API service for example: http://api.store.co.uk/products/add/productid=1234

    Thanks in advance,

    Paul

    • Gerhard 2014/09/09 at 12:28 #

      Paul, this is part of WooCommerce 2.2 which is due in the next week or two, which will enable you to add/remove/update products, orders, coupons etc.

  15. willy 2014/06/26 at 17:29 #

    Hello.. I have a problem, when try to getProducts returns only to 6 products, and i see 14 in thr getProducts/count
    Thanks

  16. Jack 2014/07/02 at 14:10 #

    Gerhard,

    While connecting to the REST API, I received the following disquieting response:

    stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 301 [message] => cURL HTTP error 301 ) ) )

    I’ve already set the permalink as you suggested.

    Any suggestions would be appreciated.

    Thank you.

  17. Dinnae 2014/07/11 at 08:21 #

    Hi Gerhard!

    Please forgive me, I’m feeling confused. :) (that’s always a good way to start a post, isn’t it?) Wondering if you can help me understand why or why not (and WHERE) a woo shop should use the REST API? The documentation does not explain the parameters around situations we should or shouldn’t use it. I understand it’s used to access data via a 3rd party site, but which ones? There’s no specificity, and I’m feeling confuzzled. 😉 And I understand it probably has very broad use, but even an example or two would help me get my head around it.

    Thank you!

    • David 2014/08/29 at 13:17 #

      Example: Our shop is on an external web server and we use the API to enable reading and manipulating orders directly from the ERP-system and the intranet.

  18. David 2014/08/07 at 15:24 #

    Hello Gerhard, very nice work, thank you.

    Our orders do contain custom fields – is it possible to get those via the API? I googled quite a bit for this, but did not find a solution.

    • David 2014/08/29 at 10:21 #

      Was simpler than I thought. In class-wc-api-orders.php I added

      ‘custom_field’ => get_post_meta($order->id, ‘custom_field’,true)

      to the $order_data array starting around line 113

      and everything works like a charm.

  19. Azamat 2014/08/13 at 11:58 #

    Kathy u can modify client api with original doc there http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#755-894.

  20. David 2014/08/29 at 17:45 #

    One more question.

    I can set customer notes using update_order – but it makes them private notes.

    What I need is to update the order with “real” customer notes so that the notification email is triggered.

    I found out that all notes have “customer_note”:true or false and those updated by the API are false, means private. I tried to hack class-wc-api-orders.php to make them all true but I couldn’t make it. If you, Gerhard or anyone else could give me a hint to the right direction how to do this, I would be very thankful. (Well, I already am for the API)

    • David 2014/09/01 at 11:26 #

      Made it: add in class-wc-api-orders.php around line 281:

      if ($data[‘kundenhinweis’] != ”) { $order->add_order_note( $data[‘kundenhinweis’], 1 ); }

      and of course, in my script, something like:

      $orders = $wc_api->update_order( $id, $data = array(‘status’ => $status, ‘note’ => ‘Via Intranet Script – ‘, ‘kundenhinweis’ => $kundenhinweis) );

  21. John 2014/09/10 at 17:20 #

    Hi Gerhard, thanks for this! I am trying to write a javascript (angular) application that can access the API. I’m trying to figure out how I can authenticate without exposing the client secret within my JavaScript. Could this library be used in some way to do that?

    • Gerhard 2014/09/11 at 11:04 #

      John I am pretty sure it is possible, this library takes care of the authentication, so if you can do a custom ajax endpoint that calls the library then you can just store the api credentials in the db and send it through when you call the library on the ajax action.

  22. charls 2014/09/12 at 08:43 #

    Hello,

    i was wondering about this api.

    when i was performing this code. it gives me error.
    print_r( $wc_api->get_products() );
    //error
    stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => 0 [message] => cURL HTTP error 0 ) ) )

    but when i use this code:
    print_r( $wc_api->get_products_count() );
    //success
    stdClass Object ( [count] => 483 )

    it will print the right amount of the product, how was that happened? any solution for this?

  23. ravi 2014/09/12 at 15:36 #

    I am trying to authenticate using objective C code, but it says that i need oauth_consumer_keys. I had a look at the woocommerce docs and they said that if using HTTPS should do the trick.
    Do i need an oauth client to actually get my things started ? If yes then can i use oauth 2 since that’s the latest.
    Thanks for your guidance.

  24. Cezar 2014/09/30 at 08:16 #

    Dear Gerhard,
    Nice job ! thanks for sharing this solution.

    Question1 :
    When I am doing call like this: $wc_api->get_products( $params = array( ‘filter[sku]’ => ‘111’ ) );
    I still get all the results. Do you have any idea why ?

    Question2:
    Understand that updating products option is not available yet – (we still use V1) am I right ?

    best best regards
    Cezar

  25. Rajib 2014/10/02 at 07:58 #

    Hi

    I am getting [code] => 401 [message] => cURL HTTP error 401 in one server with below cURL version

    cURL support enabled
    cURL Information 7.19.7

    whereas i am getting proper response in another server with bellow setting

    cURL support enabled
    cURL Information 7.30.0

    Is it the reason for 401 code or something else

    Thank you

  26. Paolo 2014/10/04 at 13:40 #

    Hi !

    How do I use filters , example if I only want products from one category or status, Where do I find docs ?

    // This fetch limit of 50 and values id, status
    $result_products = $wc_api->get_products(array( ‘filter[limit]’ => 50 , ‘fields’ => ‘id,status’ ));

    Regards

  27. Rohit 2014/10/09 at 09:56 #

    i have 2 sites and i want to show products from 1 site to another site i try it with i frame its done well but the problem is i also want that i can get know from which site the buyer buy the product.
    any help ????

  28. Abi Ekundayo 2014/10/14 at 15:47 #

    Hi Guys,

    I am new to wordpress and woocommerce. I am currently trying to create order programmtically from objective C. I have tried using HTTP POSTs with raw data input and I also tried extending the REST API in functions.php by calling $order = wc_create_order(); and adding the product etc.

    While I am able to create the order each time the price is always 0. So I am assuming I am doing something very wrong. Can anyone please point me in the right direction.

    Regards,

    Abi

  29. felipe fernandez 2014/11/10 at 20:22 #

    It is possible create, update or delete categories and productos via API?

  30. Paolo 2014/11/17 at 19:23 #

    Hi !

    I have read the docs but can’t find how to get the products by tags ? There is a part in
    class-wc-api-products.php , but i include the filter[‘type’] but I seems to be something else or

    Regards

    private function query_products
    ..
    ..
    if ( ! empty( $args[‘type’] ) ) {

    $types = explode( ‘,’, $args[‘type’] );

    $query_args[‘tax_query’] = array(
    array(
    ‘taxonomy’ => ‘product_type’,
    ‘field’ => ‘slug’,
    ‘terms’ => $types,
    ),
    );

    unset( $args[‘type’] );
    }

    $query_args = $this->merge_query_args( $query_args, $args );

  31. sureshklumar 2014/11/25 at 15:54 #

    Hi Gerhard,
    Am using Rest api, i get the products using get products, now i can add orders to woocommerce, i seen only update and delete order endpoints, but i need create order details and update order workflow. If you provide examples for both create and update order means its more useful for me. Quick response is more and very helpful for my side.
    Thanks
    Sureshsan

    • Gerhard 2014/11/26 at 08:08 #

      Hi Sureshsan

      The endpoint for creating and updating an order is the exact same, it is just the method that changes, ie for creating you would make a PUT call, for updating a POST call, the structure of the data is the same, with the exception of you can omit the ID when creating an order.

  32. Agli 2014/12/16 at 01:18 #

    Hi,
    i am planning to develop a native mobile Android App for WooCommerce shops.

    I had a look at their REST API documentation here: http://docs.woocommercev2.apiary.io/ I already started to test it but when i do different calls

    GET /orders let’s say it returns all the orders of the shop.

    Does anyone have any idea how can i develop a enduser app using their API.

    for example:

    GET /products
    PUT /order (create a order for the logged in User)

    GET /order (get orders of the logged in User)

    Any idea is appreciated :)

    Thanks in advance.

  33. Franck 2014/12/18 at 07:04 #

    Hello !

    I am readinf the rest API v2 documentation (http://docs.woocommercev2.apiary.io/) but I cannot find the required json data structure of the post requests -for a new order for instance-.

    Could you advise me about where I can find more info about the api available POST endpoints and expected json structues ?

    Franck

  34. Jacques 2015/01/23 at 12:24 #

    Hi Gerhard,

    Thank you for this post! Thank you also for the php wrapper. Works like a charm.

    Greetings from Belgium.

  35. Harry 2015/03/01 at 15:29 #

    Hi Sorry to be the person asking silly questions, but I gotta start somewhere. If I want to display products from one site, on another, how do I do this with the woo rest api. I have added my secret and consumer keys, but where do I actually place the class-wc-api-client.php, and how do I use the example to actually display content? Should I be adding to my page templates?

    Again sorry if i’m asking obvious questions.

    Cheers

    Harry

  36. Duy Tan 2015/03/12 at 08:59 #

    Dear,
    I want to list all products by categories. But i don’t know how to filter.
    Please help me.
    Thank you!

  37. Dan Allen 2015/03/20 at 21:06 #

    Hi, Congratulations on your excellent work on the api.

    Question: can you confirm basic authentication will not work if when woocommerce is running under php with fastcgi? Can you say that is false?

    Any information you can provide will be much appreciated.

    • Gerhard 2015/03/21 at 09:14 #

      Hey Dan, I am not aware of any issues with basic auth and fast-cgi. As you using basic auth with SSL? As that is only supported when you connect via SSL to the endpoint, ie your endpoint must be running over https with a valid SSL certificate on the server.

  38. Dan Allen 2015/03/21 at 17:52 #

    Thank you for responding. The api index says ssl is not enabled, but a certificate is installed, and when I check the domain for ssl, using this link, it comes back saying the SSL certificate is installed correctly.
    http://www.networking4all.com/en/support/tools/site+check/report/?fqdn=launchpad-001.com&protocol=https

    The woocommerce plugin is running at https://launchpad-001.com/_firingRange/swn. Here is part of the api index coming back.
    [weight_unit] => kg [dimension_unit] => cm [ssl_enabled] => [permalinks_enabled] => 1 [links] => stdClass Object ( [help] => http://woothemes.github.io/woocommerce/rest-api/ ) ) ) ) stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code] => woocommerce_api_authentication_error [message] => Consumer Key is missing ) ) )

    • Gerhard 2015/03/27 at 12:24 #

      Hey Dan, from the response ssl_enabled is not set meaning your site is not installed or you dont have ssl enabled on your installation, it might be on the server but not enabled on that installation.

  39. Dan Allen 2015/03/21 at 18:03 #

    Since this is a dev site with no real orders, I will share this:
    $consumer_key = ‘ck_166c3047dd5ca2c301b4cb4781355518′;
    $consumer_secret = ‘cs_cf6228bf4ff6b1785bb371f700dbb7cf';
    $store_url = ‘https://launchpad-001.com/_firingRange/swn';

    An image of the API keys is at this link:
    launchpad-001.com/_firingRange/swn/images/woocommerce.png

  40. Dan Allen 2015/03/23 at 02:15 #

    The problem disappeared when I setup a new installation nof WordPress, with no plugins except WooCommerce. My hypothesis is there is a conflict between WC api and at least one of the several dozen other plugins on the target system. Next step is to identify which of those plugins disable the WC API.

  41. Sami 2015/03/26 at 14:22 #

    Hi Gerhard,

    Any idea as to why I am getting only int(1) as a response from the API no matter what call I make? No errors, no nothing, just the number 1.

    Thanks a bunch!
    Sami

    • Gabriel Reguly 2015/04/14 at 01:31 #

      Hi Sami,

      Most likely you have a wrong URL, so cURL is returning 1.

      Like http://example.com/wc-api/V2 (notice the capital V instead of lower case v).

      At least that was my issue.

      What does the browser returns when you paste the URL at it’s address bar?

      Cheers,
      Gabriel

  42. Umakant 2015/04/06 at 07:55 #

    HI Gerhard,

    I want access WooCoommerce REST API , when i want to access then I found {“errors”:[{“code”:”woocommerce_api_authentication_error”,”message”:”oauth_consumer_key parameter is missing”}]} , when i want to access products from REST API in WooCommerce.

    I am using this url http://domainname/wc-api/v2/products.

    Please help me

  43. Ricardo Andramuño 2015/04/11 at 00:50 #

    Gerhard thanks for this client library.
    I am looking for a way to update products stock via REST API with an external app, as I can see in woocommerce site, there are various ways to edit products, orders, etc but there aren’t any of these options in your library.
    Please, can you help me?

  44. Craig Hesser 2015/04/11 at 22:25 #

    Hello, two things
    The first one is simple, the website is not yet published, so you cannot get in without a username and password – if you need one, I will send it to you. Also, when the site is published, it will be at the root directory level, not a subdomain.

    The second one is a nasty one. I have two, and maybe three websites coming up that are all e-commerce in one way or another. The first one – named above – is an online clothing and fashion accessories store with physical products and deliveries, and most likely using PayPal as the payment system – at least at the start. The others will be service and digital download delivery plus service, also probably using PayPal to start with, but totally different from the physical product store.

    I would like to establish a single payment system, (probably in a separate domain, specifically chosen to be the one where I have SSL installed now), and be able to use source keys to bill appropriately for user, amount, details, etc. and transfer to PayPal with payment assigned to the proper store operation.
    Do you think this is feasible with WooCommerce? Are there any instructions already available that would cover this type of installation? And are there any special danger areas to look out for?

    One reason I am considering this is that I have a limited reseller hosting account where only my main domain can have SSL. To get SSL for three (or more) domains, I have to upgrade to a more expensive reseller plan or make two or three new separate accounts. I think that something like that will be even more complicated than the single billing service system I am proposing.

    I would like to hear your opinion?

    Thanks,

    Craig Hesser

  45. luis 2015/04/14 at 15:52 #

    where I leave the downloaded file, in what way?

  46. Larry 2015/04/14 at 21:45 #

    Hi there, where should we put ‘class-wc-api-client.php’ and ‘woocommerce-rest-api.php’ to let the api work?

    Thanks!

Leave a Reply