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

Laravel/PHP пакет для работы с API Yandex Market: установка через Composer, установка конфигов и ресурсов, поддержка очередей Messenger с отдельным транспортом на токен, тесты PHPUnit. Требует PHP 8.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require baks-dev/yandex-market
    

    Ensure your project uses PHP 8.4+ and Laravel 10.x (or Symfony 6.4+ if using standalone).

  2. Publish Configuration and Assets

    php artisan vendor:publish --provider="BaksDev\YandexMarket\YandexMarketServiceProvider"
    php artisan baks:assets:install
    

    This generates config files (e.g., config/yandex-market.php) and sets up default resources.

  3. Configure Environment Variables Add to .env:

    YANDEX_MARKET_TOKEN=your_api_token_here
    MESSENGER_TRANSPORT_DSN=redis://localhost:6379/0
    

    For Laravel queues, ensure QUEUE_CONNECTION is configured (e.g., redis, database).

  4. First Use Case: Sync Products Asynchronously Dispatch a job to sync products to Yandex Market:

    use BaksDev\YandexMarket\Jobs\SyncProducts;
    
    SyncProducts::dispatch([
        'token' => 'your_token_uuid',
        'products' => $productData,
    ]);
    

    The job will automatically route to the configured queue (e.g., profile_name from the README).


Implementation Patterns

Usage Patterns

1. Token-Based Workflows

Each Yandex Market token (e.g., OAuth2 access token) maps to a dedicated queue transport. This isolates failures and rate limits per seller.

// Configure per-token queues in config/yandex-market.php
'tokens' => [
    'seller_1_uuid' => [
        'queue' => 'seller_1_orders',
        'retry_strategy' => [
            'max_retries' => 3,
            'delay' => 1000, // ms
            'multiplier' => 2,
        ],
    ],
];

2. Job Dispatching

Use Laravel’s queue system to dispatch Yandex Market jobs. Example:

// Sync orders with custom retry logic
SyncOrders::dispatch([
    'token' => 'seller_2_uuid',
    'orders' => $orderData,
    'priority' => 5, // Optional: Use Laravel's queue priority
])->onQueue('seller_2_orders');

3. Synchronous API Calls

For real-time operations (e.g., fetching a single product), use the client directly:

use BaksDev\YandexMarket\Client;

$client = app(Client::class)->withToken('your_token');
$product = $client->getProduct($productId);

4. Event Listeners

Listen to Yandex Market events (e.g., order status updates) via Laravel’s event system:

// In EventServiceProvider
protected $listen = [
    \BaksDev\YandexMarket\Events\OrderStatusUpdated::class => [
        \App\Listeners\UpdateInventory::class,
    ],
];

Workflows

Bulk Product Sync

  1. Prepare Data: Fetch products from your database.
  2. Dispatch Job:
    SyncProducts::dispatch([
        'token' => 'seller_1_uuid',
        'products' => $products,
        'batch_size' => 50, // Optional: Chunk products for rate limiting
    ]);
    
  3. Monitor Queue: Use Laravel Horizon or php artisan queue:work to process jobs.

Order Processing

  1. Webhook Integration: Set up Yandex Market’s webhooks to trigger Laravel events.
  2. Handle Events:
    // In a listener
    public function handle(OrderStatusUpdated $event) {
        $order = $event->order;
        // Update your system and notify the seller
    }
    

Token Rotation

  1. Refresh Tokens: Use Laravel’s scheduled tasks to refresh expiring tokens:
    // In app/Console/Kernel.php
    protected function schedule(Schedule $schedule) {
        $schedule->command('yandex-market:refresh-tokens')->daily();
    }
    

Integration Tips

  • Laravel Facades: Wrap the package’s client in a Laravel facade for cleaner usage:
    // app/Facades/YandexMarket.php
    public static function syncProducts(array $products, string $token) {
        return (new SyncProducts($products, $token))->dispatch();
    }
    
  • Testing: Run Yandex Market-specific tests:
    php artisan test --group=yandex-market
    
  • Error Handling: Extend the package’s exception handler to log Yandex Market errors to Sentry or Laravel’s logging:
    // app/Exceptions/Handler.php
    public function report(Throwable $exception) {
        if ($exception instanceof \BaksDev\YandexMarket\Exceptions\ApiException) {
            \Log::error('Yandex Market API Error', ['error' => $exception->getMessage()]);
        }
        parent::report($exception);
    }
    

Gotchas and Tips

Pitfalls

  1. Queue Transport Mismatch

    • The package expects Symfony Messenger transports, but Laravel uses its own queue system. Solution:
      • Use Laravel’s sync driver for testing, then migrate to redis/database.
      • Create a custom transport adapter to bridge Messenger and Laravel queues.
  2. Token Management

    • Tokens are not persisted by default. Solution:
      • Store tokens in the database (e.g., yandex_market_tokens table) with encrypted values.
      • Use Laravel’s HasApiTokens trait for OAuth2 tokens.
  3. Rate Limiting

    • Yandex Market enforces rate limits (e.g., 100 requests/minute). Solution:
      • Implement exponential backoff in your retry strategy:
        'retry_strategy' => [
            'delay' => 2000, // Start with 2s delay
            'multiplier' => 1.5, // Increase delay by 50% per retry
        ],
        
      • Use Laravel’s throttle middleware for synchronous calls.
  4. Webhook Delays

    • Yandex Market webhooks may have high latency (minutes). Solution:
      • Implement a reconciliation job to poll for missing updates:
        PollForUpdates::dispatch()->delay(now()->addMinutes(5));
        
  5. PHP 8.4+ Requirements

    • If using Laravel <10, upgrade or use Rector to polyfill PHP 8.4 features.

Debugging

  • Enable Messenger Debugging:
    // config/messenger.php
    'debug' => env('MESSENGER_DEBUG', false),
    
  • Log Failed Jobs:
    // In app/Console/Kernel.php
    $this->commands([
        \BaksDev\YandexMarket\Console\FailedJobs::class,
    ]);
    
  • Check Queue Metrics: Use Laravel Horizon to monitor job failures and retry counts.

Config Quirks

  • Queue Names Must Match Tokens: Ensure the queue name in MESSENGER_TRANSPORT_DSN matches the token’s configured queue (e.g., seller_1_orders).
  • Default Retry Strategy: The package uses a fixed retry delay by default. Override in config/yandex-market.php:
    'default_retry_strategy' => [
        'max_retries' => 5,
        'delay' => 5000, // 5s
        'multiplier' => 2,
    ],
    

Extension Points

  1. Custom Jobs Extend the package’s job classes to add pre/post-processing:

    // app/Jobs/CustomSyncProducts.php
    public function handle() {
        // Pre-process data
        $result = parent::handle();
        // Post-process result
        return $result;
    }
    
  2. API Client Extensions Override the client to add middleware or logging:

    // app/Providers/YandexMarketServiceProvider.php
    public function register() {
        $this->app->bind(Client::class, function ($app) {
            $client = new \BaksDev\YandexMarket\Client($app['config']['yandex-market']);
            $client->withMiddleware(new \App\Http\Middleware\LogApiCalls());
            return $client;
        });
    }
    
  3. Event Customization Publish and modify event classes:

    php artisan vendor:publish --tag=yandex-market-events
    

    Then extend app/Events/YandexMarketEvent.php.

  4. Testing Helpers Use Laravel’s testing helpers to mock Yandex Market responses:

    $response = new \Symfony\Component\HttpFoundation\Response
    
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.
symfony/ai-symfony-mate-extension
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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