PHPackages                             m4dev/laravel-usps - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. m4dev/laravel-usps

ActiveLibrary[HTTP &amp; Networking](/categories/http)

m4dev/laravel-usps
==================

Laravel package for USPS shipping integration with rates, labels, and tracking

1.0.0(8mo ago)18MITPHPPHP ^8.2

Since Aug 30Pushed 8mo agoCompare

[ Source](https://github.com/M4Dev-code/laravel-usps)[ Packagist](https://packagist.org/packages/m4dev/laravel-usps)[ RSS](/packages/m4dev-laravel-usps/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

USPS Laravel Package
====================

[](#usps-laravel-package)

A comprehensive Laravel package for USPS shipping integration with support for address validation, rate calculation, label creation, and package tracking using the USPS API v3 with OAuth2 authentication.

Features
--------

[](#features)

- **OAuth2 Authentication**: Secure authentication using client credentials
- **Address Validation**: Validate and standardize addresses using USPS API v3
- **Rate Calculation**: Get shipping rates for different USPS services with caching support
- **Label Creation**: Generate shipping labels in PDF format with tracking numbers
- **Package Tracking**: Track packages and automatically update shipment status
- **Rate Caching**: Cache rates to reduce API calls and improve performance
- **Rate Shopping**: Compare rates across multiple USPS services
- **Database Integration**: Store shipments and tracking information
- **Artisan Commands**: Built-in commands for testing and maintenance

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or 11.0
- cURL extension
- JSON extension
- Valid USPS Developer Account

Installation
------------

[](#installation)

1. Install via Composer:

```
composer require m4dev/laravel-usps
```

2. Publish the configuration file:

```
php artisan vendor:publish --tag=usps-config
```

3. Run the migrations:

```
php artisan migrate
```

4. Configure your environment variables in `.env`:

```
# USPS API Credentials (from USPS Developer Portal)
USPS_CLIENT_ID=your_client_id_from_usps_developer_portal
USPS_CLIENT_SECRET=your_client_secret_from_usps_developer_portal
USPS_SANDBOX=true

# Optional configurations
USPS_DEFAULT_SERVICE=USPS_GROUND_ADVANTAGE
USPS_LABEL_FORMAT=PDF
USPS_CACHE_ENABLED=true
USPS_RATE_SHOPPING=false

# Default sender information
USPS_SENDER_NAME="Your Company"
USPS_SENDER_COMPANY="Your Company Inc"
USPS_SENDER_STREET="123 Main St"
USPS_SENDER_CITY="Anytown"
USPS_SENDER_STATE="CA"
USPS_SENDER_ZIP="12345"
USPS_SENDER_PHONE="555-123-4567"
USPS_SENDER_EMAIL="shipping@yourcompany.com"
```

Getting USPS API Credentials
----------------------------

[](#getting-usps-api-credentials)

1. Go to the [USPS Developer Portal](https://developer.usps.com)
2. Create an account or log in
3. Register your application
4. You'll receive a `client_id` and `client_secret`
5. Use these credentials in your `.env` file

**Note**: The modern USPS API v3 uses OAuth2 authentication with client credentials, not API keys.

Quick Start
-----------

[](#quick-start)

### Basic Usage Example

[](#basic-usage-example)

```
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' => 'john@example.com'
]);

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

Detailed Usage
--------------

[](#detailed-usage)

### Address Validation

[](#address-validation)

```
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";
    }
}
```

### Getting Shipping Rates

[](#getting-shipping-rates)

```
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";
}
```

### Creating Shipping Labels

[](#creating-shipping-labels)

```
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' => 'john@example.com',
    '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));
}
```

### Package Tracking

[](#package-tracking)

```
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";
}
```

### Using the Facade

[](#using-the-facade)

```
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');
```

Artisan Commands
----------------

[](#artisan-commands)

### Test USPS Connection

[](#test-usps-connection)

```
php artisan usps:test-connection
```

### Update Tracking Information

[](#update-tracking-information)

```
# Update all non-delivered shipments
php artisan usps:update-tracking --all

# Update specific tracking numbers
php artisan usps:update-tracking --tracking=9400111899562516386781 --tracking=9400111899562516386782

# Update shipments from last 7 days
php artisan usps:update-tracking --days=7
```

### Clean Up Expired Cache

[](#clean-up-expired-cache)

```
php artisan usps:cleanup-cache
```

Configuration Options
---------------------

[](#configuration-options)

### Service Types

[](#service-types)

Configure available USPS services in `config/usps.php`:

```
'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

[](#rate-shopping)

Enable automatic rate comparison:

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

### Caching

[](#caching)

Configure rate caching:

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

Working with Models
-------------------

[](#working-with-models)

### UspsShipment Model

[](#uspsshipment-model)

```
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;
```

Advanced Usage
--------------

[](#advanced-usage)

### Batch Operations

[](#batch-operations)

```
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";
    }
}
```

### Custom Exception Handling

[](#custom-exception-handling)

```
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());
}
```

### Controller Example

[](#controller-example)

```
