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

Nepalcan Laravel Laravel Package

pralhadstha/nepalcan-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require pralhadstha/nepalcan-laravel
    

    The package uses auto-discovery, so no manual service provider registration is needed.

  2. Publish Configuration

    php artisan vendor:publish --provider="OmniCargo\NepalCan\NepalCanServiceProvider" --tag="config"
    

    This generates .env keys:

    NEPALCAN_API_TOKEN=your_api_token_here
    NEPALCAN_API_BASE_URL=https://api.nepalcanmove.com
    
  3. First Use Case: Create a Shipment

    use OmniCargo\NepalCan\Facades\NepalCan;
    
    $shipment = NepalCan::shipments()->create([
        'pickup' => [
            'address' => 'Kathmandu, Nepal',
            'contact' => '012345678',
        ],
        'delivery' => [
            'address' => 'Pokhara, Nepal',
            'contact' => '987654321',
        ],
        'items' => [
            ['name' => 'Laptop', 'weight' => 1.5, 'value' => 10000],
        ],
        'service' => 'standard',
    ]);
    

Implementation Patterns

Core Workflows

1. Dependency Injection

Inject the Client directly into services for type safety:

use OmniCargo\NepalCan\Client;

class OrderShipperService {
    public function __construct(private Client $nepalCanClient) {}

    public function shipOrder(Order $order) {
        $this->nepalCanClient->shipments()->create($order->toShipmentArray());
    }
}

2. Facade vs. Dependency Injection

  • Facade for quick CLI/artisan commands or blade templates:
    $rate = NepalCan::rates()->calculate($from, $to, $weight);
    
  • DI for testability and complex logic.

3. Webhook Handling

Register a listener for shipment.created:

use OmniCargo\NepalCan\Events\WebhookReceived;

class HandleNepalCanWebhooks {
    public function handle(WebhookReceived $event) {
        if ($event->type === 'shipment.created') {
            // Process webhook data
        }
    }
}

The package auto-registers a webhook route at /nepalcan/webhook with middleware for user-agent validation.

4. Rate Calculation

$rates = NepalCan::rates()->calculate(
    from: 'Kathmandu',
    to: 'Dharan',
    weight: 2.3,
    service: 'express'
);

5. Tracking Shipments

$tracking = NepalCan::trackings()->get('NCM123456789');

Integration Tips

  • Environment-Specific Config: Use .env overrides for staging/production API tokens.
  • Error Handling: Wrap API calls in try-catch:
    try {
        $shipment = NepalCan::shipments()->create(...);
    } catch (\OmniCargo\NepalCan\Exceptions\ApiException $e) {
        Log::error('NCM API Error: ' . $e->getMessage());
        return response()->json(['error' => 'Shipping failed'], 500);
    }
    
  • Testing: Use the Client directly in tests to mock responses:
    $client = $this->app->make(Client::class);
    $client->shouldReceive('createShipment')->once()->andReturn($mockShipment);
    

Gotchas and Tips

Pitfalls

  1. Webhook Verification

    • The package validates the User-Agent header for webhooks. If testing locally, ensure your request includes:
      User-Agent: NepalCanWebhook/1.0
      
    • Debugging tip: Check Laravel logs for SIGNATURE_VERIFICATION_FAILED errors.
  2. Rate Limits

    • NCM’s API may throttle requests. Implement exponential backoff for rate-limited endpoints:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $client = new RetryableHttpClient(
          $baseClient,
          [
              'max_retries' => 3,
              'delay_factor' => 200,
          ]
      );
      
  3. COD (Cash on Delivery) Handling

    • COD shipments require additional fields (cod_amount, cod_currency). Validate these before submission:
      $data['cod'] = [
          'amount' => $order->amount,
          'currency' => 'NPR',
      ];
      
  4. Timezone Mismatches

    • NCM’s API uses UTC. Ensure your Laravel app’s config/app.php timezone matches expectations (e.g., Asia/Kathmandu).

Debugging

  • Enable API Debugging: Add to .env:

    NEPALCAN_DEBUG=true
    

    This logs raw API requests/responses to storage/logs/nepalcan.log.

  • Webhook Testing: Use Laravel’s artisan serve with --host=0.0.0.0 to test webhook callbacks locally. Forward the webhook URL via ngrok:

    ngrok http 8000
    

Extension Points

  1. Custom Webhook Routes Override the default webhook route by binding a custom controller:

    NepalCan::extend(function ($service) {
        $service->webhookRoute(function () {
            return Route::post('/custom-webhook', [CustomWebhookController::class, 'handle']);
        });
    });
    
  2. Add New Services Extend the Client to support additional NCM services (e.g., returns, labels):

    NepalCan::extend(function ($client) {
        $client->returns = new ReturnsService($client);
    });
    
  3. Mocking for Tests Use the MockClient for unit tests:

    $mockClient = new MockClient();
    $mockClient->shouldReceive('createShipment')->andReturn($mockResponse);
    $this->app->instance(Client::class, $mockClient);
    

Config Quirks

  • Base URL Override: Dynamically change the API base URL for multi-environment setups:
    NepalCan::setBaseUrl(config('services.nepalcan.staging_url'));
    
  • Token Rotation: Rotate API tokens without redeploying by updating .env and restarting the queue worker (if using delayed jobs).
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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