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

Dhl Php Sdk Laravel Package

petschko/dhl-php-sdk

Unofficial DHL SOAP API PHP SDK for creating/deleting shipments and generating labels. Supports DHL SOAP API v2+ (v3 available via dev branch). Requires PHP 5.4+ and the PHP SOAP extension. Note: repository is inactive/out of support.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require petschko/dhl-php-sdk
    

    Verify the package loads in composer.json under require.

  2. First Use Case: Authentication Initialize the client with your DHL API credentials:

    use DHL\Api\Client;
    use DHL\Api\Authentication\BasicAuthentication;
    
    $client = new Client();
    $client->setAuthentication(new BasicAuthentication('your-username', 'your-password'));
    

    Locate credentials in .env or a secure config file (never hardcode).

  3. First API Call (Shipment Tracking)

    $trackingResponse = $client->getShipmentTracking()->getShipmentTracking('1234567890');
    dd($trackingResponse->getShipmentTrackingResponse());
    

    Check the DHL API docs for endpoint specifics.


Implementation Patterns

Workflows

  1. Common Operations

    • Shipment Tracking: Use getShipmentTracking() for real-time status.
    • Label Printing: Chain createShipment() with getLabel():
      $shipment = $client->getShipment()->createShipment($requestData);
      $label = $client->getLabel()->getLabel($shipment->getShipmentId());
      
    • Batch Processing: Loop through shipments with getShipmentTracking()->getShipmentTracking($trackingNumbers).
  2. Request/Response Handling

    • Request Building: Use DHL\Api\Request\ShipmentRequest for structured payloads.
    • Response Parsing: Access data via getter methods (e.g., getShipmentTrackingResponse()->getTrackingItems()).
  3. Error Handling

    • Wrap API calls in try-catch:
      try {
          $response = $client->getShipment()->createShipment($data);
      } catch (\DHL\Api\Exception\ApiException $e) {
          log::error('DHL API Error: ' . $e->getMessage());
          return response()->json(['error' => 'DHL Service Unavailable'], 500);
      }
      

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:
    $this->app->singleton(Client::class, function () {
        $client = new Client();
        $client->setAuthentication(new BasicAuthentication(config('dhl.username'), config('dhl.password')));
        return $client;
    });
    
  • Queue Jobs: Offload long-running operations (e.g., bulk tracking) to queues:
    Dispatch(new ProcessDhlShipments($trackingNumbers))->onQueue('dhl');
    
  • Caching: Cache frequent responses (e.g., tracking data) with Laravel’s cache:
    $trackingData = Cache::remember("dhl_tracking_{$trackingNumber}", now()->addHours(1), function () use ($client, $trackingNumber) {
        return $client->getShipmentTracking()->getShipmentTracking($trackingNumber);
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecated API Version

    • The package is archived (last updated 2019) and may not support DHL’s latest API (v3+).
    • Workaround: Fork the repo and update endpoints/authentication manually. Monitor DHL’s API changelog for breaking changes.
  2. Authentication Issues

    • Basic Auth Deprecation: DHL may phase out Basic Auth. Switch to OAuth2 if required:
      $client->setAuthentication(new OAuth2Authentication($token));
      
    • Rate Limiting: DHL throttles requests. Implement exponential backoff:
      use Symfony\Component\Cache\Adapter\AdapterInterface;
      
      $cache = app(AdapterInterface::class);
      if (!$cache->get("dhl_rate_limit_{$ip}", false)) {
          $cache->set("dhl_rate_limit_{$ip}", true, 60); // 1-minute cooldown
          $response = $client->getShipmentTracking()->getShipmentTracking($number);
      }
      
  3. Response Parsing Quirks

    • Nested Arrays: Some responses use non-standard structures. Flatten data with collect($response)->toArray().
    • Empty Responses: Validate responses before processing:
      if (empty($response->getShipmentTrackingResponse()->getTrackingItems())) {
          throw new \RuntimeException('No tracking data found');
      }
      

Debugging

  • Enable Verbose Logging Configure the client to log raw requests/responses:
    $client->setLogger(new \Monolog\Logger('dhl', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/dhl.log'))
    ]));
    
  • Mocking for Tests Use Laravel’s HTTP mocking to test without hitting DHL’s API:
    $this->mock(DHL\Api\Client::class, function ($mock) {
        $mock->shouldReceive('getShipmentTracking')
             ->andReturnSelf()
             ->shouldReceive('getShipmentTracking')
             ->andReturn(new \DHL\Api\Response\ShipmentTrackingResponse([...]));
    });
    

Extension Points

  1. Custom Request/Response Classes Extend DHL\Api\Request\AbstractRequest or DHL\Api\Response\AbstractResponse to add domain-specific logic.

  2. Middleware for Requests Add headers or modify payloads via a middleware:

    $client->addMiddleware(function ($request) {
        $request->setHeader('X-Custom-Header', 'value');
        return $request;
    });
    
  3. Webhook Integration Use DHL’s webhook API (if supported) to push updates to your app. Store callbacks in Laravel’s queue:work:

    Route::post('/dhl/webhook', function (Request $request) {
        dispatch(new HandleDhlWebhook($request->json()->all()));
    });
    
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