Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Woocommerce Api Laravel Package

woothemes/woocommerce-api

PHP client wrapper for the WooCommerce REST API. Create a WC_API_Client with your store URL and API keys to fetch the API index, list/filter orders, and retrieve single orders. Supports debug output, array responses, timeouts, URL validation, and exceptions with request/response details.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require woothemes/woocommerce-api
    
  2. Generate API Credentials: Navigate to WooCommerce → Settings → Advanced → REST API in your WordPress admin panel. Create a new consumer key/secret pair with Read/Write permissions (or restrict as needed).
  3. Initialize the Client (Laravel example):
    use WC_API_Client;
    
    $client = new WC_API_Client(
        env('WOOCOMMERCE_STORE_URL'),
        env('WOOCOMMERCE_CONSUMER_KEY'),
        env('WOOCOMMERCE_CONSUMER_SECRET'),
        ['ssl_verify' => false, 'debug' => env('APP_DEBUG')]
    );
    
    Store credentials in .env:
    WOOCOMMERCE_STORE_URL=https://your-store.com
    WOOCOMMERCE_CONSUMER_KEY=ck_your_key
    WOOCOMMERCE_CONSUMER_SECRET=cs_your_secret
    

First Use Case: Fetch Orders

// Get all orders (returns stdClass by default)
$orders = $client->orders->get();

// Get a single order
$order = $client->orders->get(123);

// Filter orders (e.g., completed status)
$completedOrders = $client->orders->get(null, ['status' => 'completed']);

// Return as associative array
$client->set_return_as_array(true);
$ordersArray = $client->orders->get();

Implementation Patterns

Common Workflows

1. Order Management

  • Create an Order:
    $orderData = [
        'payment_method' => 'bacs',
        'payment_method_title' => 'Direct Bank Transfer',
        'set_paid' => true,
        'billing' => [
            'first_name' => 'John',
            'last_name' => 'Doe',
            'email' => 'john@example.com',
        ],
        'line_items' => [
            [
                'product_id' => 123,
                'quantity' => 2,
            ],
        ],
    ];
    $newOrder = $client->orders->create($orderData);
    
  • Update an Order Status:
    $client->orders->update(123, ['status' => 'processing']);
    
  • Cancel an Order:
    $client->orders->update(123, ['status' => 'cancelled']);
    

2. Product Management

  • Fetch Products:
    $products = $client->products->get();
    $featuredProducts = $client->products->get(null, ['featured' => true]);
    
  • Create a Product:
    $productData = [
        'name' => 'Premium Widget',
        'type' => 'simple',
        'regular_price' => '29.99',
        'description' => 'A high-quality widget.',
        'categories' => [['id' => 5]],
    ];
    $newProduct = $client->products->create($productData);
    

3. Custom Endpoints

  • Call a Custom API Route:
    $customResponse = $client->get('reports/top_sellers', ['period' => 'month']);
    

4. Webhooks (Server-Side)

  • Validate Webhook Signatures (Laravel middleware example):
    use Illuminate\Http\Request;
    
    public function handle(Request $request, Closure $next) {
        $signature = $request->header('X-WC-Webhook-Signature');
        $payload = $request->getContent();
        $secret = env('WOOCOMMERCE_WEBHOOK_SECRET');
    
        if (!hash_equals($signature, hash_hmac('sha256', $payload, $secret))) {
            abort(401, 'Invalid webhook signature');
        }
        return $next($request);
    }
    

5. Batch Operations

  • Bulk Update Orders:
    $orderIds = [123, 456, 789];
    foreach ($orderIds as $id) {
        $client->orders->update($id, ['status' => 'completed']);
    }
    

Integration Tips

Laravel Service Provider

Register the client as a singleton in AppServiceProvider:

public function register() {
    $this->app->singleton('woocommerce', function ($app) {
        return new WC_API_Client(
            env('WOOCOMMERCE_STORE_URL'),
            env('WOOCOMMERCE_CONSUMER_KEY'),
            env('WOOCOMMERCE_CONSUMER_SECRET'),
            ['ssl_verify' => false, 'debug' => env('APP_DEBUG')]
        );
    });
}

API Rate Limiting

  • WooCommerce enforces 60 requests per minute by default. Cache responses aggressively:
    $cacheKey = 'woocommerce_orders_' . $status;
    $orders = Cache::remember($cacheKey, now()->addMinutes(1), function () use ($client, $status) {
        return $client->orders->get(null, ['status' => $status]);
    });
    

Testing

  • Use mocking for unit tests (e.g., with Mockery):
    $mockClient = Mockery::mock('overload:WC_API_Client');
    $mockClient->shouldReceive('orders->get')->andReturn(['data' => 'mocked']);
    

Gotchas and Tips

Pitfalls

  1. SSL Verification:

    • Disabling ssl_verify (e.g., for local testing) is not recommended for production. Use a valid SSL certificate or configure your CA bundle:
      $options = [
          'ssl_verify' => true,
          'cafile' => '/path/to/cacert.pem',
      ];
      
  2. API Versioning:

    • This library only supports WooCommerce REST API v2/v3. Ensure your store is updated.
  3. Pagination:

    • The library does not handle pagination automatically. Use the page and per_page parameters manually:
      $client->orders->get(null, ['page' => 2, 'per_page' => 10]);
      
  4. Debugging:

    • Enable debug: true to log requests/responses, but disable in production for security:
      $client = new WC_API_Client(..., ['debug' => true]);
      
  5. Timeouts:

    • Default timeout is 30 seconds. Increase for large payloads (e.g., bulk operations):
      $client = new WC_API_Client(..., ['timeout' => 60]);
      
  6. Webhook Delays:

    • WooCommerce webhooks may have delays (up to 5 minutes). Implement retry logic for critical operations.
  7. Data Types:

    • Dates are returned as strings (e.g., "2023-10-01T12:00:00"). Parse with Carbon:
      $orderDate = Carbon::parse($order->date_created);
      
  8. Error Handling:

    • Always wrap API calls in try-catch blocks:
      try {
          $order = $client->orders->get(123);
      } catch (WC_API_Client_HTTP_Exception $e) {
          Log::error('WooCommerce API Error: ' . $e->getMessage());
          abort(500, 'Failed to fetch order');
      }
      

Tips

  1. Use return_as_array:

    • Set return_as_array: true for easier JSON/API response handling:
      $client->set_return_as_array(true);
      $order = $client->orders->get(123); // Now an associative array
      
  2. Leverage get() for Custom Endpoints:

    • Access any WooCommerce REST endpoint dynamically:
      $reports = $client->get('reports/top_sellers', ['period' => 'year']);
      
  3. Cache API Responses:

    • Cache frequent queries (e.g., product catalog, order statuses) to reduce API calls:
      Cache::remember('woocommerce_products', now()->addHours(1), function () {
          return $client->products->get();
      });
      
  4. Batch Processing:

    • For large datasets, use chunking with pagination:
      $perPage = 100;
      $page = 1;
      do {
          $orders = $client->orders->get(null, [
              'page' => $page,
              'per_page' => $perPage,
          ]);
          // Process $orders
          $page++;
      } while (!empty($orders));
      
  5. Webhook Testing:

    • Test webhooks locally using ngrok to expose your Laravel app to the internet:
      ngrok http 8000
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle