PHP code example of mmediasoftwarelab / usps-oauth-php
1. Go to this page and download the library: Download mmediasoftwarelab/usps-oauth-php 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/ */
mmediasoftwarelab / usps-oauth-php example snippets
MMedia\USPS\Client;
use MMedia\USPS\Rates\DomesticRates;
// Initialize client
$client = new Client(
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
sandbox: true // Use sandbox for testing
);
// Get domestic shipping rates
$domesticRates = new DomesticRates($client);
$rate = $domesticRates->getRate(
originZip: '90210',
destinationZip: '10001',
weightLbs: 2.5,
length: 12,
width: 8,
height: 6,
serviceType: 'USPS_GROUND_ADVANTAGE'
);
echo "Shipping cost: $" . $rate->getTotalPrice();
use MMedia\USPS\Rates\DomesticRates;
use MMedia\USPS\Enums\DomesticServiceType;
$rates = new DomesticRates($client);
// Get rate for specific service
$rate = $rates->getRate(
originZip: '90210',
destinationZip: '10001',
weightLbs: 2.5,
length: 12,
width: 8,
height: 6,
serviceType: DomesticServiceType::GROUND_ADVANTAGE
);
// Or get all available services
$allRates = $rates->getAllRates(
originZip: '90210',
destinationZip: '10001',
weightLbs: 2.5,
length: 12,
width: 8,
height: 6
);
foreach ($allRates as $service => $rate) {
echo "{$service}: $" . $rate->getTotalPrice() . "\n";
}
use MMedia\USPS\Rates\InternationalRates;
use MMedia\USPS\Enums\InternationalServiceType;
$rates = new InternationalRates($client);
$rate = $rates->getRate(
originZip: '90210',
destinationCountry: 'CA', // Canada
weightLbs: 2.5,
length: 12,
width: 8,
height: 6,
serviceType: InternationalServiceType::PRIORITY_MAIL_INTERNATIONAL
);
// Development/Testing
$client = new Client(
clientId: 'sandbox-client-id',
clientSecret: 'sandbox-secret',
sandbox: true
);
// Production
$client = new Client(
clientId: 'production-client-id',
clientSecret: 'production-secret',
sandbox: false
);
use MMedia\USPS\Http\CurlHttpClient;
$httpClient = new CurlHttpClient(
timeout: 30,
connectTimeout: 10
);
$client = new Client(
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
httpClient: $httpClient
);
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('usps');
$logger->pushHandler(new StreamHandler('usps.log', Logger::DEBUG));
$client = new Client(
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
logger: $logger
);
// In a service provider
use MMedia\USPS\Client;
$this->app->singleton(Client::class, function ($app) {
return new Client(
clientId: config('services.usps.client_id'),
clientSecret: config('services.usps.client_secret'),
sandbox: config('services.usps.sandbox', true),
logger: $app->make('log')
);
});