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

Gls Uni Box Bundle Laravel Package

ekyna/gls-uni-box-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require ekyna/gls-uni-box-bundle
    

    Add to config/bundles.php:

    Ekyna\GlsUniBoxBundle\EkynaGlsUniBoxBundle::class => ['all' => true],
    
  2. First Use Case

    • Generate a UniBox Label: Inject the Ekyna\GlsUniBox\UniBox service into a controller or command.
      use Ekyna\GlsUniBox\UniBox;
      
      public function generateLabel(UniBox $uniBox)
      {
          $label = $uniBox->generateLabel(
              'your_gls_customer_id',
              'your_gls_password',
              [
                  'items' => [
                      ['weight' => 1.5, 'length' => 20, 'width' => 15, 'height' => 10],
                      ['weight' => 0.8, 'length' => 10, 'width' => 8, 'height' => 5],
                  ],
                  'recipient' => [
                      'name' => 'Recipient Name',
                      'address' => 'Recipient Address',
                      'postcode' => '1234AB',
                      'city' => 'Recipient City',
                      'country' => 'NL',
                  ],
              ]
          );
          return response()->streamDownload(
              fn () => fwrite(STDOUT, $label),
              'gls_label.pdf'
          );
      }
      
  3. Configuration

    • Publish the default config:
      php artisan vendor:publish --tag=gls-uni-box-config
      
    • Update config/gls_uni_box.php with your GLS credentials and API settings.

Implementation Patterns

Workflows

  1. Order Processing

    • Hook into Order Events: Use Laravel events (e.g., Ekyna\CommerceBundle\Event\OrderShippedEvent) to trigger label generation after an order is marked as shipped.
      public function handle(OrderShippedEvent $event)
      {
          $uniBox = app(UniBox::class);
          $label = $uniBox->generateLabel(
              config('gls_uni_box.customer_id'),
              config('gls_uni_box.password'),
              $this->mapOrderToUniBoxData($event->getOrder())
          );
          // Save label path to order or send via email
      }
      
  2. Batch Processing

    • Process multiple orders in bulk (e.g., nightly cron job):
      public function generateLabelsForPendingOrders()
      {
          $orders = Order::where('status', 'shipped')->get();
          foreach ($orders as $order) {
              $uniBox->generateLabel(/* ... */);
          }
      }
      
  3. Integration with EkynaCommerceBundle

    • Extend Ekyna\CommerceBundle\Model\OrderInterface to include UniBox-specific fields (e.g., getUniBoxItems()).
    • Use the bundle’s ShipmentProvider to register GLS as a shipping option:
      # config/ekyna_commerce/shipping_providers.yml
      gls_uni_box:
          class: Ekyna\GlsUniBoxBundle\Provider\GlsUniBoxProvider
          label: 'GLS Uni Box'
      

Tips for Integration

  • Dependency Injection: Prefer constructor injection for UniBox service to avoid tight coupling.
  • Error Handling: Wrap API calls in try-catch blocks to handle GLS API errors gracefully:
    try {
        $label = $uniBox->generateLabel(/* ... */);
    } catch (\Ekyna\GlsUniBox\Exception\ApiException $e) {
        Log::error('GLS API Error: ' . $e->getMessage());
        throw new \RuntimeException('Failed to generate GLS label.');
    }
    
  • Testing: Mock the UniBox service in unit tests:
    $this->mock(UniBox::class)->shouldReceive('generateLabel')->once()->andReturn('mocked_label');
    

Gotchas and Tips

Pitfalls

  1. API Credentials

    • Hardcoded Credentials: Avoid committing config/gls_uni_box.php to version control. Use environment variables:
      'customer_id' => env('GLS_CUSTOMER_ID'),
      'password'    => env('GLS_PASSWORD'),
      
    • Sandbox vs. Production: Ensure you’re not accidentally using sandbox credentials in production (or vice versa). Check the base_url in the config.
  2. Item Dimensions

    • Unit Consistency: GLS expects dimensions in centimeters and weight in kilograms. Validate input data:
      $items = array_map(function ($item) {
          return [
              'weight' => $item['weight_kg'], // Ensure this is in kg
              'length' => $item['length_cm'],  // Ensure this is in cm
              'width'  => $item['width_cm'],
              'height' => $item['height_cm'],
          ];
      }, $order->items);
      
  3. Rate Limits

    • GLS APIs may throttle requests. Implement exponential backoff for retries:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = \Symfony\Component\HttpClient\HttpClient::create([
          'timeout' => 30,
          'retry_on_status' => [429, 500, 502, 503, 504],
          'retry_delay' => RetryStrategy::DELAY_MILLISECONDS,
      ]);
      
  4. Label Formatting

    • PDF Output: The generated PDF may require specific DPI or margins for printer compatibility. Test with your label printer’s requirements.

Debugging

  • API Responses: Enable debug mode in the config to log raw API responses:

    'debug' => true, // In config/gls_uni_box.php
    

    Check logs in storage/logs/laravel.log for detailed API interactions.

  • Validation Errors: GLS may return validation errors in the response body. Parse them explicitly:

    $response = $uniBox->getClient()->post($url, [
        'json' => $data,
    ]);
    $content = $response->getContent();
    if ($response->getStatusCode() === 400) {
        $errors = json_decode($content, true);
        throw new \InvalidArgumentException($errors['message'] ?? 'Unknown error');
    }
    

Extension Points

  1. Custom Label Templates

    • Override the default PDF template by publishing and modifying the Twig template:
      php artisan vendor:publish --tag=gls-uni-box-templates
      
      Edit resources/views/gls_uni_box/label.html.twig.
  2. Additional API Features

    • Extend the UniBox class to support additional GLS API endpoints (e.g., tracking, returns):
      namespace App\Services;
      
      use Ekyna\GlsUniBox\UniBox as BaseUniBox;
      
      class ExtendedUniBox extends BaseUniBox
      {
          public function getTrackingInfo(string $trackingNumber)
          {
              return $this->getClient()->get("/tracking/{$trackingNumber}");
          }
      }
      
  3. Webhook Handling

    • Implement a webhook endpoint to handle GLS API callbacks (e.g., shipment status updates):
      Route::post('/gls/webhook', [GlsWebhookController::class, 'handle']);
      
      Use the Ekyna\GlsUniBox\Webhook\Handler trait for validation:
      use Ekyna\GlsUniBox\Webhook\Handler;
      
      class GlsWebhookController extends Controller
      {
          use Handler;
      
          public function handle(Request $request)
          {
              return $this->processWebhook($request);
          }
      }
      
  4. Multi-Carrier Support

    • Create a wrapper service to abstract GLS logic and support other carriers (e.g., DHL, PostNL):
      interface ShipperInterface
      {
          public function generateLabel(array $data);
      }
      
      class GlsShipper implements ShipperInterface
      {
          public function __construct(private UniBox $uniBox) {}
      
          public function generateLabel(array $data)
          {
              return $this->uniBox->generateLabel(
                  config('gls_uni_box.customer_id'),
                  config('gls_uni_box.password'),
                  $data
              );
          }
      }
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware