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

Megamarket Orders Laravel Package

baks-dev/megamarket-orders

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install Dependencies:
    composer require baks-dev/megamarket baks-dev/megamarket-orders
    
  2. Run Initial Setup Commands:
    php artisan baks:users-profile-type:megamarket
    php artisan baks:payment:megamarket
    php artisan baks:delivery:megamarket
    
  3. Configure Megamarket API:
    • Add Megamarket API credentials to .env (check config/megamarket.php if it exists).
    • Ensure MEGAMARKET_API_KEY and MEGAMARKET_API_SECRET are set.
  4. Set Up Database:
    php artisan migrate
    
  5. Install Assets (if needed):
    php artisan baks:assets:install
    
  6. Test Webhook Endpoints:
    • Use Megamarket’s sandbox to send test payloads to:
      https://yourdomain.com/megamarket/order/new
      https://yourdomain.com/megamarket/order/cancel
      

First Use Case: Processing an Order

  1. Trigger an Order Creation:
    • Send a POST request to /megamarket/order/new with a Megamarket-compatible payload.
    • Example payload structure (undocumented; infer from Megamarket API):
      {
        "lot_id": "12345",
        "buyer_id": "67890",
        "items": [...],
        "delivery_method": "megamarket",
        "payment_method": "megamarket"
      }
      
  2. Verify Order in Database:
    • Check the orders table for the new Megamarket order with associated profile_type, payment, and delivery records.
  3. Cancel an Order:
    • Send a POST request to /megamarket/order/cancel with the lot_id:
      { "lot_id": "12345" }
      
    • Confirm the order status updates in your system and Megamarket’s dashboard.

Implementation Patterns

Core Workflows

1. Order Creation Workflow

  • Trigger: Megamarket sends a webhook to /megamarket/order/new.

  • Steps:

    1. Validate Payload: Ensure required fields (lot_id, buyer_id, items) are present.
    2. Create Order: Use the package’s OrderService (assumed) to generate a Laravel order with Megamarket-specific metadata.
    3. Link Profile/Payment/Delivery:
      $order->profile_type()->attach(MegamarketProfileType::whereName('megamarket')->first());
      $order->payment()->attach(MegamarketPayment::whereName('megamarket')->first());
      $order->delivery()->attach(MegamarketDelivery::whereName('megamarket')->first());
      
    4. Sync with Megamarket: Send confirmation back to Megamarket (if required by their API).
    5. Queue Notifications: Trigger email/SMS to seller/buyer (custom logic).
  • Example Controller:

    public function handleOrderNew(Request $request)
    {
        $validated = $request->validate([
            'lot_id' => 'required|string',
            'buyer_id' => 'required|string',
            'items' => 'required|array',
        ]);
    
        $order = app(\Baks\MegamarketOrders\Services\OrderService::class)
            ->createFromMegamarket($validated);
    
        return response()->json(['status' => 'order_created', 'order_id' => $order->id]);
    }
    

2. Order Cancellation Workflow

  • Trigger: Megamarket sends a webhook to /megamarket/order/cancel.

  • Steps:

    1. Validate lot_id: Ensure the order exists in your system.
    2. Cancel Order:
      $order = Order::where('megamarket_lot_id', $request->lot_id)->firstOrFail();
      $order->update(['status' => 'canceled']);
      
    3. Notify Megamarket: Send a confirmation (if required).
    4. Refund Processing: Trigger refund logic (if payment was processed).
  • Example Controller:

    public function handleOrderCancel(Request $request)
    {
        $request->validate(['lot_id' => 'required|string']);
    
        $order = Order::where('megamarket_lot_id', $request->lot_id)->firstOrFail();
        $order->cancel();
    
        return response()->json(['status' => 'canceled']);
    }
    

3. Seller Profile Management

  • Pattern: Use console commands to pre-configure Megamarket-specific options.
  • Extending Profiles:
    // Customize Megamarket profile type (e.g., add fields)
    $profileType = \Baks\Megamarket\Entities\UserProfileType::create([
        'name' => 'megamarket_custom',
        'config' => ['api_key' => 'your_key'],
    ]);
    

4. Payment/Delivery Integration

  • Pattern: Attach Megamarket methods to orders via relationships.
  • Custom Logic:
    // Override default payment processing
    event(OrderPaid::class, function ($event) {
        if ($event->order->payment->name === 'megamarket') {
            // Call Megamarket API to confirm payment
            \Baks\Megamarket\Services\PaymentService::confirm($event->order->id);
        }
    });
    

Integration Tips

  1. Webhook Security:

    • Validate Megamarket’s IP addresses or use API signatures.
    • Example middleware:
      public function handle($request, Closure $next)
      {
          if (!$request->hasValidSignature()) {
              abort(403);
          }
          return $next($request);
      }
      
  2. Asynchronous Processing:

    • Use Laravel queues to handle webhooks:
      dispatch(new ProcessMegamarketOrder($payload))->onQueue('megamarket');
      
  3. Logging:

    • Log all Megamarket API interactions for debugging:
      \Log::channel('megamarket')->info('Order created', ['lot_id' => $lotId, 'data' => $payload]);
      
  4. Testing:

    • Use PHPUnit’s Megamarket group:
      phpunit --group=megamarket-orders
      
    • Mock Megamarket API responses in tests:
      $this->mock(MegamarketApi::class)->shouldReceive('createOrder')->andReturn($mockResponse);
      
  5. Configuration:

    • Override default settings in config/megamarket.php:
      'api' => [
          'base_url' => env('MEGAMARKET_API_URL', 'https://api.megamarket.ru'),
          'timeout' => 30,
      ],
      

Gotchas and Tips

Pitfalls

  1. Missing Documentation:

    • API Payloads: Megamarket’s expected request/response formats are undocumented. Reverse-engineer from their official API docs (if available).
    • Error Handling: No clear guidance on how to handle Megamarket API errors (e.g., rate limits, invalid responses).
  2. Database Conflicts:

    • Schema Migrations: The package’s migrations may conflict with existing orders, payments, or deliveries tables. Backup your database before running migrate.
    • Foreign Keys: Ensure profile_type_id, payment_id, and delivery_id columns exist in your orders table.
  3. Console Command Dependencies:

    • Commands like baks:users-profile-type:megamarket assume the baks-dev/megamarket package is installed. Install both packages simultaneously to avoid errors.
  4. Webhook Idempotency:

    • Megamarket may resend webhooks. Design your endpoints to be idempotent (e.g., check lot_id existence before processing).
  5. API Key Management:

    • The package does not document where to store Megamarket API keys. Avoid hardcoding in .env; use Laravel’s config/services.php or a secrets manager.
  6. Timeouts:

    • Megamarket’s API may have strict timeouts. Use queues for long-running operations (e.g., order creation).
  7. Localization:

    • Assumes Russian-specific data (e.g., addresses, currencies). Validate internationalization if targeting non-Russian markets.

Debugging Tips

  1. Enable Debug Logging:
    'logging' => [
        'enabled' => env('MEGAMARKET_DEBUG', false),
        'channel' => 'megamarket',
    ],
    
    View logs with:
    tail -f storage/logs/megamarket
    
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