A plugin for WordPress that grants e-commerce capabilities to a website, and also provides API support for various solutions and service access options.
So, what are these API capabilities and how are they used?
WooCommerce
For more detailed information about WooCommerce, you may refer to the WooCommerce section. WooCommerce is a highly successful and popular WordPress plugin that provides product pages, product types, and sales features, as well as tools for campaign planning. According to recent data, WooCommerce is being used on 3,317,205 websites and accounts for 28.19% of online e-commerce sites1.
You can request support regarding Google Analytics.
WooCommerce offers capabilities including WebHooks, the Legacy API, and the REST API, based on customization and required features. Previously, I discussed an example operation using PHP cURL, such as retrieving a list of products via a GET request and adding a new product via a PUT request. In this article, we will walk through the relevant operations step by step and detail the procedures that can be implemented.
REST API (WOO REST API)
WOO REST API, a REST API service fully integrated with WordPress REST API, which processes standard HTTP requests in JSON format (creation, reading, updating, and deletion) and utilizes WordPress REST API authentication methods2. WooCommerce 3.5+ and WordPress 4.4+ versions are required for usage. Finally, the v3 version of WOO REST API uses the /wp-json/wc/v3 endpoint. For requirements, errors, and sample queries, please refer to the API documentation3.
First, let’s view the index. I’ll be using Postman for example operations. We’ll proceed by directly defining the URI via the domain name.
GET alanadi.com/wp-json/wc/v3
The GET request will return a long response containing information such as methods, data types, and allowed request types for the relevant endpoint, all in JSON format.
{
"namespace": "wc/v3",
"routes": {
"/wc/v3": {
"namespace": "wc/v3",
"methods": [
"GET"
],
"endpoints": [
{
"methods": [
"GET"
],
"args": {
"namespace": {
"required": false,
"default": "wc/v3"
},
"context": {
"required": false,
"default": "view"
}
}
}
],
//...
},
//...
},
//...
}
Authentication
The most basic approach is to create one or more keys by following the steps: WooCommerce > Settings > REST API > Add Key, enabling usage with the specified user for various purposes4.
Another method is to automatically generate an API key via the Application Authentication Endpoint. The following definitions are required for this process.
The app_name specifies the application name, the scope defines the purpose of the key being created—such as read (read-only), read_write (read and write), write (write-only), the return_url indicates where the user will be redirected after the operation succeeds, and finally, the callback_url specifies the URL where the generated API key will be received. Importantly, the callback_url must use HTTPS. Now, let’s express these details in a sample line5.
https://alanadi.com/wc-auth/v1/authorize?app_name= &scope=read_write&user_id= &return_url=https://alanadi.com/return-page
&callback_url=https://alanadi.com/callback-endpoint
With the necessary information for API access, we can use the HTTP Basic Auth definition to utilize these details. Let’s briefly examine the parameters6.
Parameters
When making a request through the WOO API, the request will return specific predefined values for each parameter3. For example, when listing products, the returned JSON output will contain 10 products. If more than 10 products exist, we can leverage parameters such as the number of items per page, pagination, and offset. Pagination itself supports next, last, first, and prev navigation options7.
Let’s list orders for the range from 21 to 30 as an example query.
GET /orders?per_page=15&page=2&offset=5
Important Rules:
- Maintain the original formatting (markdown, HTML tags, links, etc.)
- Keep technical terms and proper nouns as appropriate
- Preserve code blocks and technical syntax exactly
- Maintain the same tone and style
- Only output the translated text, no explanations or comments
When using parameters, two custom fields are sent in the HEADER section related to the total item count and per_page: X-WP-Total and X-WP-TotalPages. Together with these definitions, we can determine the total number of items and how many pages this count is distributed across. For example, in my article titled R with WordPress REST API Access, I stored all content into a data table by paginating based on these details.
Now, let’s move on to our main topic: the endpoints.
Endpoints (en: Endpoint)
Endpoints are customized query addresses. We previously discussed their basic principle in the topic routing. Using these addresses, we can easily define and implement operations. For instance, let’s assume we want to add a product in WooCommerce. First, we need to check whether the product has already been added before. If it exists, instead of re-adding it, we should compare the details of the existing product and, if there are differences, our goal would be to update the product rather than adding a new one. For all these operations, we would need to write different and/or complex SQL queries or hooks. However, via the API, this operation can be accomplished in just a few lines of code with a very low risk of error8.
For example, the XML2WOO extension retrieves the specified XML file and queries products via the WooCommerce API based on the information within it. If similar products exist, it indicates this through a table and transfers the XML data to the corresponding products in WooCommerce upon request. If no similar product exists, the product from the XML content is added as a new product. Moreover, the extension can be scheduled to automatically execute this process at specified time intervals9.
Products
We can list products (by default 10 items) (view) by making a GET request to the endpoint /wp-json/wc/v3/products. To view a specific product, we can also specify the id parameter; /wp-json/wc/v3/products/. Upon listing or viewing a single product, we will receive many product details such as id, name, slug, permalink, date_created, date_modified, type, status, and more. Through this endpoint, we can also add one or more products using a POST request.
curl -X POST https://website.com/wp-json/wc/v3/products \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"name": "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": [
{
"id": 9
},
{
"id": 14
}
],
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg"
},
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg"
}
]
}'
To update a product’s information, we can perform a PUT request targeting the id. If the id we send via the PUT request does not exist, the product will be added as a new product. However, in this case, the information of the product we wish to update will be included, while all other fields will be left blank.
PUT /wp-json/wc/v3/products/
We can also delete a specific product by sending a DELETE request with the id.
DELETE /wp-json/wc/v3/products/
In order to perform bulk operations (deletion, addition, updates, etc.) in a single request, our content must be sent to the /wp-json/wc/v3/products/batch endpoint via a POST request3.
Orders
We can use the /wp-json/wc/v3/orders endpoint to list placed orders. In our queries, various details such as _id_, _order_key_, _status_, _currency_, _date_created_, _discount_total_, _total_, _customer_id_, _billing_, _shipping_, _customer_note_, _payment_method_, and _refunds_ can be retrieved. A simple GET request to this endpoint will suffice to list all orders.
GET /wp-json/wc/v3/orders/
A POST request to the /wp-json/wc/v3/orders endpoint is sufficient to create a new order.
curl -X POST https://alanadi.com/wp-json/wc/v3/orders \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"payment_method": "bacs",
"payment_method_title": "Direct Bank Transfer",
"set_paid": true,
"billing": {
"first_name": "John",
"last_name": "Doe",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US",
"email": "john.doe@alanadi.com",
"phone": "(555) 555-5555"
},
"shipping": {
"first_name": "John",
"last_name": "Doe",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US"
},
"line_items": [
{
"product_id": 93,
"quantity": 2
},
{
"product_id": 22,
"variation_id": 23,
"quantity": 1
}
],
"shipping_lines": [
{
"method_id": "flat_rate",
"method_title": "Flat Rate",
"total": 10
}
]
}'
After processing this request, we will return more detailed information including other predefined details related to the added product. We can access the details of an order via a GET request using its id.
GET /wp-json/wc/v3/orders/
If we wish to update the information related to an order, we can simply perform a PUT request using the id.
curl -X PUT https://website.com/wp-json/wc/v3/orders/<id> \
-u consumer_key:consumer_secret \
-H "Content-Type: application/json" \
-d '{
"status": "completed"
}'
To delete an order, we can use a DELETE request including the id. For more detailed information and examples related to order operations, refer to the woocommerce-rest-api-docs.
Refunds
Refund operations can also be easily managed via the WOO API. The endpoint used for these operations is /wp-json/wc/v3/orders/refunds. As observed, a refund is processed based on the order’s _id. Therefore, prior to initiating a refund, it is necessary to obtain the id of the relevant order. We can initiate a refund using the following POST request.
POST /wp-json/wc/v3/orders/refunds
To list all refund operations, a GET request to the refunds endpoint will suffice.
GET /wp-json/wc/v3/orders/refunds
To view details of a created refund, we can retrieve them via the refund_id.
GET /wp-json/wc/v3/orders/refunds/
Finally, to delete a refund, we will perform a DELETE request using the refund_id.
DELETE /wp-json/wc/v3/orders/refunds/
You can also review the WOO REST API documentation for other endpoints such as customers, coupons, product attributes, product categories, predefined shipping classes, product tags, tax rates, tax classes, payment methods, and shipping zones3.
Related Recommendations
Further Reading
- sgwebpartners. How To Use The WooCommerce API Without Knowing How to Code
- joshuaiz. No WooCommerce Cart API? No Problem
- How to Connect Your PHP Based Web App to the WooCommerce Rest API
Footnotes
- Getting started with the REST API ↩
- WOO REST API ↩
- WooCommerce REST API Documentation ↩ ↩2 ↩3 ↩4
- 21+ WooCommerce Stats – The Leader in WordPress eCommerce ↩
- Builtwith – Trends. WooCommerce Usage Statistics ↩
- Basic access authentication. Wikipedia ↩
- W3Techs. Usage statistics and market share of WooCommerce ↩
- Datanyze. Top Competitors of WooCommerce in Datanyze Universe ↩
- Torque. The Beginner’s Guide to the WooCommerce REST API ↩