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 Laravel Package

baks-dev/ozon

Laravel/PHP модуль для работы с Ozon API. Установка через Composer (baks-dev/ozon), поддержка PHP 8.4+, версия 7.4.10. В комплекте тесты PHPUnit (группа ozon). Лицензия MIT.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require baks-dev/ozon
    

    Ensure your project uses PHP 8.4+ and Laravel 10.x+.

  2. Publish Configuration:

    php artisan vendor:publish --provider="BaksDev\Ozon\OzonServiceProvider" --tag="config"
    

    Configure .env with Ozon API credentials:

    OZON_CLIENT_ID=your_client_id
    OZON_CLIENT_SECRET=your_client_secret
    OZON_SANDBOX=true  # Use sandbox for testing
    
  3. First API Call: Use the facade to fetch orders (example from README or tests):

    use BaksDev\Ozon\Facades\Ozon;
    
    $orders = Ozon::orders()->fetch();
    
  4. Run Tests: Validate the package works in your environment:

    php artisan test --group=ozon
    

Implementation Patterns

Core Workflows

  1. Order Management:

    • Fetch Orders:
      $orders = Ozon::orders()->fetch(['limit' => 10]);
      
    • Create Order Webhook Handler:
      public function handle(OzonOrderCreated $event) {
          // Process order in your system
          Order::create($event->orderData);
      }
      
  2. Catalog Sync:

    • Bulk Product Update:
      Ozon::products()->update([
          'id' => 123,
          'price' => 999.99,
          'available' => true,
      ]);
      
    • Inventory Sync Job:
      class SyncOzonInventory implements ShouldQueue {
          public function handle() {
              $ozonProducts = Ozon::products()->fetch();
              foreach ($ozonProducts as $product) {
                  Product::where('ozon_id', $product['id'])->update([
                      'stock' => $product['available_quantity'],
                  ]);
              }
          }
      }
      
  3. OAuth Integration:

    • Generate Auth URL:
      $authUrl = Ozon::auth()->getAuthorizationUrl();
      
    • Handle Callback:
      public function handleOzonCallback(Request $request) {
          $token = Ozon::auth()->getAccessToken($request->code);
          // Store token for future use
      }
      

Integration Tips

  • Use Queues for Async Operations: Offload heavy syncs (e.g., bulk updates) to queues to avoid timeouts:

    SyncOzonInventory::dispatch();
    
  • Leverage Laravel Events: Subscribe to Ozon events (e.g., OzonOrderCreated) to trigger business logic:

    // In EventServiceProvider
    protected $listen = [
        \BaksDev\Ozon\Events\OzonOrderCreated::class => [
            HandleOzonOrder::class,
        ],
    ];
    
  • Customize HTTP Client: Extend the package’s HTTP client for retries or middleware:

    // In OzonServiceProvider
    $this->app->singleton(OzonClient::class, function ($app) {
        return new OzonClient(
            $app->make(HttpClient::class)->withOptions([
                'timeout' => 30,
                'retry' => true,
            ])
        );
    });
    
  • Database Migrations: Create migrations to store Ozon data locally:

    Schema::create('ozon_orders', function (Blueprint $table) {
        $table->id();
        $table->string('ozon_id');
        $table->json('data');
        $table->timestamps();
    });
    

Gotchas and Tips

Pitfalls

  1. Sandbox vs. Production:

    • Always test in Ozon’s sandbox first. Forgetting to toggle OZON_SANDBOX can lead to real API calls.
    • Fix: Use a .env variable to switch environments:
      OZON_SANDBOX=${APP_ENV !== 'production'}
      
  2. Rate Limiting:

    • Ozon’s API enforces rate limits (e.g., 100 requests/minute). The package may not handle retries gracefully.
    • Fix: Configure Laravel’s HTTP client retries in config/http.php:
      'retry' => [
          'enabled' => true,
          'max_attempts' => 5,
          'delay' => 1000, // 1 second
      ],
      
  3. Missing Webhook Support:

    • The package lacks built-in webhook handling for real-time updates (e.g., order status changes).
    • Fix: Build a custom webhook endpoint:
      Route::post('/ozon/webhook', function (Request $request) {
          $payload = $request->json()->all();
          // Validate signature and process
          event(new OzonWebhookReceived($payload));
      });
      
  4. Error Handling:

    • Ozon API errors may not be translated into Laravel exceptions. Raw responses can clutter logs.
    • Fix: Extend the package’s exception handler:
      // app/Exceptions/Handler.php
      public function render($request, Throwable $exception) {
          if ($exception instanceof \BaksDev\Ozon\Exceptions\OzonApiException) {
              return response()->json([
                  'error' => 'Ozon API Error',
                  'message' => $exception->getMessage(),
              ], 422);
          }
          return parent::render($request, $exception);
      }
      
  5. Type Safety:

    • The package may return loosely typed arrays (e.g., fetch() returns array instead of a Collection or DTO).
    • Fix: Create DTOs for strong typing:
      class OzonOrderDto {
          public function __construct(
              public string $id,
              public array $items,
              public float $total,
          ) {}
      }
      

Debugging Tips

  1. Enable API Logging: Add middleware to log Ozon API requests/responses:

    // app/Http/Middleware/LogOzonRequests.php
    public function handle($request, Closure $next) {
        if ($request->is('ozon/*')) {
            \Log::info('Ozon API Request', $request->all());
        }
        return $next($request);
    }
    
  2. Validate API Responses: Use Laravel’s Http facade to inspect raw responses:

    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->get('https://api.ozon.ru/orders');
    
    \Log::debug('Ozon Response', $response->body());
    
  3. Test with Postman: Manually test Ozon endpoints using Postman with your credentials to isolate issues.

Extension Points

  1. Add Custom Endpoints: Extend the package’s client to support unsupported endpoints:

    // app/Services/OzonClientExtension.php
    public function customEndpoint(array $data) {
        return $this->client->post('https://api.ozon.ru/custom', $data);
    }
    
  2. Override Facade Methods: Replace facade methods in a service provider:

    // app/Providers/OzonServiceProvider.php
    public function register() {
        $this->app->bind('ozon', function () {
            return new CustomOzonService();
        });
    }
    
  3. Add New Events: Dispatch custom events for business logic:

    // In your service
    event(new OzonInventoryUpdated($productId, $newStock));
    
  4. Localize Error Messages: Translate Ozon API errors for users:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        \BaksDev\Ozon\Exceptions\OzonApiException::setTranslator(function ($message) {
            return __("ozon.errors.$message");
        });
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
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