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 Setup

  1. Install the Package

    composer require baks-dev/ozon
    
  2. Publish Configuration

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

    This generates a .env file with Ozon API credentials (client ID, secret, etc.).

  3. Configure .env

    OZON_CLIENT_ID=your_client_id
    OZON_CLIENT_SECRET=your_client_secret
    OZON_SANDBOX=true  # Set to false for production
    
  4. First Use Case: Fetch Orders

    use BaksDev\Ozon\Facades\OzonApi;
    
    $orders = OzonApi::orders()->fetch();
    

    This retrieves a collection of orders from Ozon’s API.


Implementation Patterns

Core Workflows

1. Catalog Management

  • List Products
    $products = OzonApi::products()->list(['limit' => 100]);
    
  • Create/Update Product
    $product = OzonApi::products()->create([
        'name' => 'Test Product',
        'price' => 1000,
        // ... other fields
    ]);
    

2. Order Processing

  • Fetch Orders
    $orders = OzonApi::orders()->fetch(['status' => 'new']);
    
  • Fulfill Order
    OzonApi::orders()->fulfill($orderId, [
        'tracking_number' => 'TRACK123',
        'carrier' => 'ozon'
    ]);
    

3. Shipment Tracking

  • Track Shipment
    $shipment = OzonApi::shipments()->track($trackingNumber);
    

4. Webhooks (Event-Driven)

  • Register Webhook Listener
    OzonApi::webhooks()->listen('orders.created', function ($payload) {
        // Handle new order
    });
    
  • Verify Webhook Signature (if using Ozon’s webhook system)
    $isValid = OzonApi::webhooks()->verify($payload, $signature);
    

Integration Tips

  • Use Facades for Simplicity Leverage the OzonApi facade to reduce boilerplate in controllers/blades:

    OzonApi::products()->list(); // Instead of resolving the service manually
    
  • Dependency Injection for Services For better testability, inject the service directly:

    use BaksDev\Ozon\Contracts\OzonClient;
    
    public function __construct(private OzonClient $ozonClient) {}
    
  • Queue Async Operations Offload long-running tasks (e.g., bulk order processing) to queues:

    dispatch(new ProcessOzonOrders($ozonClient));
    
  • Extend with Custom Logic Create a service layer to wrap Ozon API calls with business logic:

    class OzonOrderService {
        public function __construct(private OzonClient $ozonClient) {}
    
        public function syncOrders() {
            $orders = $this->ozonClient->orders()->fetch();
            foreach ($orders as $order) {
                // Custom logic (e.g., update inventory, notify warehouse)
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Quirks

    • Token Refresh: The package may not handle OAuth token refresh automatically. Implement a fallback:
      try {
          $response = OzonApi::orders()->fetch();
      } catch (\BaksDev\Ozon\Exceptions\OzonAuthException $e) {
          OzonApi::auth()->refreshToken();
          retry();
      }
      
    • Sandbox vs. Production: Always test in Ozon’s sandbox (OZON_SANDBOX=true) before going live.
  2. Rate Limiting

    • Ozon enforces rate limits (e.g., 100 requests/minute). Use Laravel’s throttle middleware or implement retries:
      use Illuminate\Support\Facades\RateLimiter;
      
      if (!RateLimiter::tooManyAttempts('ozon-api', 100)) {
          $response = OzonApi::orders()->fetch();
      }
      
  3. Data Mapping Issues

    • Ozon’s API responses may not align with your Laravel models. Use DTOs or casting to normalize data:
      $order = OzonApi::orders()->fetch()->first();
      $order->cast([
          'created_at' => 'datetime:Y-m-d H:i:s',
      ]);
      
  4. Webhook Delays

    • Ozon’s webhooks may have delays (up to 5 minutes). Use exponential backoff for retries:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              OzonApi::webhooks()->process($payload);
              break;
          } catch (\Exception $e) {
              sleep(2 ** $attempts); // Exponential backoff
              $attempts++;
          }
      }
      
  5. Error Handling

    • Ozon returns custom error codes (e.g., 422 for validation errors). Extend the exception handler:
      OzonApi::catch(\BaksDev\Ozon\Exceptions\OzonValidationException::class, function ($e) {
          return response()->json(['error' => $e->getMessage()], 422);
      });
      

Debugging Tips

  • Log Raw API Responses Enable debug mode to log requests/responses:

    OZON_DEBUG=true
    

    Check logs in storage/logs/laravel.log.

  • Use Ozon’s Sandbox Test all endpoints in Ozon’s sandbox before production:

    OZON_SANDBOX=true
    OZON_SANDBOX_URL=https://sandbox.ozon.ru
    
  • Mock the Client for Testing Override the Ozon client in tests:

    $this->app->instance(
        \BaksDev\Ozon\Contracts\OzonClient::class,
        Mockery::mock(\BaksDev\Ozon\Contracts\OzonClient::class)
    );
    

Extension Points

  1. Custom Endpoints Extend the package to support unsupported Ozon API endpoints:

    class CustomOzonClient extends \BaksDev\Ozon\OzonClient {
        public function customEndpoint($params) {
            return $this->get('custom/endpoint', $params);
        }
    }
    
  2. Add New Resources Create a new repository for unsupported resources (e.g., ReturnsRepository):

    namespace BaksDev\Ozon\Repositories;
    
    class ReturnsRepository extends BaseRepository {
        protected $endpoint = 'returns';
    }
    
  3. Event Extensions Dispatch custom events for Ozon API responses:

    OzonApi::orders()->fetch()->each(function ($order) {
        event(new OzonOrderReceived($order));
    });
    
  4. Queue Jobs for Async Processing Create a job to handle Ozon webhooks asynchronously:

    class ProcessOzonWebhook implements ShouldQueue {
        public function handle() {
            OzonApi::webhooks()->process($this->payload);
        }
    }
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
testo/output-teamcity
testo/bridge-symfony