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

Wildberries Laravel Package

baks-dev/wildberries

Laravel/PHP модуль для интеграции с Wildberries API. Установка через Composer, поддержка PHP 8.4+. В комплекте команды для установки конфигурации и ресурсов (baks:assets:install) и набор тестов PHPUnit (group=wildberries).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require baks-dev/wildberries
    
  2. Publish configuration and assets:

    php artisan baks:assets:install
    

    This generates:

    • config/wildberries.php (configuration file)
    • Storage directory for API responses (storage/wildberries/)
  3. Configure .env:

    WILDBERRIES_API_KEY=your_api_key_here
    WILDBERRIES_API_SECRET=your_api_secret_here
    WILDBERRIES_SANDBOX=false  # Set to true for testing
    
  4. First API call (orders example):

    use BaksDev\Wildberries\Facades\Wildberries;
    
    $orders = Wildberries::orders()->get();
    

First Use Case: Fetching Orders

// Fetch last 10 orders
$orders = Wildberries::orders()->get(['limit' => 10]);

// Process each order
foreach ($orders as $order) {
    // Handle order logic (e.g., update local DB, trigger fulfillment)
    \Log::info("Processing order ID: {$order->id}");
}

Key Configuration Options

  • API Endpoints: Configure in config/wildberries.php:
    'endpoints' => [
        'orders' => 'https://api.wildberries.ru/v2/orders',
        'catalog' => 'https://api.wildberries.ru/v2/catalog',
    ],
    
  • Rate Limiting: Adjust in config:
    'rate_limits' => [
        'orders' => 100, // requests per minute
        'catalog' => 50,
    ],
    

Implementation Patterns

Core Workflows

1. Order Management

// Create a new order
$orderData = [
    'clientOrderId' => 'YOUR_LOCAL_ORDER_ID',
    'items' => [
        ['productId' => 12345, 'quantity' => 2],
    ],
];
$createdOrder = Wildberries::orders()->create($orderData);

// Get order details
$order = Wildberries::orders()->getById($createdOrder->id);

// Update order status
Wildberries::orders()->updateStatus($createdOrder->id, 'shipped');

2. Catalog Management

// Add product to catalog
$productData = [
    'name' => 'Test Product',
    'price' => 1000,
    'description' => 'Product description',
    'images' => ['url1', 'url2'],
];
$product = Wildberries::catalog()->addProduct($productData);

// Update product stock
Wildberries::catalog()->updateStock($product->id, 50);

3. Inventory Sync

// Sync inventory with Wildberries
$inventory = [
    ['productId' => 12345, 'quantity' => 100],
    ['productId' => 67890, 'quantity' => 200],
];
Wildberries::inventory()->sync($inventory);

Integration Tips

Laravel Service Providers

Extend functionality via service providers:

// app/Providers/WildberriesServiceProvider.php
public function register()
{
    $this->app->extend('wildberries', function ($wildberries) {
        $wildberries->extend('custom_method', function () {
            return new CustomWildberriesService();
        });
        return $wildberries;
    });
}

Queued API Calls

Offload heavy API operations to queues:

// Dispatch a job to fetch orders asynchronously
FetchWildberriesOrders::dispatch();

// Job class
class FetchWildberriesOrders implements ShouldQueue
{
    public function handle()
    {
        $orders = Wildberries::orders()->get();
        // Process orders...
    }
}

API Response Caching

Cache responses to reduce API calls:

$cacheKey = 'wildberries_orders_' . now()->timestamp;
$orders = Cache::remember($cacheKey, now()->addMinutes(5), function () {
    return Wildberries::orders()->get();
});

Webhook Handling

Set up webhook endpoints for real-time updates:

// routes/web.php
Route::post('/wildberries/webhook', [WildberriesWebhookController::class, 'handle']);

// Controller
public function handle(Request $request)
{
    $payload = $request->json()->all();
    $event = Wildberries::webhooks()->parse($payload);

    // Handle event (e.g., order status change)
    if ($event->type === 'order_status_updated') {
        $this->updateLocalOrder($event->data);
    }
}

Gotchas and Tips

Common Pitfalls

  1. Authentication Issues

    • Problem: API calls fail with 401 Unauthorized.
    • Solution: Verify .env credentials and ensure the token is refreshed:
      Wildberries::auth()->refreshToken();
      
  2. Rate Limiting

    • Problem: 429 Too Many Requests errors.
    • Solution: Configure rate limits in config/wildberries.php and implement exponential backoff:
      use BaksDev\Wildberries\Exceptions\RateLimitExceeded;
      
      try {
          $orders = Wildberries::orders()->get();
      } catch (RateLimitExceeded $e) {
          sleep($e->retryAfter);
          retry();
      }
      
  3. Sandbox vs Production

    • Problem: Accidental API calls to production.
    • Solution: Always set WILDBERRIES_SANDBOX=true in .env during development.
  4. XML Schema Validation

    • Problem: Wildberries rejects payloads with malformed XML.
    • Solution: Use the package’s built-in validators:
      $validator = Wildberries::validator();
      if (!$validator->validateOrder($orderData)) {
          throw new \InvalidArgumentException($validator->getErrors());
      }
      
  5. Storage Permissions

    • Problem: baks:assets:install fails with permission errors.
    • Solution: Ensure the storage/wildberries directory is writable:
      mkdir -p storage/wildberries
      chmod -R 775 storage/wildberries
      

Debugging Tips

  1. Enable Debug Logging Add to config/wildberries.php:

    'debug' => env('WILDBERRIES_DEBUG', false),
    

    Then check logs for detailed API request/response data.

  2. Inspect Raw API Responses

    $response = Wildberries::orders()->get(['debug' => true]);
    // $response->raw() contains the unprocessed API response
    
  3. Test with Postman Use the Wildberries API documentation to manually test endpoints before integrating.

Configuration Quirks

  1. Default Timeouts The package uses Guzzle’s default timeout (5 seconds). Increase it for slow responses:

    Wildberries::setTimeout(30); // 30 seconds
    
  2. Custom Headers Add headers to all API requests:

    Wildberries::setDefaultHeaders([
        'X-Custom-Header' => 'value',
    ]);
    
  3. Proxy Support Configure proxy settings in config/wildberries.php:

    'proxy' => [
        'http' => 'http://proxy.example.com:8080',
        'https' => 'http://proxy.example.com:8080',
    ],
    

Extension Points

  1. Custom API Endpoints Extend the API client to support non-standard endpoints:

    Wildberries::extend('custom_endpoint', function () {
        return new CustomEndpointService();
    });
    
    // Usage
    $data = Wildberries::custom_endpoint()->get();
    
  2. Middleware for Requests/Responses Add middleware to modify requests or responses:

    Wildberries::middleware(function ($request) {
        $request->headers->set('X-Request-ID', Str::uuid());
    });
    
    Wildberries::responseMiddleware(function ($response) {
        $response->data['processed_at'] = now()->toIso8601String();
        return $response;
    });
    
  3. Event Listeners Listen for Wildberries API events:

    Wildberries::on('order.created', function ($order) {
        // Trigger local order creation
    });
    
    Wildberries::on('order.updated', function ($order) {
        // Update local order status
    });
    

Performance Optimization

  1. Batch Processing Process large datasets in batches:
    $batchSize = 50;
    $totalOrders = Wildberries::orders()->count();
    
    for ($i = 0; $i < $totalOrders; $i += $batchSize) {
        $orders = Wildberries::orders()->get(['offset' => $i, 'limit' => $batchSize]);
        // Process batch
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit