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

Yandex Market Laravel Package

baks-dev/yandex-market

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require baks-dev/yandex-market
    php artisan vendor:publish --provider="BaksDev\YandexMarket\YandexMarketServiceProvider"
    

    Publish the config file to customize API endpoints, token storage, and queue settings.

  2. Environment Setup: Add Yandex Market API credentials and queue configuration to .env:

    YANDEX_MARKET_TOKEN=your_oauth_token_here
    MESSENGER_TRANSPORT_DSN=redis://localhost:6379/1
    
  3. First Use Case: Fetch a product by ID synchronously:

    use BaksDev\YandexMarket\Facades\YandexMarket;
    
    $product = YandexMarket::products()->get(12345);
    dd($product);
    
  4. Run Asset Installation (if needed for additional resources):

    php artisan baks:assets:install
    

Implementation Patterns

Usage Patterns

  1. Synchronous API Calls: Use facades or service container bindings for direct API interactions:

    // Via Facade
    $orders = YandexMarket::orders()->list(['limit' => 10]);
    
    // Via Service Container
    $client = app(\BaksDev\YandexMarket\Contracts\YandexMarketClient::class);
    $client->products()->create($productData);
    
  2. Asynchronous Processing with Queues: Leverage Symfony Messenger for background tasks. Configure per-token queues:

    // In a service provider or config
    $messenger->transport('yandex_market_token_1')
        ->dsn('%env(MESSENGER_TRANSPORT_DSN)%')
        ->options(['queue_name' => 'yandex_market_products'])
        ->retryStrategy()
        ->maxRetries(3);
    

    Dispatch a queued job:

    use BaksDev\YandexMarket\Messages\SyncProductCatalog;
    
    $message = new SyncProductCatalog($productIds);
    $message->setToken('yandex_market_token_1');
    $bus->dispatch($message);
    
  3. Bulk Operations: Use batch processing for high-volume tasks (e.g., catalog syncs):

    $batch = YandexMarket::products()->batch();
    foreach ($products as $product) {
        $batch->add($product);
    }
    $batch->sync(); // Queues each product for async processing
    
  4. Event Listeners: Subscribe to Yandex Market webhook events (if supported) or process queue failures:

    // Example: Handle failed queue jobs
    public function handleFailedJob(FailedJob $event)
    {
        if ($event->job instanceof SyncProductCatalog) {
            // Retry logic or alert
        }
    }
    

Workflows

  1. Product Catalog Sync:

    • Step 1: Fetch product data from your system.
    • Step 2: Use YandexMarket::products()->batch()->sync() to queue updates.
    • Step 3: Monitor queue workers for completion.
  2. Order Fulfillment:

    • Step 1: Listen for new orders via webhooks (if enabled) or poll the API.
    • Step 2: Dispatch a ProcessOrder message to the queue:
      $message = new ProcessOrder($orderId, $fulfillmentData);
      $bus->dispatch($message);
      
    • Step 3: Process fulfillment in the queue worker (e.g., update inventory, notify seller).
  3. Dynamic Pricing:

    • Step 1: Fetch current prices from Yandex Market:
      $prices = YandexMarket::pricing()->get();
      
    • Step 2: Adjust your system’s prices based on the response.
    • Step 3: Queue a price update if needed:
      $message = new UpdatePricing($adjustedPrices);
      $bus->dispatch($message);
      

Integration Tips

  1. Laravel Service Provider: Bind the package’s client to an interface for easier mocking in tests:

    $this->app->bind(
        \BaksDev\YandexMarket\Contracts\YandexMarketClient::class,
        \BaksDev\YandexMarket\YandexMarketClient::class
    );
    
  2. Custom Transports: If using Laravel’s queue system instead of Messenger, create a custom transport:

    // app/Providers/YandexMarketServiceProvider.php
    public function boot()
    {
        $this->app->extend(
            \BaksDev\YandexMarket\Contracts\YandexMarketClient::class,
            function ($client) {
                $client->setTransport(new LaravelQueueTransport());
                return $client;
            }
        );
    }
    
  3. Testing: Use PHPUnit’s testing group to run package-specific tests:

    php artisan test --group=yandex-market
    

    Mock the HTTP client for unit tests:

    $this->mock(\BaksDev\YandexMarket\Http\YandexMarketHttpClient::class)
        ->shouldReceive('get')
        ->andReturn($mockResponse);
    
  4. Error Handling: Catch YandexMarketException for API-specific errors:

    try {
        $product = YandexMarket::products()->get($id);
    } catch (\BaksDev\YandexMarket\Exceptions\YandexMarketException $e) {
        Log::error("Yandex Market API error: " . $e->getMessage());
        // Retry or notify admin
    }
    

Gotchas and Tips

Pitfalls

  1. Queue Configuration:

    • Issue: Forgetting to configure per-token queues can lead to throttling or mixed data.
    • Fix: Ensure each token has a dedicated queue name in Messenger:
      ->options(['queue_name' => 'token_' . $tokenId])
      
  2. Token Management:

    • Issue: Hardcoded tokens or lack of rotation logic may expose credentials.
    • Fix: Store tokens in Laravel’s .env or a secure vault (e.g., AWS Secrets Manager). Implement a token refresh mechanism:
      // Example: Refresh token before expiration
      $client->refreshToken();
      
  3. API Rate Limits:

    • Issue: Yandex Market may throttle requests during bulk operations.
    • Fix: Implement exponential backoff in retry logic or use Laravel’s throttle middleware:
      Route::middleware(['throttle:60,1'])->group(function () {
          // Yandex Market API routes
      });
      
  4. Data Mismatches:

    • Issue: Inconsistent data between your system and Yandex Market (e.g., SKU mismatches).
    • Fix: Validate responses and implement idempotency keys for critical operations:
      $response = YandexMarket::products()->create($data, ['idempotency_key' => uniqid()]);
      
  5. Package Updates:

    • Issue: Breaking changes in future package versions may disrupt functionality.
    • Fix: Pin the package version in composer.json or monitor the GitHub repo for updates:
      "baks-dev/yandex-market": "7.4.7"
      

Debugging

  1. Queue Debugging:

    • Enable Messenger debug mode in .env:
      MESSENGER_DEBUG=true
      
    • Check queue workers for stuck jobs:
      php artisan queue:work --queue=yandex_market_products --verbose
      
  2. API Response Logging:

    • Wrap the client to log raw responses:
      $client = app(YandexMarketClient::class);
      $client->setLogger(new CustomLogger());
      
  3. Token Validation:

    • Verify token expiration and permissions:
      try {
          $client->validateToken();
      } catch (\BaksDev\YandexMarket\Exceptions\InvalidTokenException $e) {
          // Regenerate token
      }
      
  4. HTTP Client Issues:

    • If using Laravel’s HTTP client, ensure it’s properly configured in config/http.php:
      'timeout' => 30,
      'connect_timeout' => 10,
      

Config Quirks

  1. Custom Endpoints:

    • Override default API endpoints in config/yandex-market.php:
      'endpoints' => [
          'products' => 'https://market.yandex.ru/api/v2/products',
      ],
      
  2. Retry Strategy:

    • Adjust retry settings in Messenger config:
      ->retryStrategy()
          ->maxRetries(5)
          ->delay(1000)
          ->maxDelay(60000)
          ->multiplier
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui