Woocommerce
WooCommerce is an open-source e-commerce plugin for WordPress, transforming any WordPress website into a fully functional online store. It provides comprehensive features for product management, order processing, payments, and shipping, making it a highly customizable and flexible solution for businesses ranging from small startups to large enterprises who prefer a self-hosted platform with full control over their data and infrastructure.
You are a WooCommerce integration specialist, expert in extending WordPress-based e-commerce platforms and automating store operations. You configure products, manage orders, handle customer data, process payments, and leverage the powerful REST API to synchronize data, create custom workflows, and build bespoke e-commerce experiences on top of the robust WooCommerce core. ## Key Points 1. **Install WooCommerce**: Ensure WooCommerce is installed and active on your WordPress site. 2. **Generate API Keys**: 3. **Install SDK (Node.js Example)**: Use a community-maintained SDK for easier interaction. * **Specify API Version:** Always include the `version` parameter in your API client (`wc/v3` is current stable) to ensure compatibility and avoid unexpected behavior if the API evolves. ## Quick Example ```bash npm install --save @woocommerce/woocommerce-rest-api # or yarn add @woocommerce/woocommerce-rest-api ```
skilldb get ecommerce-services-skills/WoocommerceFull skill: 226 linesYou are a WooCommerce integration specialist, expert in extending WordPress-based e-commerce platforms and automating store operations. You configure products, manage orders, handle customer data, process payments, and leverage the powerful REST API to synchronize data, create custom workflows, and build bespoke e-commerce experiences on top of the robust WooCommerce core.
Core Philosophy
WooCommerce's core philosophy is built on the foundation of WordPress: open-source, extensible, and user-centric. It empowers businesses with complete ownership and control over their e-commerce data and functionality, without being locked into proprietary SaaS platforms. You choose WooCommerce when deep customization, integration with the vast WordPress plugin ecosystem, and the ability to scale without escalating platform fees are paramount. It's an ideal solution for those who require a highly tailored online store experience or already operate within the WordPress environment.
Unlike managed e-commerce services, WooCommerce requires you to manage your own hosting, security, and maintenance. This trade-off grants unparalleled flexibility, allowing you to modify virtually every aspect of your store's appearance and behavior. Its REST API is a central component of this flexibility, enabling headless commerce architectures, integration with third-party systems like CRMs or ERPs, and the automation of administrative tasks, providing a robust backbone for complex e-commerce operations.
Setup
Integrating with the WooCommerce REST API requires generating API keys from your WordPress admin panel and using an SDK or direct HTTP requests.
- Install WooCommerce: Ensure WooCommerce is installed and active on your WordPress site.
- Generate API Keys:
- Navigate to WooCommerce > Settings > Advanced > REST API.
- Click "Add key".
- Provide a description, select a user, and set "Permissions" to
Read/Write. - Generate the API key. You will receive a
Consumer KeyandConsumer Secret. Keep these secure.
- Install SDK (Node.js Example): Use a community-maintained SDK for easier interaction.
npm install --save @woocommerce/woocommerce-rest-api
# or
yarn add @woocommerce/woocommerce-rest-api
// Import the WooCommerce REST API client library
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;
// Initialize the API client with your store details and API keys
const wooApi = new WooCommerceRestApi({
url: "https://your-wordpress-site.com", // Your store URL (e.g., https://example.com)
consumerKey: "ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // Your Consumer Key
consumerSecret: "cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // Your Consumer Secret
version: "wc/v3", // Specify the WooCommerce API version
// If your server doesn't support Basic Auth, set queryStringAuth to true
// This passes the keys as query parameters (less secure, use HTTPS!)
queryStringAuth: false,
});
// Example: Verify connection by listing products (first page, limit 1)
async function testConnection() {
try {
const { data } = await wooApi.get("products", { per_page: 1 });
console.log("Successfully connected to WooCommerce API. Found products:", data.length);
} catch (error) {
console.error("Error connecting to WooCommerce API:", error.response ? error.response.data : error.message);
}
}
testConnection();
Key Techniques
1. Retrieving Products
Fetch products from your store, applying filters for specific categories, statuses, or search terms.
// Retrieve a list of products
async function getProducts(options = {}) {
try {
const { data } = await wooApi.get("products", options);
console.log("Retrieved products:", data.map(p => ({ id: p.id, name: p.name, price: p.price })));
return data;
} catch (error) {
console.error("Error retrieving products:", error.response ? error.response.data : error.message);
throw error;
}
}
// Get all products
getProducts();
// Get products from a specific category (e.g., category ID 12)
getProducts({ category: 12 });
// Get a single product by ID
async function getProductById(productId) {
try {
const { data } = await wooApi.get(`products/${productId}`);
console.log(`Retrieved product ${productId}:`, { id: data.id, name: data.name, price: data.price, stock: data.stock_quantity });
return data;
} catch (error) {
console.error(`Error retrieving product ${productId}:`, error.response ? error.response.data : error.message);
throw error;
}
}
getProductById(123); // Replace with an actual product ID
2. Creating an Order
Programmatically create new orders, useful for integrating with external sales channels or custom checkout flows.
// Create a new order
async function createOrder(orderData) {
try {
const { data } = await wooApi.post("orders", orderData);
console.log("Order created successfully:", { id: data.id, status: data.status, total: data.total });
return data;
} catch (error) {
console.error("Error creating order:", error.response ? error.response.data : error.message);
throw error;
}
}
// Example order data:
const newOrder = {
payment_method: "bacs", // "bacs" (Bank Transfer), "cheque", "cod" (Cash on Delivery), etc.
payment_method_title: "Direct Bank Transfer",
set_paid: true, // Set to true to mark order as paid
status: "processing", // "pending", "processing", "on-hold", "completed", "cancelled", "refunded", "failed"
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@example.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: 456, // Replace with an actual product ID
quantity: 2
},
{
product_id: 789, // Replace with an actual product ID
quantity: 1
}
],
shipping_lines: [
{
method_id: "flat_rate",
method_title: "Flat Rate",
total: "10.00"
}
]
};
createOrder(newOrder);
3. Updating Product Inventory
Modify product details, such as stock quantity, price, or status. Essential for inventory management systems.
// Update a product's stock quantity
async function updateProductStock(productId, newStockQuantity) {
const data = {
stock_quantity: newStockQuantity,
};
try {
const { data: updatedProduct } = await wooApi.put(`products/${productId}`, data);
console.log(`Product ${productId} stock updated to:`, updatedProduct.stock_quantity);
return updatedProduct;
} catch (error) {
console.error(`Error updating product ${productId} stock:`, error.response ? error.response.data : error.message);
throw error;
}
}
// Update a product's price and status
async function updateProductDetails(productId, price, status) {
const data = {
regular_price: String(price), // Prices must be strings
status: status, // e.g., 'publish', 'draft'
};
try {
const { data: updatedProduct } = await wooApi.put(`products/${productId}`, data);
console.log(`Product ${productId} updated: Price: ${updatedProduct.regular_price}, Status: ${updatedProduct.status}`);
return updatedProduct;
} catch (error) {
console.error(`Error updating product ${productId} details:`, error.response ? error.response.data : error.message);
throw error;
}
}
// Example usage:
updateProductStock(123, 50); // Set product 123's stock to 50
updateProductDetails(123, 29.99, 'publish'); // Set product 123's price to 29.99 and publish it
Best Practices
- Secure Your API Keys: Treat
Consumer KeyandConsumer Secretas sensitive credentials. Never hardcode them in client-side code or expose them publicly. Use environment variables or a secure secret management service. - Implement Robust Error Handling: Always wrap API calls in
try-catchblocks and handle various HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Server Error). Log detailed error responses. - Utilize Pagination: For endpoints returning large datasets (e.g.,
products,orders), always useper_pageandpageparameters to fetch data in manageable chunks and avoid performance issues or hitting memory limits. - Monitor Rate Limits: Be aware of potential API rate limits, especially on shared hosting environments or when making many requests. Implement exponential backoff for retries to avoid being blocked.
- Leverage Webhooks for Real-time Updates: Instead of continuously polling the API for changes, configure WooCommerce webhooks to push notifications to your application when specific events occur (e.g., new order, product update). This is more efficient and responsive.
- Test in a Staging Environment: Always develop and test your integrations against a staging or development version of your WooCommerce store before deploying to production to prevent disrupting live operations.
- Specify API Version: Always include the
versionparameter in your API client (wc/v3is current stable) to ensure compatibility and avoid unexpected behavior if the API evolves.
Anti-Patterns
- Hardcoding API Keys in Public Repositories. Never commit your
Consumer KeyandConsumer Secretdirectly into your source code, especially if it's publicly accessible. Use environment variables or a secrets manager. - Ignoring API Error Responses. Failing to check for non-2xx HTTP status codes or parse error messages can lead to silent failures, data inconsistencies, and difficult debugging. Always log and respond to API errors.
- Polling for Data Changes Instead of Using Webhooks. Regularly querying an endpoint (e.g.,
/orders) to check for new data is inefficient, consumes excessive API requests, and can lead to rate limiting. Configure webhooks for real-time, event-driven updates. - Synchronous Processing of Long-Running Tasks. Performing complex operations (like bulk product updates or order fulfillment) synchronously within a web request can cause timeouts and poor user experience. Delegate these to background jobs or asynchronous queues.
- Exposing API Keys in Client-Side Code. Never make direct WooCommerce API calls from frontend JavaScript or mobile applications using your
Consumer KeyandConsumer Secret. Route all API requests through a secure backend server that can authenticate and authorize requests safely.
Install this skill directly: skilldb add ecommerce-services-skills
Related Skills
Bigcommerce
Integrate BigCommerce APIs for catalog management, order processing,
Commercejs
Integrate Commerce.js headless commerce SDK for product management,
Fourthwall
Fourthwall is a specialized e-commerce platform that empowers creators to design, launch, and sell custom physical merchandise directly to their audience. It streamlines the entire process from product creation and manufacturing to fulfillment and customer service, making it an ideal solution for content creators, streamers, and influencers looking to monetize their brand with high-quality physical goods without managing inventory or logistics.
Gumroad
Gumroad is an e-commerce platform designed for creators to sell digital products, memberships, and physical goods directly to their audience. It provides a simple storefront, payment processing, and delivery mechanisms, making it ideal for solopreneurs, artists, and educators who want to monetize their creations quickly and efficiently without complex technical setups.
Lemonsqueezy
Lemon Squeezy is an all-in-one platform for selling digital products and subscriptions.
Medusa
Build headless commerce backends with Medusa's modular architecture.