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

baks-dev/ozon-package

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require baks-dev/ozon-package
    

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

  2. Publish Assets and Configure Run the installation command to set up configuration files and migrations:

    php artisan baks:assets:install
    

    This generates:

    • Config files in config/ozon.php
    • Migration files in database/migrations/
    • Optional: Service provider registration (check config/app.php for Baks\OzonPackage\OzonPackageServiceProvider).
  3. Run Migrations Apply the database schema changes:

    php artisan doctrine:migrations:migrate
    

    Verify the ozon_orders, ozon_shipping, and related tables are created.

  4. First Use Case: Packaging an Order Inject the OzonOrderPackager service into a controller or command:

    use Baks\OzonPackage\Services\OzonOrderPackager;
    
    public function __construct(private OzonOrderPackager $packager) {}
    
    public function handleOrder(Order $order) {
        $packagingData = $this->packager->generatePackaging($order);
        // $packagingData includes Ozon-compliant box dimensions, weight, etc.
        return response()->json($packagingData);
    }
    
  5. Test the Integration Run the package-specific tests to validate core functionality:

    php artisan test --group=ozon-package
    

Implementation Patterns

Core Workflows

1. Order Packaging

  • Pattern: Use the OzonOrderPackager service to generate Ozon-compliant packaging templates.
  • Example:
    $packager = app(OzonOrderPackager::class);
    $template = $packager->generatePackaging($order, [
        'box_type' => 'standard', // or 'fragile', 'oversized'
        'include_branding' => true,
    ]);
    
  • Customization: Override default packaging rules by extending the OzonPackagingConfig class or binding a custom service.

2. Shipping Label Generation

  • Pattern: Use the OzonShippingLabelGenerator to create PLP (Prepaid Label Printing) or shipping labels.
  • Example:
    $labelGenerator = app(OzonShippingLabelGenerator::class);
    $labelData = $labelGenerator->generateLabel($order, $carrier);
    $labelUrl = $labelGenerator->downloadLabel($labelData);
    
  • Integration: Hook into Laravel’s queue system for async label generation during order processing.

3. Webhook Handling

  • Pattern: Register Ozon webhook listeners using Laravel’s event system.
  • Example:
    // In a service provider or EventServiceProvider
    event(new OzonWebhookReceived($payload));
    
  • Common Events:
    • order_created
    • order_status_updated
    • shipment_sent
    • refund_processed
  • Validation: Use the OzonWebhookValidator to verify payload signatures and structure.

4. Order Sync

  • Pattern: Sync orders from Ozon to your database using the OzonOrderSync service.
  • Example:
    $sync = app(OzonOrderSync::class);
    $sync->fetchAndStoreOrders(); // Fetches from Ozon API and saves to DB
    
  • Scheduling: Run this via Laravel’s scheduler (e.g., php artisan schedule:run) or as a queue job.

Integration Tips

Laravel Ecosystem

  • Service Binding: Bind custom implementations of package interfaces for testing or extensions:
    $this->app->bind(
        OzonOrderPackager::class,
        fn() => new CustomOzonOrderPackager()
    );
    
  • Events: Extend package events by listening to them in your EventServiceProvider:
    protected $listen = [
        'ozon.order.packaged' => [
            \App\Listeners\NotifyWarehouse::class,
        ],
    ];
    
  • Commands: Extend the package’s console commands by creating custom commands that use its services.

Database

  • Schema Conflicts: If your app already has order tables, merge the package’s migrations or use a custom schema:
    // In a custom migration
    Schema::create('ozon_orders', function (Blueprint $table) {
        // Add Ozon-specific fields to your existing order table
        $table->string('ozon_order_id')->unique();
        $table->json('ozon_metadata');
    });
    
  • Repositories: Use the package’s OzonOrderRepository or create a custom repository that extends it.

API Integration

  • Rate Limiting: Implement retries for API calls using Laravel’s Illuminate\Support\Facades\Retry:
    use Illuminate\Support\Facades\Retry;
    
    Retry::retry(3, function () {
        $response = $ozonClient->get('/orders');
    }, 100); // 100ms delay between retries
    
  • Logging: Log API interactions for debugging:
    \Log::channel('ozon')->info('API Request', [
        'endpoint' => $endpoint,
        'payload' => $payload,
        'response' => $response,
    ]);
    

Testing

  • Mocking: Mock the OzonClient interface in tests:
    $this->mock(OzonClient::class)->shouldReceive('getOrders')->andReturn([...]);
    
  • Test Coverage: Focus on:
    • Order packaging edge cases (e.g., oversized items, fragile goods).
    • Webhook payload validation.
    • API error scenarios (e.g., rate limits, invalid responses).

Gotchas and Tips

Pitfalls

  1. Assumptions About Order Structure

    • The package assumes orders have specific fields (e.g., weight, dimensions). If your order model differs, extend the OzonOrderMapper or create a custom mapper:
      $mapper = new CustomOzonOrderMapper($order);
      $ozonOrder = $mapper->map();
      
  2. Webhook Signature Validation

    • Ozon webhooks require signature validation. The package provides a validator, but ensure your ozon.php config includes the correct secret:
      'webhook' => [
          'secret' => env('OZON_WEBHOOK_SECRET'),
      ],
      
    • Gotcha: If the secret is misconfigured, webhooks will fail silently. Enable logging for ozon.webhook to debug.
  3. Database Conflicts

    • The package’s migrations may conflict with existing orders tables. Solution:
      • Use a custom migration that merges schemas.
      • Disable the package’s migrations by commenting out the OzonMigrations service provider.
  4. API Version Mismatches

    • The package may not support the latest Ozon API version. Solution:
      • Check the CHANGELOG.md for API version compatibility.
      • Override the OzonClient to use a custom API version:
        $client = new OzonClient(env('OZON_API_KEY'), 'v3');
        
  5. Label Generation Dependencies

    • Some label generation features may require external libraries (e.g., for PDF creation). Ensure these are installed:
      composer require dompdf/dompdf
      
  6. Queue Jobs for Async Processing

    • The package does not include built-in queue support for async operations (e.g., label generation). Solution:
      • Dispatch jobs manually:
        GenerateOzonLabelJob::dispatch($order, $carrier);
        

Debugging Tips

  1. Enable Debug Logging Add this to config/logging.php:

    'channels' => [
        'ozon' => [
            'driver' => 'single',
            'path' => storage_path('logs/ozon.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log API interactions:

    \Log::ozon()->debug('Ozon API Response', ['data' => $response]);
    
  2. Validate API Responses Use the OzonResponseValidator to check for errors:

    $validator = new OzonResponseValidator();
    if (!$validator->isValid($response)) {
        \Log::error('Invalid Ozon API response', ['errors' => $validator->getErrors()]);
    }
    
  3. Test Webhooks Locally Use Laravel’s queue:work to process webhooks in development:

    php artisan queue:work
    

    Simulate webhooks with:

    php artisan ozons:webhook:test order_created
    
  4. Check for Deprecated Methods The package may use deprecated Ozon API endpoints. Solution:

    • Override the
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
andydefer/laravel-cluster
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