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

baks-dev/ozon-support

Модуль техподдержки Ozon для Laravel/Symfony: установка через Composer, добавление типа профиля Ozon Support командой baks:users-profile-type:ozon-support, запуск тестов PHPUnit (группа ozon-support). Требуется PHP 8.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/ozon-support
    

    Ensure your project uses PHP 8.4+ and Laravel/Symfony.

  2. Register Ozon Support Profile Type Run the console command to add the Ozon-specific user profile:

    php artisan baks:users-profile-type:ozon-support
    

    This creates the necessary database tables and migrations.

  3. Configure Ozon API Credentials Add your Ozon API credentials (client ID, client secret, etc.) to your .env file or Laravel config. Example:

    OZON_CLIENT_ID=your_client_id
    OZON_CLIENT_SECRET=your_client_secret
    OZON_REDIRECT_URI=http://your-app.com/ozon/callback
    
  4. First Use Case: OAuth Authentication Use the provided OAuth service to authenticate with Ozon:

    use Baks\OzonSupport\Facades\OzonAuth;
    
    $authUrl = OzonAuth::getAuthorizationUrl();
    // Redirect user to $authUrl to start OAuth flow.
    
    // After callback, exchange code for token:
    $token = OzonAuth::exchangeCodeForToken($authorizationCode);
    
  5. Test the Integration Run the package-specific tests to verify functionality:

    php artisan phpunit --group=ozon-support
    

Implementation Patterns

Usage Patterns

1. OAuth Flow Integration

  • Pattern: Use the OzonAuth facade to handle OAuth2 authentication.
  • Workflow:
    1. Generate an authorization URL:
      $authUrl = OzonAuth::getAuthorizationUrl(['scope' => 'Orders.ReadWrite']);
      
    2. Handle the callback in your routes:
      Route::get('/ozon/callback', function ($request) {
          $token = OzonAuth::exchangeCodeForToken($request->query('code'));
          // Store token in session/database.
      });
      
    3. Refresh tokens when expired:
      $refreshedToken = OzonAuth::refreshToken($refreshToken);
      

2. Order Management

  • Pattern: Use the OzonOrderService to create, update, and fetch orders.

  • Example: Create an Order

    use Baks\OzonSupport\Services\OzonOrderService;
    
    $orderService = app(OzonOrderService::class);
    $orderData = [
        'external_id' => 'ORDER_123',
        'items' => [
            ['external_id' => 'PROD_456', 'price' => 1000, 'quantity' => 2],
        ],
    ];
    $createdOrder = $orderService->create($orderData);
    
  • Example: Fetch Orders

    $orders = $orderService->getOrders(['limit' => 10]);
    

3. Webhook Handling

  • Pattern: Register webhook listeners for real-time updates (e.g., order cancellations, payment status changes).
  • Example: Register a Webhook Listener
    use Baks\OzonSupport\Events\OzonWebhookReceived;
    
    Event::listen(OzonWebhookReceived::class, function ($event) {
        $payload = $event->payload;
        if ($payload['event_type'] === 'order_cancelled') {
            // Handle cancellation logic.
        }
    });
    
  • Verify Webhook Signatures (if enabled):
    $isValid = OzonAuth::validateWebhookSignature($payload, $signature);
    

4. Profile Management

  • Pattern: Attach Ozon profiles to users for personalized integrations.
  • Example: Create an Ozon Profile for a User
    use Baks\OzonSupport\Models\OzonProfile;
    
    $user = auth()->user();
    $ozonProfile = OzonProfile::create([
        'user_id' => $user->id,
        'ozon_shop_id' => '12345',
        'access_token' => $token,
    ]);
    

5. CLI Workflows

  • Pattern: Use artisan commands for administrative tasks.
  • Example: Sync Ozon Inventory
    php artisan ozon:sync-inventory --shop-id=12345
    
  • Example: Generate Ozon Reports
    php artisan ozon:generate-report --type=sales --days=7
    

Integration Tips

  1. Laravel Service Providers

    • Bind custom services to the container for extended functionality:
      $this->app->bind(
          CustomOzonService::class,
          function ($app) {
              return new CustomOzonService(
                  $app->make(OzonOrderService::class),
                  $app->make(OzonAuth::class)
              );
          }
      );
      
  2. Event-Driven Extensions

    • Extend existing events (e.g., OzonOrderCreated) to trigger custom logic:
      Event::listen(OzonOrderCreated::class, function ($event) {
          // Send notification or update ERP system.
      });
      
  3. Testing Strategies

    • Mock the Ozon API responses in tests:
      $this->mock(OzonOrderService::class)
           ->shouldReceive('create')
           ->once()
           ->andReturn($mockOrder);
      
  4. Localization

    • Override hardcoded Russian strings by publishing the package’s language files:
      php artisan vendor:publish --provider="Baks\OzonSupport\OzonSupportServiceProvider" --tag=lang
      
    • Customize the resources/lang/ru/ozon.php file.
  5. Error Handling

    • Centralize Ozon API error handling using middleware:
      public function handle($request, Closure $next)
      {
          try {
              return $next($request);
          } catch (OzonApiException $e) {
              Log::error('Ozon API Error: ' . $e->getMessage());
              return response()->json(['error' => 'Ozon service unavailable'], 503);
          }
      }
      

Gotchas and Tips

Pitfalls

  1. OAuth Token Management

    • Pitfall: Tokens expire, and the package does not auto-refresh by default.
    • Fix: Implement a middleware to refresh tokens before expired:
      public function handle($request, Closure $next)
      {
          if (OzonAuth::isTokenExpired()) {
              $token = OzonAuth::refreshToken($request->user()->ozonProfile->refresh_token);
              $request->user()->ozonProfile->update(['access_token' => $token]);
          }
          return $next($request);
      }
      
  2. Webhook Signature Validation

    • Pitfall: Webhook signatures may fail if the secret key is misconfigured.
    • Fix: Verify the OZON_WEBHOOK_SECRET in .env matches Ozon’s configured secret.
  3. Database Schema Conflicts

    • Pitfall: Running migrations after initial setup may fail if tables already exist.
    • Fix: Check migration status first:
      php artisan migrate:status
      
      Roll back and re-run if needed:
      php artisan migrate:rollback --step=1
      php artisan migrate
      
  4. Rate Limiting

    • Pitfall: Ozon’s API has strict rate limits. Unoptimized calls may trigger throttling.
    • Fix: Implement exponential backoff in your service layer:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $client = new RetryableHttpClient(
          new HttpClient(),
          [
              'max_retries' => 3,
              'delay' => 1000,
              'multiplier' => 2,
              'statuses' => [429],
          ]
      );
      
  5. Hardcoded Values

    • Pitfall: Some values (e.g., Ozon API endpoints, scopes) may be hardcoded.
    • Fix: Override config via .env or publish the config:
      php artisan vendor:publish --provider="Baks\OzonSupport\OzonSupportServiceProvider" --tag=config
      

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 Ozon API responses:

    Log::channel('ozon')->debug('Ozon API Response', ['response' => $response]);
    
  2. Inspect Raw API Responses Use a debug middleware to log raw HTTP requests/responses:

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