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

baks-dev/yandex-market-orders

Symfony/PHP модуль для работы с заказами Яндекс.Маркета: поддержка схем FBS и DBS, установка профилей пользователя, способов оплаты и доставки через консольные команды, миграции БД и установка ассетов. Тесты PHPUnit.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/yandex-market baks-dev/yandex-market-orders
    

    Ensure PHP 8.4+ is used.

  2. Run Console Commands: Choose either FBS (Fast Business Service) or DBS (Delivery Business Service) and execute:

    php bin/console baks:users-profile-type:yandex-market-{fbs|dbs}
    php bin/console baks:payment:yandex-market-{fbs|dbs}
    php bin/console baks:delivery:yandex-market-{fbs|dbs}
    
  3. Configure Assets:

    php bin/console baks:assets:install
    
  4. Database Migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

First Use Case

  • Webhook Handling: Configure a route to handle Yandex Market webhook callbacks (e.g., order status updates).
    use BaksDev\YandexMarketOrders\Webhook\YandexMarketWebhookHandler;
    
    Route::post('/yandex-market/webhook', [YandexMarketWebhookHandler::class, 'handle']);
    
  • Order Creation: Use the service to create an order via Yandex Market API.
    use BaksDev\YandexMarketOrders\Service\OrderService;
    
    $orderService = app(OrderService::class);
    $order = $orderService->createOrder($yandexOrderData);
    

Implementation Patterns

Core Workflows

  1. Order Lifecycle Management:

    • Fetch Orders: Retrieve orders from Yandex Market via API.
      $orders = $orderService->fetchOrders($token, $sinceId);
      
    • Update Order Status: Sync order status between your system and Yandex Market.
      $orderService->updateOrderStatus($orderId, 'delivered');
      
    • Cancel Orders: Handle cancellations programmatically.
      $orderService->cancelOrder($orderId, 'Customer requested cancellation');
      
  2. Webhook Integration:

    • Extend the default webhook handler to process custom logic.
      class CustomWebhookHandler extends YandexMarketWebhookHandler
      {
          protected function handleOrderStatusUpdate(array $data): void
          {
              // Custom logic for order status updates
          }
      }
      
  3. Delivery and Payment Integration:

    • Use the configured delivery and payment services to process orders.
      $deliveryService = app(\BaksDev\YandexMarketDelivery\Service\DeliveryService::class);
      $deliveryService->createDelivery($orderId, $address);
      

Integration Tips

  • Event-Driven Architecture: Subscribe to Yandex Market events (e.g., OrderCreated, OrderStatusUpdated) using Laravel’s event system.
    Event::listen(OrderStatusUpdated::class, function ($event) {
        // Handle status update (e.g., send notification)
    });
    
  • Logging: Enable debug logging for API interactions.
    $this->logger->debug('Yandex Market API Response', ['response' => $response]);
    
  • Testing: Run the provided test group to validate core functionality.
    php bin/phpunit --group=yandex-market-orders
    

Gotchas and Tips

Pitfalls

  1. Token Management:

    • Ensure Yandex Market API tokens are securely stored (e.g., in .env or a secrets manager). Avoid hardcoding tokens in configuration files.
    • Rotate tokens periodically and update them in the package configuration.
  2. Webhook Verification:

    • Yandex Market sends webhook payloads with a signature. Always verify the signature to prevent spoofing:
      if (!$this->verifyWebhookSignature($data, $signature)) {
          abort(403, 'Invalid signature');
      }
      
  3. Rate Limiting:

    • Yandex Market APIs may throttle requests. Implement exponential backoff in your service layer:
      try {
          $response = $client->request('GET', '/orders');
      } catch (RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Database Schema Conflicts:

    • If you customize the Order or Delivery entities, ensure migrations are compatible with the package’s expectations. Run doctrine:migrations:diff after changes.

Debugging Tips

  • Enable API Debugging: Add this to your config/yandex-market.php to log API requests/responses:
    'debug' => env('YANDEX_MARKET_DEBUG', false),
    
  • Webhook Testing: Use Yandex Market’s sandbox environment for testing webhooks. Mock the payload in Laravel’s Testing facade:
    $this->post('/yandex-market/webhook', $mockPayload, [
        'headers' => ['X-Yandex-Signature' => $mockSignature],
    ]);
    
  • Common Errors:
    • 401 Unauthorized: Verify API tokens and scopes.
    • 404 Not Found: Check if the order ID or resource exists in Yandex Market.
    • Validation Errors: Ensure payloads match Yandex Market’s API schema (e.g., items array format in orders).

Extension Points

  1. Custom Order Fields: Override the Order entity to add custom fields:

    namespace App\Entity;
    
    use BaksDev\YandexMarketOrders\Entity\Order as BaseOrder;
    
    class Order extends BaseOrder
    {
        #[ORM\Column(nullable: true)]
        private ?string $customField = null;
    }
    
  2. API Client Extensions: Extend the HTTP client to add custom headers or middleware:

    $client = new YandexMarketClient($token, new CustomHttpClient());
    
  3. Event Subscribers: Create subscribers for Yandex Market events to trigger custom logic:

    class OrderStatusSubscriber implements SubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                OrderStatusUpdated::class => 'onOrderStatusUpdated',
            ];
        }
    
        public function onOrderStatusUpdated(OrderStatusUpdated $event): void
        {
            // Custom logic
        }
    }
    
  4. Delivery/Driver Integration: Hook into the delivery service to integrate with third-party logistics providers:

    $deliveryService->extend(function (Delivery $delivery) {
        $delivery->setExternalTrackingId($thirdPartyTrackingId);
    });
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager