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

Shipping Sdk Laravel Laravel Package

dinas/shipping-sdk-laravel

Laravel SDK for the Dinas Shipping API. Send requests to REST endpoints and receive/verify incoming webhooks. Webhook events are logged and dispatched as Laravel jobs for async updates like shipment status changes and document availability.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dinas/shipping-sdk-laravel
    

    Add to .env:

    DINAS_SHIPPING_TOKEN=your_api_token
    DINAS_SHIPPING_SECRET=your_webhook_secret
    
  2. Webhook Route: Add to routes/api.php:

    Route::dinasShippingWebhooks('dinas-shipping/webhook');
    
  3. CSRF Exclusion: Update app/Providers/AppServiceProvider.php:

    protected $except = ['dinas-shipping/webhook'];
    
  4. Publish Config/Migrations:

    php artisan vendor:publish --provider="Dinas\Shipping\ShippingServiceProvider" --tag="shipping-sdk-laravel-config"
    php artisan vendor:publish --tag="shipping-sdk-laravel-migrations"
    php artisan migrate
    
  5. Register Webhook:

    php artisan webhook:dinas-shipping -i
    

First Use Case

Fetch pending cars with photos:

use Dinas\Shipping\Facades\Shipping;

$cars = Shipping::getCars([
    'status' => \Dinas\ShippingSdk\Model\StockStatus::PENDING,
    'photos' => true
]);

foreach ($cars->getData() as $car) {
    echo $car->getChassis() . ': ' . $car->getMake();
}

Implementation Patterns

Core Workflow: CRUD with Async Callbacks

  1. Fetch Data:

    $cars = Shipping::getCars(['status' => 'pending']);
    $voyage = Shipping::getVoyage(123);
    
  2. Create/Update:

    // Sync cars (upsert)
    Shipping::syncCars([['chassis' => 'ABC123', 'make' => 'Toyota']]);
    
    // Async operations with callbacks
    $result = Shipping::storeCarPhotos([...], onResolve: fn($ctx) => {
        if ($ctx->isFailed()) Log::error($ctx->message);
    });
    
  3. Status Management:

    // Hold/release cars
    Shipping::holdCars(['ABC123'], ['date' => '2026-03-15']);
    Shipping::releaseCars(['ABC123']);
    
    // Withhold/grant
    Shipping::withholdCars(['ABC123'], 'Payment pending');
    Shipping::grantCars(['ABC123']);
    

Integration with Laravel Ecosystem

  1. Jobs Queue: Async operations (e.g., storeCarPhotos) dispatch Laravel jobs. Handle failures in FailedJob handler:

    public function handle(ShouldQueue $job, array $data)
    {
        if ($job instanceof \Dinas\Shipping\Jobs\StoreCarPhotosJob) {
            Log::error('Photo upload failed', $data);
        }
    }
    
  2. Events: Listen to ShippingJobResolved for real-time updates:

    event(new ShippingJobResolved($jobId, 'storeCarPhotos', 'finished'));
    
  3. Broadcasting: Enable Pusher for frontend notifications:

    // config/dinas-shipping-sdk.php
    'broadcasting' => ['enabled' => true],
    

    Frontend (Laravel Echo):

    Echo.private(`user.${userId}`)
         .listen('.shipping.job.resolved', (e) => {
             console.log('Job resolved:', e);
         });
    

Batch Processing

  1. Chunked Uploads: Photos/documents are uploaded in chunks (default: 50 items). Customize in config:

    'chunk_size' => 25,
    
  2. Error Handling: Validate StoreResult objects:

    $result = Shipping::storeCarPhotos([...]);
    if (!$result->ok) {
        foreach ($result->validationErrors as $field => $messages) {
            // Handle per-field errors
        }
    }
    

Direct API Access

For advanced use cases, access underlying APIs:

$carsApi = Shipping::cars();
$photos = $carsApi->getCarPhotos(chassis: 'ABC123', photos: true);

Gotchas and Tips

Common Pitfalls

  1. Webhook Verification:

    • Ensure DINAS_SHIPPING_SECRET matches the API’s registered secret.
    • Test webhooks locally using php artisan webhook:dinas-shipping:test.
  2. Async Job Callbacks:

    • Callbacks are stored in the webhook_jobs table. Prune old entries to avoid bloat:
      php artisan model:prune --model="Dinas\Shipping\Models\WebhookJob"
      
    • Gotcha: Callbacks are executed once per webhook, even if the webhook is retried. Use WebhookJobContext::isFailed() to distinguish failures.
  3. Rate Limiting:

    • The API enforces rate limits (e.g., 100 requests/minute). Implement exponential backoff:
      use Dinas\Shipping\Exceptions\RateLimitExceeded;
      
      try {
          $result = Shipping::getCars([...]);
      } catch (RateLimitExceeded $e) {
          sleep($e->retryAfter);
          retry();
      }
      
  4. File Uploads:

    • Max File Size: Configure upload_max_filesize in php.ini (e.g., 20M for large documents).
    • Storage: Files are streamed directly to the API. Ensure your storage adapter (e.g., S3) supports streaming.
  5. Time Zones:

    • API dates (e.g., valid_until) are in UTC. Convert local dates explicitly:
      use Carbon\Carbon;
      $validUntil = Carbon::now()->addDays(30)->toDateTimeString();
      

Debugging Tips

  1. Log Webhook Payloads: Enable debug logging in config/dinas-shipping-sdk.php:

    'debug' => [
        'log_webhooks' => true,
    ],
    

    Logs appear in storage/logs/laravel.log.

  2. Test Webhooks Locally: Use the webhook:dinas-shipping:test command to simulate webhooks:

    php artisan webhook:dinas-shipping:test --event="api.job" --payload='{"job_id": "123"}'
    
  3. Inspect API Responses: Enable HTTP logging in config/dinas-shipping-sdk.php:

    'http' => [
        'debug' => true,
    ],
    

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client:

    Shipping::setHttpClient(app(\Illuminate\Http\Client\PendingRequest::class));
    
  2. Webhook Middleware: Add middleware to app/Providers/WebhookServiceProvider.php:

    public function boot()
    {
        \Spatie\WebhookClient\WebhookClient::useMiddleware(\App\Middleware\ValidateSignature::class);
    }
    
  3. Event Listeners: Extend webhook handling by listening to WebhookReceived:

    public function handle(WebhookReceived $event)
    {
        if ($event->payload['event'] === 'api.job') {
            // Custom logic for job events
        }
    }
    
  4. API Response Transformers: Modify responses globally by binding a transformer:

    Shipping::bindTransformer(\Dinas\ShippingSdk\Model\Car::class, \App\Transformers\CarTransformer::class);
    

Configuration Quirks

  1. Chunk Size: Adjust config/dinas-shipping-sdk.php for large batches:

    'chunk_size' => 50, // Default
    
  2. Broadcasting: Disable if not using Pusher:

    'broadcasting' => ['enabled' => false],
    
  3. Webhook Retries: Configure retry logic in config/webhook-client.php:

    'retries' => 3,
    'delay' => 60, // seconds
    

Performance Optimizations

  1. Caching: Cache frequent API calls (e.g., voyages) using Laravel’s cache:

    $voyages = Cache::remember('voyages', now()->addHours(1), function () {
        return Shipping::getVoyages();
    });
    
  2. Batch Processing: Use Laravel’s chunk() for large datasets:

    Shipping::getCars(['per_page' => 1000])->chunk(100, function ($cars) {
        foreach ($cars as $car) {
            // Process in batches
        }
    });
    
  3. Queue Workers: Scale async jobs with multiple queue workers:

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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope