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

Ozon Products Laravel Package

baks-dev/ozon-products

Laravel/PHP 8.4+ пакет для интеграции с Ozon Products: управление продукцией, синхронизация и обмен данными с маркетплейсом Ozon. Устанавливается через Composer, включает PHPUnit-тесты.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/ozon-products
    php artisan vendor:publish --provider="BaksDev\OzonProducts\OzonProductsServiceProvider" --tag="config"
    
    • Publishes config file (config/ozon-products.php) for API credentials and settings.
  2. Configuration:

    • Update .env with Ozon API credentials:
      OZON_CLIENT_ID=your_client_id
      OZON_CLIENT_SECRET=your_client_secret
      OZON_SANDBOX=false  # Set to true for testing
      
    • Configure required settings in config/ozon-products.php:
      'api' => [
          'base_url' => env('OZON_API_URL', 'https://api.ozon.ru'),
          'timeout' => 30,
      ],
      'models' => [
          'product' => \App\Models\Product::class, // Your Eloquent model
      ],
      
  3. First Use Case: Sync a single product to Ozon:

    use BaksDev\OzonProducts\Facades\OzonProducts;
    
    $product = \App\Models\Product::find(1);
    $ozonProduct = OzonProducts::syncProduct($product);
    
    • Assumes your Product model has fields matching Ozon’s API requirements (e.g., title, description, price, sku).
  4. Verify:

    • Check Ozon’s sandbox or production dashboard for the synced product.
    • Review Laravel logs for errors (e.g., authentication failures, validation issues).

Implementation Patterns

Core Workflows

1. Product Synchronization

  • Bulk Sync:

    OzonProducts::syncProducts(\App\Models\Product::where('needs_sync', true)->get());
    
  • Queued Sync (for large catalogs):

    \App\Models\Product::where('needs_sync', true)->each(function ($product) {
        SyncOzonProduct::dispatch($product);
    });
    
    • Requires a custom job (SyncOzonProduct) extending ShouldQueue.
  • Event-Driven Sync: Listen for product updates and trigger syncs:

    \App\Models\Product::observe(OzonProductsObserver::class);
    
    • Implement OzonProductsObserver to hook into saved, updated, or deleted events.

2. Inventory Management

  • Update inventory levels:
    $product = \App\Models\Product::find(1);
    OzonProducts::updateInventory($product, ['quantity' => 50]);
    
  • Batch inventory updates:
    $products = \App\Models\Product::where('inventory_needs_update', true)->get();
    OzonProducts::batchUpdateInventory($products);
    

3. Order Management

  • Fetch orders from Ozon:
    $orders = OzonProducts::getOrders(['status' => 'new']);
    
  • Process orders (e.g., mark as shipped):
    OzonProducts::updateOrderStatus($orderId, 'shipped');
    

4. Webhook Handling

  • Register a webhook endpoint for Ozon’s real-time updates:
    Route::post('/ozon-webhook', [OzonWebhookController::class, 'handle']);
    
  • Controller example:
    public function handle(Request $request) {
        $payload = $request->json()->all();
        OzonProducts::handleWebhook($payload);
    }
    
  • Extend OzonProducts::handleWebhook() to process specific events (e.g., product_updated, order_canceled).

Integration Tips

1. Model Mapping

  • Ensure your Product model includes Ozon-specific fields:
    class Product extends Model
    {
        protected $casts = [
            'ozon_id' => 'integer',
            'external_seller_id' => 'string',
            'price' => 'float',
            'quantity' => 'integer',
        ];
    
        protected $fillable = [
            'title', 'description', 'sku', 'price', 'quantity', 'ozon_id', 'external_seller_id',
        ];
    }
    
  • Use accessors/mutators to transform data between your schema and Ozon’s API:
    public function getOzonAttributes()
    {
        return [
            'name' => $this->title,
            'description' => $this->description,
            'price' => $this->price,
            'sku' => $this->sku,
            'quantity' => $this->quantity,
        ];
    }
    

2. Authentication

  • The package likely uses OAuth2. Configure the OzonProductsServiceProvider to handle token refresh:
    'auth' => [
        'client_id' => env('OZON_CLIENT_ID'),
        'client_secret' => env('OZON_CLIENT_SECRET'),
        'token_url' => 'https://auth.ozon.ru/token',
        'refresh_token' => env('OZON_REFRESH_TOKEN'),
    ],
    
  • Manually refresh tokens if needed:
    OzonProducts::refreshAuthToken();
    

3. Error Handling

  • Catch exceptions and retry failed requests:
    try {
        OzonProducts::syncProduct($product);
    } catch (\BaksDev\OzonProducts\Exceptions\OzonApiException $e) {
        \Log::error('Ozon sync failed: ' . $e->getMessage());
        $this->retrySync($product);
    }
    

4. Testing

  • Run the package’s tests in your environment:
    php bin/phpunit --group=ozon-products
    
  • Mock Ozon’s API responses in your tests:
    $mockHandler = \Mockery::mock(\GuzzleHttp\Handler\MockHandler::class);
    $mockHandler->shouldReceive('handle')
        ->once()
        ->andReturn(new \GuzzleHttp\Psr7\Response(200, [], '{"id": 123}'));
    

5. Extending Functionality

  • Custom API Endpoints: Use the package’s HTTP client to make raw API calls:
    $response = OzonProducts::get('products/search', ['text' => 'test']);
    
  • Middleware: Add middleware to transform requests/responses:
    OzonProducts::getClient()->getEmitter()->getMiddlewareStack()
        ->push(\App\Http\Middleware\LogOzonRequests::class);
    

Gotchas and Tips

Pitfalls

1. Schema Mismatches

  • Issue: Ozon’s API expects specific fields (e.g., external_seller_id, delivery_cost). Missing or incorrectly named fields cause validation errors.
  • Fix: Audit your Product model against Ozon’s API docs and use accessors to map fields:
    public function getExternalSellerIdAttribute()
    {
        return $this->ozon_seller_id ?? 'default_seller_id';
    }
    

2. Rate Limiting

  • Issue: Ozon’s API enforces rate limits (e.g., 10 requests/second). Bulk operations may hit limits and fail silently.
  • Fix:
    • Use batching:
      OzonProducts::syncProducts($products, ['batch_size' => 5]);
      
    • Implement exponential backoff in middleware:
      OzonProducts::getClient()->getEmitter()->getMiddlewareStack()
          ->push(\BaksDev\OzonProducts\Middleware\RateLimitMiddleware::class);
      

3. Authentication Failures

  • Issue: Expired tokens or incorrect credentials cause 401 Unauthorized errors.
  • Fix:
    • Ensure OZON_REFRESH_TOKEN is set in .env.
    • Manually refresh tokens:
      php artisan ozon:refresh-token
      
    • Log token refresh events:
      OzonProducts::getClient()->getEmitter()->getMiddlewareStack()
          ->push(\App\Http\Middleware\LogTokenRefresh::class);
      

4. Data Conflicts

  • Issue: Ozon’s API may return products with conflicting data (e.g., price discrepancies). The package may overwrite your local data without warning.
  • Fix:
    • Implement a merge strategy in your model:
      public function updateFromOzon(array $ozonData)
      {
          $this->price = $ozonData['price'] ?? $this->price;
          $this->quantity = $ozonData['quantity'] ?? $this->quantity;
          $this->save();
      }
      
    • Use Laravel’s upsert for conflict resolution:
      \DB::table('products')->upsert(
          $ozonData,
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor