PHP code example of m4dev / laravel-usps

1. Go to this page and download the library: Download m4dev/laravel-usps library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

m4dev / laravel-usps example snippets


use UspsShipping\Laravel\Services\UspsShippingService;

$shippingService = app(UspsShippingService::class);

$shipment = $shippingService->createShipment([
    'from_address' => [
        'street' => '123 Sender St',
        'city' => 'Los Angeles',
        'state' => 'CA',
        'zip' => '90210'
    ],
    'to_address' => [
        'street' => '456 Recipient Ave',
        'city' => 'New York',
        'state' => 'NY',
        'zip' => '10001'
    ],
    'weight' => 2.5,
    'dimensions' => [
        'length' => 12,
        'width' => 9,
        'height' => 3
    ],
    'service_type' => 'PRIORITY_MAIL',
    'customer_name' => 'John Doe',
    'customer_email' => '[email protected]'
]);

echo "Tracking Number: " . $shipment->tracking_number;
echo "Label URL: " . $shipment->label_url;

use UspsShipping\Laravel\Services\AddressValidationService;

$addressService = app(AddressValidationService::class);

$result = $addressService->validate([
    'street' => '123 Main Street',
    'city' => 'Beverly Hills',
    'state' => 'CA',
    'zip' => '90210'
]);

if ($result['valid']) {
    $standardizedAddress = $result['standardized'];
    $corrections = $result['corrections'];

    foreach ($corrections as $field => $correction) {
        echo "Corrected {$field}: {$correction['original']} → {$correction['corrected']}\n";
    }
}

use UspsShipping\Laravel\Services\RateService;

$rateService = app(RateService::class);

// Get rates for a single service
$rates = $rateService->getRates([
    'origin_zip' => '90210',
    'destination_zip' => '10001',
    'weight' => 2.5,
    'length' => 12,
    'width' => 9,
    'height' => 3,
    'mail_class' => 'PRIORITY_MAIL'
]);

echo "Shipping cost: $" . $rates['totalBasePrice'];

// Enable rate shopping in config to compare multiple services
config(['usps.rate_shopping.enabled' => true]);
$allRates = $rateService->getRates([
    'origin_zip' => '90210',
    'destination_zip' => '10001',
    'weight' => 2.5
]);

foreach ($allRates['rates'] as $rate) {
    echo "{$rate['service_name']}: $" . $rate['totalBasePrice'] . "\n";
}

use UspsShipping\Laravel\Services\LabelService;

$labelService = app(LabelService::class);

$shipment = $labelService->createAndSaveLabel([
    'to_address' => [
        'street' => '123 Customer St',
        'city' => 'New York',
        'state' => 'NY',
        'zip' => '10001'
    ],
    'weight' => 2.5,
    'dimensions' => [
        'length' => 12,
        'width' => 9,
        'height' => 3
    ],
    'service_type' => 'PRIORITY_MAIL',
    'customer_name' => 'John Doe',
    'customer_email' => '[email protected]',
    'label_format' => 'PDF'
]);

// Access the label
echo "Tracking Number: " . $shipment->tracking_number;
echo "Label URL: " . $shipment->label_url;

// Download label as base64 for storage
if ($shipment->label_base64) {
    file_put_contents("label_{$shipment->tracking_number}.pdf",
        base64_decode($shipment->label_base64));
}

use UspsShipping\Laravel\Services\TrackingService;

$trackingService = app(TrackingService::class);

$trackingInfo = $trackingService->track('9400111899562516386781');

echo "Status: " . $trackingInfo['status'] . "\n";
echo "Current Location: " . ($trackingInfo['current_location']['city'] ?? 'Unknown') . "\n";

foreach ($trackingInfo['events'] as $event) {
    echo $event['datetime'] . ": " . $event['description'] . " - " .
         ($event['location']['city'] ?? 'Unknown location') . "\n";
}

// Update a specific shipment's tracking
$updated = $trackingService->updateShipmentTracking('9400111899562516386781');
if ($updated) {
    echo "Shipment tracking updated successfully";
}

use Usps;

// Validate address
$address = Usps::validateAddress([
    'street' => '123 Main St',
    'city' => 'Beverly Hills',
    'state' => 'CA',
    'zip' => '90210'
]);

// Get rates
$rates = Usps::getRates([
    'origin_zip' => '90210',
    'destination_zip' => '10001',
    'weight' => 2.5
]);

// Track package
$tracking = Usps::trackPackage('9400111899562516386781');

// Get ZIP code info
$zipInfo = Usps::getZipInfo('90210');

