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

baks-dev/ozon-orders

Laravel/PHP модуль для интеграции заказов Ozon (FBS/DBS). Установка через Composer, команды консоли для добавления типа профиля, оплаты и доставки для Ozon. Поддерживает PHP 8.4+, включает тесты (группа ozon-orders).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require baks-dev/ozon-orders
    

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

  2. Publish Configuration (if needed) Check for config files (e.g., config/ozon-orders.php) and publish them:

    php artisan vendor:publish --provider="BaksDev\OzonOrders\OzonOrdersServiceProvider"
    
  3. Set Up Ozon Credentials Add your Ozon API credentials (e.g., OZON_API_KEY, OZON_SECRET_KEY) to your .env:

    OZON_FBS_API_KEY=your_fbs_key
    OZON_DBS_API_KEY=your_dbs_key
    
  4. Run Initialization Commands Choose either FBS or DBS (or both):

    # For FBS
    php artisan baks:users-profile-type:ozon-fbs
    php artisan baks:payment:ozon-fbs
    php artisan baks:delivery:ozon-fbs
    
    # For DBS
    php artisan baks:users-profile-type:ozon-dbs
    php artisan baks:payment:ozon-dbs
    php artisan baks:delivery:ozon-dbs
    
  5. Set Up Webhook Endpoint Create a route to handle Ozon webhooks (e.g., routes/web.php):

    Route::post('/ozon/webhook', [OzonWebhookController::class, 'handle']);
    

    Implement OzonWebhookController to process incoming webhook events (see Gotchas).

  6. Test with Sandbox Run PHPUnit tests to validate basic functionality:

    php artisan test --group=ozon-orders
    

First Use Case: Syncing an Order

To create an order in Ozon via the package:

use BaksDev\OzonOrders\Facades\OzonOrder;

$orderData = [
    'external_id' => 'your_order_id_123',
    'items' => [
        ['external_id' => 'sku_456', 'price' => 1000, 'quantity' => 2],
    ],
    'buyer' => ['email' => 'customer@example.com', 'phone' => '+79123456789'],
];

$ozonOrder = OzonOrder::create($orderData, 'fbs'); // or 'dbs'

Implementation Patterns

Core Workflows

1. Order Management

  • Creation: Use OzonOrder::create() with fbs/dbs mode.
  • Status Updates: Listen for order.status_changed events (webhook-triggered).
  • Cancellations/Refunds: Extend via custom logic (not natively supported).

2. Payment Processing

  • FBS/DBS Payments: Configured via CLI (baks:payment:ozon-{fbs|dbs}).
  • Webhook Handling: Process payment.status_changed events in your controller.
    public function handlePaymentWebhook(Request $request) {
        $event = OzonWebhook::parse($request->json()->all());
        if ($event->type === 'payment.status_changed') {
            Payment::syncWithOzon($event->data);
        }
    }
    

3. Delivery Integration

  • Carrier Assignment: CLI sets up DBS carriers (e.g., baks:delivery:ozon-dbs).
  • Tracking Updates: Webhook delivery.status_changed triggers sync:
    public function handleDeliveryWebhook(Request $request) {
        $event = OzonWebhook::parse($request->json()->all());
        if ($event->type === 'delivery.status_changed') {
            Delivery::updateTracking($event->data);
        }
    }
    

Integration Tips

Laravel-Specific Patterns

  1. Service Providers Bind the package’s services in AppServiceProvider:

    $this->app->singleton(OzonOrder::class, function ($app) {
        return new OzonOrder($app->make(OzonClient::class));
    });
    
  2. Queue Jobs for Async Processing Offload webhook handling to queues:

    public function handleWebhook(Request $request) {
        OzonWebhookJob::dispatch($request->json()->all());
    }
    
  3. Events and Listeners Dispatch custom events for order/payment lifecycle:

    // In OzonOrder::create()
    event(new OrderCreated($ozonOrder));
    
    // Listen in EventServiceProvider
    protected $listen = [
        OrderCreated::class => [
            SyncInventory::class,
            NotifyCustomer::class,
        ],
    ];
    
  4. API Client Customization Extend OzonClient for retries/timeouts:

    $client = new OzonClient([
        'timeout' => 30,
        'retry' => 3,
    ]);
    

Multi-Environment Setup

  • Sandbox vs. Production: Use environment-specific configs:
    OZON_SANDBOX=true  # Enable sandbox mode in .env
    
    Override the client in AppServiceProvider:
    $client = config('ozon.sandbox')
        ? new OzonClient(['sandbox' => true])
        : new OzonClient();
    

Gotchas and Tips

Pitfalls

  1. Webhook Idempotency

    • Ozon may resend webhooks. Ensure your endpoint is idempotent:
      public function handle(Request $request) {
          $signature = $request->header('X-Ozon-Signature');
          if (!OzonWebhook::validateSignature($request->json()->all(), $signature)) {
              abort(403, 'Invalid signature');
          }
          // Process only if not already handled
          if (!OzonWebhook::isProcessed($request->json()->all())) {
              OzonWebhook::markAsProcessed($request->json()->all());
              // ... handle logic
          }
      }
      
  2. Schema Assumptions

    • The package expects tables like users_profile_types, payments, and deliveries. If your schema differs:
      • Extend the package’s models or create migrations to match.
      • Example migration for ozon_orders:
        Schema::create('ozon_orders', function (Blueprint $table) {
            $table->id();
            $table->string('external_id')->unique();
            $table->string('ozon_id')->nullable();
            $table->enum('mode', ['fbs', 'dbs']);
            $table->json('metadata');
            $table->timestamps();
        });
        
  3. CLI Command Idempotency

    • Running CLI commands multiple times may cause duplicates. Add checks:
      // In your command
      if (ProfileType::where('name', 'ozon_fbs')->exists()) {
          $this->info('Profile type already exists.');
          return;
      }
      
  4. Rate Limiting

    • Ozon’s API has rate limits. Implement exponential backoff in OzonClient:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $client = new RetryableHttpClient([
          'max_retries' => 3,
          'delay' => 1000,
          'multiplier' => 2,
      ]);
      
  5. Timezone Mismatches

    • Ozon uses UTC. Ensure your Laravel app’s timezone matches:
      APP_TIMEZONE=UTC
      

Debugging Tips

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

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

    Then log requests/responses in OzonClient:

    \Log::channel('ozon')->debug('Ozon API Request', [
        'url' => $url,
        'data' => $data,
        'response' => $response->getContent(),
    ]);
    
  2. Validate API Responses Use Laravel’s Validator to check Ozon responses:

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($response->json(), [
        'result' => 'required|boolean',
        'data' => 'sometimes|array',
        'errors' => 'sometimes|array',
    ]);
    
    if ($validator->fails()) {
        \Log::error('Ozon API validation failed', $validator->errors());
        throw new \RuntimeException('Ozon API error');
    }
    
  3. Sandbox Testing Test thoroughly in Ozon’s sandbox before going live:

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