Hey there, fellow JavaScript aficionados! Ready to dive into the world of WooCommerce API? Let's talk about syncing data for user-facing integrations. Buckle up, because we're about to make your e-commerce projects a whole lot smoother.
First things first, let's get you set up. WooCommerce offers two authentication methods: OAuth 1.0a and API keys. For quick and dirty setups, API keys are your best friend. Here's how to get rolling with the @woocommerce/woocommerce-rest-api
library:
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default; const api = new WooCommerceRestApi({ url: "https://your-store.com", consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", version: "wc/v3" });
Now that we're connected, let's fetch some data. Here's a quick async function to grab products:
async function fetchProducts() { try { const response = await api.get("products", { per_page: 20 }); return response.data; } catch (error) { console.error("Error fetching products:", error); } }
Writing data is just as easy. Want to update a product? Check this out:
async function updateProduct(productId, data) { try { const response = await api.put(`products/${productId}`, data); return response.data; } catch (error) { console.error("Error updating product:", error); } }
For real-time updates, webhooks are your best bet. Here's a simple Express.js webhook listener:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { topic, data } = req.body; console.log(`Received webhook: ${topic}`); // Process the data res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook listener running on port 3000'));
When dealing with large datasets, pagination is crucial. Here's how to fetch all products:
async function getAllProducts() { let page = 1; let allProducts = []; while (true) { const response = await api.get("products", { per_page: 100, page }); allProducts = allProducts.concat(response.data); if (response.data.length < 100) break; page++; } return allProducts; }
Remember to respect rate limits! WooCommerce typically allows 25 API requests per second.
Always prepare for the worst. Here's a retry function with exponential backoff:
async function retryOperation(operation, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await operation(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 2 ** i * 1000)); } } }
Caching can significantly boost your app's performance. Here's a simple in-memory cache:
const cache = new Map(); function getCachedData(key, fetchFunction, ttl = 60000) { if (cache.has(key) && cache.get(key).expiry > Date.now()) { return cache.get(key).data; } const data = fetchFunction(); cache.set(key, { data, expiry: Date.now() + ttl }); return data; }
Always sanitize your inputs! Here's a basic example:
function sanitizeInput(input) { return String(input).replace(/[^\w\s]/gi, ''); }
And never, ever store API credentials in your client-side code. Use environment variables or a secure backend.
There you have it, folks! You're now armed with the knowledge to build robust, efficient integrations with the WooCommerce API. Remember, with great power comes great responsibility – use these tools wisely, and your e-commerce projects will thank you.
Keep coding, keep learning, and most importantly, keep having fun with it. Until next time, happy hacking!