'services' => [
    'USPS_GROUND_ADVANTAGE' => [
        'name' => 'USPS Ground Advantage',
        'delivery_days' => '2-5',
        'max_weight' => 70,
    ],
    'PRIORITY_MAIL' => [
        'name' => 'Priority Mail',
        'delivery_days' => '1-3',
        'max_weight' => 70,
    ],
    // ... more services
],

'rate_shopping' => [
    'enabled' => true,
    'services' => ['USPS_GROUND_ADVANTAGE', 'PRIORITY_MAIL', 'PRIORITY_MAIL_EXPRESS'],
    'sort_by' => 'price', // 'price' or 'delivery_time'
],

'cache' => [
    'enabled' => true,
    'duration' => 3600, // 1 hour
    'prefix' => 'usps_',
],

use UspsShipping\Laravel\Models\UspsShipment;

// Get all shipments
$shipments = UspsShipment::all();

// Get shipments by status
$inTransit = UspsShipment::where('status', 'in_transit')->get();

// Get delivered shipments
$delivered = UspsShipment::where('status', 'delivered')->get();

// Check shipment status
$shipment = UspsShipment::where('tracking_number', '9400111899562516386781')->first();
if ($shipment->isDelivered()) {
    echo "Package delivered on: " . $shipment->delivered_at;
}

// Get formatted weight and service name
echo "Weight: " . $shipment->formatted_weight;
echo "Service: " . $shipment->service_name;

use UspsShipping\Laravel\Services\UspsShippingService;

$shippingService = app(UspsShippingService::class);

$shipments = [
    [
        'to_address' => ['street' => '123 First St', 'city' => 'New York', 'state' => 'NY', 'zip' => '10001'],
        'weight' => 1.5,
        'service_type' => 'PRIORITY_MAIL'
    ],
    [
        'to_address' => ['street' => '456 Second Ave', 'city' => 'Chicago', 'state' => 'IL', 'zip' => '60601'],
        'weight' => 2.0,
        'service_type' => 'USPS_GROUND_ADVANTAGE'
    ]
];

$results = $shippingService->createBatchShipments($shipments);

foreach ($results as $index => $result) {
    if ($result['success']) {
        echo "Shipment {$index}: " . $result['shipment']->tracking_number . "\n";
    } else {
        echo "Shipment {$index} failed: " . $result['error'] . "\n";
    }
}

use UspsShipping\Laravel\Exceptions\{
    UspsException,
    UspsApiException,
    UspsValidationException,
    UspsAuthenticationException,
    UspsRateLimitException
};

try {
    $rates = $rateService->getRates($params);
} catch (UspsAuthenticationException $e) {
    // Handle authentication errors (invalid client credentials)
    Log::error('USPS Authentication Error: ' . $e->getMessage());
} catch (UspsValidationException $e) {
    // Handle address validation errors
    return response()->json(['error' => 'Invalid address: ' . $e->getMessage()], 400);
} catch (UspsRateLimitException $e) {
    // Handle rate limiting
    return response()->json(['error' => 'Rate limit exceeded'], 429);
} catch (UspsApiException $e) {
    // Handle other API errors
    Log::error('USPS API Error: ' . $e->getMessage(), $e->getContext());
} catch (UspsException $e) {
    // Handle general USPS errors
    Log::error('USPS Error: ' . $e->getMessage());
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use UspsShipping\Laravel\Services\{RateService, LabelService, TrackingService, AddressValidationService};
use UspsShipping\Laravel\Models\UspsShipment;

class ShippingController extends Controller
{
    public function calculateRates(Request $request, RateService $rateService)
    {
        $request->validate([
            'origin_zip' => ',
                'rates' => $rates
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }

    public function createShipment(Request $request, LabelService $labelService)
    {
        $request->validate([
            'to_address.street' => '       }
    }

    public function trackShipment(string $trackingNumber, TrackingService $trackingService)
    {
        try {
            $trackingInfo = $trackingService->track($trackingNumber);

            return response()->json([
                'success' => true,
                'tracking' => $trackingInfo
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }

    public function validateAddress(Request $request, AddressValidationService $addressService)
    {
        $request->validate([
            'street' => '

protected function schedule(Schedule $schedule)
{
    // Update tracking for recent shipments every hour
    $schedule->command('usps:update-tracking --days=7')
             ->hourly()
             ->withoutOverlapping();

    // Clean up expired cache daily
    $schedule->command('usps:cleanup-cache')
             ->daily();
}
bash
php artisan vendor:publish --tag=usps-config
bash
php artisan migrate
bash
php artisan usps:test-connection
bash
php artisan usps:cleanup-cache