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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Include the client library | |
require_once 'class-wc-api-client.php'; | |
$consumer_key = 'ck_fcedaba8f0fcb0fb4ae4f1211a75da72'; // Add your own Consumer Key here | |
$consumer_secret = 'cs_9914968ae9adafd3741c818bf6d704c7'; // Add your own Consumer Secret here | |
$store_url = 'http://localhost/'; // Add the home URL to the store you want to connect to here | |
// Initialize the class | |
$wc_api = new WC_API_Client( $consumer_key, $consumer_secret, $store_url ); | |
?> |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Get all orders | |
$orders = $wc_api->get_orders(); | |
// Output the order object retrieved from the API | |
print_r( $orders ); | |
?> |
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.
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
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
}
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.
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
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
Hi Craig, thank you very much.
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 … ?
Hi Simon, be sure to enable permalinks to fix the error.
Oh ya ! Thats work now! Thank you very much !
Check your mod rewrite configuration http://httpd.apache.org/docs/current/mod/mod_rewrite.html
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?
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.
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][/code] => 0 [message] => cURL HTTP error 0 ) ) )
Any idea?
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.
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
I got the error “stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code][/code] => 404 [message] => cURL HTTP error 404 ) ) )”. Idownloaded the code and replaced the keys. But i did get anything. Please help me
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
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.
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
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!
Hi Gerahard,
is it possible to share woocommerce user-email name and passwords via the api with another application in a secure way?
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!
Ah, just looked at the code in GitHub and it seems they are planning to add a create_coupon API function call and roll it out with WC 2.2:
https://github.com/woothemes/woocommerce/blob/master/includes/api/class-wc-api-coupons.php
And seems you are involved in bringing this coupon functionality out as well. 🙂 Thanks!
https://github.com/woothemes/woocommerce/pull/5044
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 🙂
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][/code] => 404
[message] => cURL HTTP error 404
)
)
)
Any idea?
Hi, is it possible to use the api to select products based on one or more assigned categories? Cheers Craig.
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
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.
Hello.. I have a problem, when try to getProducts returns only to 6 products, and i see 14 in thr getProducts/count
Thanks
Gerhard,
While connecting to the REST API, I received the following disquieting response:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code][/code] => 301 [message] => cURL HTTP error 301 ) ) )
I’ve already set the permalink as you suggested.
Any suggestions would be appreciated.
Thank you.
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!
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.
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.
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.
Thanks!!!!!!!!!!!
Kathy u can modify client api with original doc there http://docs.woothemes.com/wc-apidocs/source-class-WC_Cart.html#755-894.
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)
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) );
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?
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.
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][/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?
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.
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
Hi
I am getting [code][/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
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
Hi Paolo, you can find the docs for the API here http://docs.woocommercev2.apiary.io/
There is no orders and products api reference by this link…
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 ????
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
It is possible create, update or delete categories and productos via API?
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 );
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
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.
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.
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
Hi Gerhard,
Thank you for this post! Thank you also for the php wrapper. Works like a charm.
Greetings from Belgium.
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
Dear,
I want to list all products by categories. But i don’t know how to filter.
Please help me.
Thank you!
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.
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.
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][/code] => woocommerce_api_authentication_error [message] => Consumer Key is missing ) ) )
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.
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
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.
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
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
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
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?
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
where I leave the downloaded file, in what way?
Hi there, where should we put ‘class-wc-api-client.php’ and ‘woocommerce-rest-api.php’ to let the api work?
Thanks!
Hello,
First of all thanks a lot for such a great efforts.
I downloaded the library from the github.com and installed the files and folders of that, in the following directory :
.
..
1). wp-content > plugins > woocommerce > includes > libraries > lib
2). wp-content > plugins > woocommerce > includes > libraries > woocommerce-rest-api.php
..
.
I also configured the “woocommerce-rest-api.php” file with the Store_URL, CK_KEY, CK_SECRET.
Still getting the following error :
{“errors”:[{“code”:”woocommerce_api_authentication_error”,”message”:”oauth_consumer_key parameter is missing”}]}
when trying to access http://localhost/wordpress_new/wc-api/v1/products
and also this one too,
http://localhost/wordpress_new/wc-api/v1/products?consumer_key=ck_658cxxxxxx&consumer_secret=cs_6d489xxxxx
Help me with this and let me know where am i wrong..
Your help will be appreciated..
I am having a problem with updating products via API,
it gives me Error: Consumer Key is missing [woocommerce_api_authentication_error] 404
when using a PUT request type, but POST and GET work fine.
Please advise?
Hi, I wonder If I can authenticate the user by only receiving their username/email and password. If they entered them correctly, wordpress will be able to generate API for the customer(READ) and authenticate them, instead of manually generate the keys for them
Hello, first of all I found this to be a great tutorial. I am currently using the client-API to implement a simple user front-end to upload products. The function client->products->create() seems to work fine, how ever I can’t get around one issue. Every time I upload a product, the vendor is set to the admin user instead of the user that is currently logged in. Is there a way to set the vendor through the API? Has anybody get done this?
0 Pingbacks
Comment navigation
Comment navigation
Categories
Top Posts & Pages
Instagram
No Instagram images were found.
Get Email Notifications