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

Mondial Relay Laravel Package

codingbyjerez/mondial-relay

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle via Composer:

    composer require codingbyjerez/mondial-relay
    

    Enable the bundle in config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel via Symfony bridge):

    CodingByJerez\MondialRelayBundle\MondialRelayBundle::class => ['all' => true],
    
  2. Configuration Publish the default config and update .env:

    php artisan vendor:publish --provider="CodingByJerez\MondialRelayBundle\MondialRelayBundle" --tag="config"
    

    Set your Mondial Relay credentials in .env:

    MONDIAL_RELAY_API_KEY=your_api_key
    MONDIAL_RELAY_API_SECRET=your_api_secret
    MONDIAL_RELAY_API_URL=https://api.mondialrelay.fr
    
  3. First Use Case: Searching a Relay Point Inject the MondialRelayService into a controller or service:

    use CodingByJerez\MondialRelayBundle\Service\MondialRelayService;
    
    public function searchRelay(MondialRelayService $mondialRelay)
    {
        $relayPoints = $mondialRelay->searchRelayPoint('75000', 5, 10); // ZIP, radius (km), limit
        return response()->json($relayPoints);
    }
    
  4. First Use Case: Creating a Label

    $label = $mondialRelay->createLabel([
        'relayCode' => 'FR12345',
        'weight' => 1.5,
        'height' => 0.02,
        'width' => 0.15,
        'length' => 0.2,
        'description' => 'Order #12345',
        'sender' => [
            'name' => 'John Doe',
            'address' => '123 Main St',
            'zipCode' => '75000',
            'city' => 'Paris',
            'country' => 'FR',
        ],
        'recipient' => [
            'name' => 'Jane Doe',
            'address' => '456 Oak Ave',
            'zipCode' => '33000',
            'city' => 'Bordeaux',
            'country' => 'FR',
        ],
    ]);
    

Implementation Patterns

Usage Patterns

  1. Service Integration Use dependency injection to integrate Mondial Relay into your workflows:

    public function __construct(
        private MondialRelayService $mondialRelay,
        private OrderRepository $orders
    ) {}
    
  2. Order Shipping Workflow

    • Step 1: Search relay points for the customer’s ZIP code.
    • Step 2: Let the user select a relay point (store relayCode in the order).
    • Step 3: Generate a label when the order is shipped:
      $order->shipWithMondialRelay($this->mondialRelay);
      
  3. Label Generation with Dynamic Data Fetch order data dynamically and pass it to the label creation:

    $labelData = $this->prepareLabelData($order);
    $label = $this->mondialRelay->createLabel($labelData);
    
  4. Error Handling Wrap API calls in try-catch blocks to handle Mondial Relay exceptions:

    try {
        $label = $mondialRelay->createLabel($data);
    } catch (\CodingByJerez\MondialRelayBundle\Exception\MondialRelayException $e) {
        \Log::error('Mondial Relay error: ' . $e->getMessage());
        return response()->json(['error' => 'Failed to create label'], 500);
    }
    

Integration Tips

  1. Queue Delayed Label Creation Use Laravel Queues to defer label creation until the order is ready for shipment:

    OrderShipped::dispatch($order)
        ->delay(now()->addMinutes(10))
        ->onQueue('mondial-relay');
    
  2. Webhook for Label Status Updates Implement a webhook endpoint to handle status updates from Mondial Relay:

    Route::post('/mondial-relay/webhook', [MondialRelayWebhookController::class, 'handle']);
    
  3. Caching Relay Points Cache relay point searches to reduce API calls:

    $relayPoints = Cache::remember("relay_points_{$zipCode}", now()->addHours(1), function () use ($mondialRelay, $zipCode) {
        return $mondialRelay->searchRelayPoint($zipCode, 5, 10);
    });
    
  4. Testing Use mocks for MondialRelayService in unit tests:

    $this->mock(MondialRelayService::class)->shouldReceive('createLabel')
        ->once()
        ->andReturn(['labelUrl' => 'https://example.com/label.pdf']);
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits Mondial Relay’s API has rate limits. Monitor your usage and implement retries with exponential backoff:

    use Symfony\Component\HttpClient\RetryableHttpClient;
    
    $client = new RetryableHttpClient(
        new HttpClient(),
        [
            'max_retries' => 3,
            'delay_ms' => 1000,
            'multiplier' => 2,
            'statuses' => [429],
        ]
    );
    
  2. Deprecated API Version The bundle may not support the latest Mondial Relay API version (v5.1 as of the README). Verify compatibility or extend the bundle:

    // Override the API endpoint in config/services.yaml
    parameters:
        mondial_relay.api_url: 'https://api.mondialrelay.fr/v5.1'
    
  3. Missing Documentation The bundle’s documentation is minimal. Refer to the official Mondial Relay API docs for undocumented endpoints or parameters.

  4. Archived Status The package is archived, so expect no updates. Fork and maintain it if critical features are missing.

Debugging

  1. Enable API Logging Enable debug mode in the config to log API requests/responses:

    # config/packages/mondial_relay.yaml
    parameters:
        mondial_relay.debug: true
    
  2. Validate Request Data Always validate input before passing it to createLabel:

    $validator = Validator::make($request->all(), [
        'relayCode' => 'required|string',
        'weight' => 'required|numeric|min:0.1',
        // ... other fields
    ]);
    
  3. Handle Timeouts Mondial Relay API calls may timeout. Increase the timeout in the HTTP client:

    $client = new HttpClient([
        'timeout' => 30, // seconds
    ]);
    

Tips

  1. Extend the Bundle Create a custom service to extend functionality:

    namespace App\Services;
    
    use CodingByJerez\MondialRelayBundle\Service\MondialRelayService;
    
    class ExtendedMondialRelayService
    {
        public function __construct(private MondialRelayService $mondialRelay) {}
    
        public function createTrackedLabel(array $data): array
        {
            $label = $this->mondialRelay->createLabel($data);
            return $this->addTrackingToOrder($label['labelId'], $data['orderId']);
        }
    }
    
  2. Use Events for Label Creation Dispatch an event when a label is created to notify other services:

    event(new LabelCreated($label, $order));
    
  3. Store Label URLs Securely Store generated label URLs in the database with proper access controls:

    $order->label_url = $label['labelUrl'];
    $order->label_expiry = now()->addHours(24); // Mondial Relay labels expire
    $order->save();
    
  4. Local Testing with Mock API Use tools like WireMock to mock Mondial Relay API responses during development:

    // Example WireMock stub for testing
    {
      "request": {
        "method": "POST",
        "url": "/api/v5.1/label"
      },
      "response": {
        "status": 200,
        "body": "{\"labelUrl\":\"https://example.com/label.pdf\"}",
        "headers": {"Content-Type": "application/json"}
      }
    }
    
  5. Handle Currency and Weight Units Ensure weights are in kilograms and amounts in euros (as per Mondial Relay’s requirements). Convert if needed:

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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle