woocommerce-react-api
v1.0.8
Published
A TypeScript/JavaScript client library for interacting with WooCommerce REST API. This package provides a clean, type-safe interface for managing products, categories, orders, and other WooCommerce resources.
Downloads
24
Readme
WooCommerce React API
A TypeScript/JavaScript client library for interacting with WooCommerce REST API. This package provides a clean, type-safe interface for managing products, categories, orders, and other WooCommerce resources.
Features
- 🚀 TypeScript Support: Full TypeScript definitions for all WooCommerce resources
- 🔒 Authentication: Built-in support for WooCommerce API authentication
- 📦 Repository Pattern: Clean, organized API with dedicated repositories for each resource
- ✅ Data Validation: Zod-based validation for request/response data
- 🧪 Testing: Comprehensive test suite with Jest
- 📚 Well Documented: Clear API documentation and examples
Installation
npm install woocommerce-react-apiQuick Start
import { WooCommerceClient } from 'woocommerce-react-api';
// Initialize the client
const wc = new WooCommerceClient({
url: 'https://your-store.com',
consumerKey: 'ck_your_consumer_key',
consumerSecret: 'cs_your_consumer_secret',
version: 'v3', // optional, defaults to 'v3'
timeout: 30000 // optional, defaults to 30000ms
});
// Fetch products
const products = await wc.products.findMany();
console.log('Products:', products);
// Fetch categories
const categories = await wc.categories.findMany();
console.log('Categories:', categories);Configuration
The WooCommerceConfig interface requires the following properties:
interface WooCommerceConfig {
url: string; // Your WooCommerce store URL
consumerKey: string; // WooCommerce API consumer key
consumerSecret: string; // WooCommerce API consumer secret
version?: string; // API version (default: 'v3')
timeout?: number; // Request timeout in ms (default: 30000)
}Available Repositories
Products Repository
The ProductRepository provides methods to manage WooCommerce products:
// Get all products
const products = await wc.products.findMany();
// Get products with pagination and filters
const products = await wc.products.findMany({
per_page: 20,
page: 1,
status: 'publish',
featured: 'true',
category: 'electronics'
});
// Get a specific product
const product = await wc.products.findById(123);
// Create a new product
const newProduct = await wc.products.create({
name: 'New Product',
type: 'simple',
regular_price: '29.99',
description: 'Product description',
short_description: 'Short description'
});
// Update a product
const updatedProduct = await wc.products.update(123, {
name: 'Updated Product Name',
regular_price: '39.99'
});
// Delete a product
await wc.products.delete(123);
// Search products by name
const searchResults = await wc.products.searchByName('laptop');
// Get products by category
const categoryProducts = await wc.products.getByCategory(15);Categories Repository
The CategoryRepository provides methods to manage product categories:
// Get all categories
const categories = await wc.categories.findMany();
// Get categories with filters
const categories = await wc.categories.findMany({
per_page: 50,
hide_empty: false,
parent: 0
});
// Get a specific category
const category = await wc.categories.findById(15);
// Create a new category
const newCategory = await wc.categories.create({
name: 'Electronics',
slug: 'electronics',
description: 'Electronic products and gadgets',
parent: 0
});
// Update a category
const updatedCategory = await wc.categories.update(15, {
name: 'Updated Category Name',
description: 'Updated description'
});
// Delete a category
await wc.categories.delete(15);
// Get top-level categories
const topLevelCategories = await wc.categories.getTopLevel();
// Get subcategories by parent
const subcategories = await wc.categories.getByParent(15);
// Search categories by name
const searchResults = await wc.categories.searchByName('electronics');
// Get categories by slug
const categoryBySlug = await wc.categories.getBySlug('electronics');
// Get empty categories
const emptyCategories = await wc.categories.getEmpty();
// Get non-empty categories
const nonEmptyCategories = await wc.categories.getNonEmpty();Orders Repository
The OrderRepository provides methods to manage WooCommerce orders:
// Get all orders
const orders = await wc.orders.findMany();
// Get orders with filters
const orders = await wc.orders.findMany({
status: 'completed',
per_page: 20,
orderby: 'date',
order: 'desc'
});
// Get a specific order
const order = await wc.orders.findById(123);
// Create a new order
const newOrder = await wc.orders.create({
payment_method: 'bacs',
payment_method_title: 'Direct Bank Transfer',
set_paid: true,
billing: {
first_name: 'John',
last_name: 'Doe',
address_1: '123 Main St',
city: 'New York',
state: 'NY',
postcode: '10001',
country: 'US',
email: '[email protected]',
phone: '555-1234'
},
shipping: {
first_name: 'John',
last_name: 'Doe',
address_1: '123 Main St',
city: 'New York',
state: 'NY',
postcode: '10001',
country: 'US'
},
line_items: [
{
product_id: 123,
quantity: 2
}
]
});
// Update an order
const updatedOrder = await wc.orders.update(123, {
status: 'processing'
});
// Delete an order
await wc.orders.delete(123);
// Get orders by status
const pendingOrders = await wc.orders.getByStatus('pending');
const completedOrders = await wc.orders.getCompleted();
// Get orders by customer
const customerOrders = await wc.orders.getByCustomer(456);
// Get orders by product
const productOrders = await wc.orders.getByProduct(789);
// Get recent orders
const recentOrders = await wc.orders.getRecent(10);
// Get orders by date range
const dateRangeOrders = await wc.orders.getByDateRange('2024-01-01', '2024-01-31');
// Search orders by number
const orderSearch = await wc.orders.searchByNumber('12345');Type Definitions
The package includes comprehensive TypeScript definitions for all WooCommerce resources:
Product- Complete product interface with all WooCommerce product fieldsCategory- Category interface with image, links, and metadataOrder- Order interface with billing, shipping, line items, and moreProductSearchParams- Parameters for product queriesCategorySearchParams- Parameters for category queriesOrderSearchParams- Parameters for order queries
Error Handling
The client includes proper error handling for API responses:
try {
const products = await wc.products.findMany();
} catch (error) {
if (error.response) {
// API responded with error status
console.error('API Error:', error.response.status, error.response.data);
} else if (error.request) {
// Request was made but no response received
console.error('Network Error:', error.request);
} else {
// Something else happened
console.error('Error:', error.message);
}
}Authentication
The package supports WooCommerce's standard authentication methods:
- Basic Authentication: Uses consumer key and secret for API authentication
- OAuth 1.0a: Planned for future releases
Development
Building the Package
npm run buildRunning Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageProject Structure
src/
├── http/ # HTTP client and authentication
│ ├── HTTPClient.ts
│ └── strategies/
│ └── AuthStrategy.ts
├── repositories/ # Repository classes for each resource
│ ├── BaseRepository.ts
│ ├── ProductRepository.ts
│ ├── CategoryRepository.ts
│ └── OrderRepository.ts
├── types/ # TypeScript type definitions
│ ├── product.types.ts
│ ├── category.types.ts
│ └── order.types.ts
├── validations/ # Zod validation schemas
│ ├── product.validation.ts
│ ├── category.validation.ts
│ └── order.validation.ts
└── WooCommerceClient.ts # Main client classContributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the ISC License.
Support
For support and questions, please open an issue on the GitHub repository.
Changelog
v1.0.0
- Initial release
- Product, Category, and Order repositories
- TypeScript support
- Basic authentication
- Comprehensive test suite
