0.7.10 2016-07-12 07:59 UTC


Build Status StyleCI Scrutinizer Code Quality Code Coverage Code Climate Latest Stable Version Total Downloads License SensioLabsInsight Join the chat at

This library is aimed at wrapping all the UPS API into a simple to use PHP Library. It currently covers the Quantum View®, Tracking API, Shipping API, Rating API and Time in Transit API. Feel free to contribute.

Table Of Content

  1. Requirements
  2. Installation
  3. Address Validation Class
  4. QuantumView Class
  5. Tracking Class
  6. Rate Class
  7. TimeInTransit Class
  8. Locator Class
  9. Tradeability Class
  10. Shipping Class
  11. Logging
  12. License


This library uses PHP 5.5+.

To use the UPS API, you have to request an access key from UPS. For every request, you will have to provide the Access Key, your UPS User ID and Password.


It is recommended that you install the PHP UPS API library through composer. To do so, run the Composer command to install the latest stable version of PHP UPS API:

composer require gabrielbull/ups-api

Address Validation Class (Street Level)

The Address Validation Class allow you to validate an address at street level. Suggestions are given when address is invalid.

Note: UPS has two Address Validations. This is Street Level option, which includes all option of the normal Address Validation class and adds street level validation.

Not all countries are supported, see UPS documentation. Currently US & Puerto Rico are supported.


$address = new \Ups\Entity\Address();
$address->setAttentionName('Test Test');
$address->setAddressLine1('Address Line 1');
$address->setAddressLine2('Address Line 2');
$address->setAddressLine3('Address Line 3');
$address->setCity('New York');

$xav = new \Ups\AddressValidation($accessKey, $userId, $password);
$xav->activateReturnObjectOnValidate(); //This is optional
try {
    $response = $xav->validate($address, $requestOption = \Ups\AddressValidation::REQUEST_OPTION_ADDRESS_VALIDATION, $maxSuggestion = 15);
} catch (Exception $e) {

In the code above $xav->activateReturnObjectOnValidate() is completely optional. Calling this method will cause AddressValidation::validate() to return an AddressValidationResponse object. If you do not call this method, validate continues to function as it has previously. If you do not call this method, a single object with either the matched validated address, or the first candidate address if the address is ambiguous, will be returned.

The AddressValidationResponse object provides a number of methods to allow you to more easily query the API response to determine the outcome. Continuing the example from above, returning an AddressValidationResponse object will allow you to be a bit more specific with how you handle the various outcomes:

if ($response->noCandidates()) {
    //Do something clever and helpful to let the use know the address is invalid
if ($response->isAmbiguous()) {
    $candidateAddresses = $response->getCandidateAddressList();
    foreach($candidateAddresses as $address) {
        //Present user with list of candidate addresses so they can pick the correct one        
if ($response->isValid()) {
    $validAddress = $response->getValidatedAddress();

    //Show user validated address or update their address with the 'official' address
    //Or do something else helpful...


Address Validation parameters are:

  • address Address object as constructed in example
  • requestOption One of the three request options. See documentation. Default = Address Validation.
  • maxSuggestion Maximum number of suggestions to be returned. Max = 50

QuantumView Class

The QuantumView Class allow you to request a Quantum View Data subscription.


$quantumView = new Ups\QuantumView($accessKey, $userId, $password);

try {
    // Get the subscription for all events for the last hour
    $events = $quantumView->getSubscription(null, (time() - 3600));

    foreach($events as $event) {
        // Your code here
        echo $event->Type;

} catch (Exception $e) {


QuantumView parameters are:

  • name Name of subscription requested by user. If null, all events will be returned.
  • beginDateTime Beginning date time for the retrieval criteria of the subscriptions. Format: Y-m-d H:i:s or Unix timestamp.
  • endDateTime Ending date time for the retrieval criteria of the subscriptions. Format: Y-m-d H:i:s or Unix timestamp.
  • fileName File name of specific subscription requested by user.
  • bookmark Bookmarks the file for next retrieval.

If you provide a beginDateTime, but no endDateTime, the endDateTime will default to the current date time.

To use the fileName parameter, do not provide a beginDateTime.

Tracking Class

The Tracking Class allow you to track a shipment using the UPS Tracking API.

Example using Tracking Number / Mail Innovations tracking number

$tracking = new Ups\Tracking($accessKey, $userId, $password);

try {
    $shipment = $tracking->track('TRACKING NUMBER');

    foreach($shipment->Package->Activity as $activity) {

} catch (Exception $e) {


Tracking parameters are:

  • trackingNumber The package’s tracking number.
  • requestOption Optional processing. For Mail Innovations the only valid options are Last Activity and All activity.

Example using Reference Number

$tracking = new Ups\Tracking($accessKey, $userId, $password);

try {
    $shipment = $tracking->trackByReference('REFERENCE NUMBER');

    foreach($shipment->Package->Activity as $activity) {

} catch (Exception $e) {


Tracking parameters are:

  • referenceNumber The ability to track any UPS package or shipment by reference number. Reference numbers can be a purchase order number, job number, etc. Reference Number is supplied when generating a shipment.
  • requestOption Optional processing. For Mail Innovations the only valid options are Last Activity and All activity.

Example using Reference Number with additional parameters

$tracking = new Ups\Tracking($accessKey, $userId, $password);

$tracking->setShipperNumber('SHIPPER NUMBER');

$beginDate = new \DateTime('2016-01-01');
$endDate = new \DateTime('2016-01-31');


try {
    $shipment = $tracking->trackByReference('REFERENCE NUMBER');

    foreach($shipment->Package->Activity as $activity) {

} catch (Exception $e) {

The parameters shipperNumber, beginDate and endDate are optional. Either of the parameters can be set individually. These parameters can help to narrow the search field when tracking by reference, since it might happen that the reference number used is not unique. When using tracking by tracking number these parameters are not needed since the tracking number is unique.

Rate Class

The Rate Class allow you to get shipment rates using the UPS Rate API.


$rate = new Ups\Rate(

try {
    $shipment = new \Ups\Entity\Shipment();

    $shipperAddress = $shipment->getShipper()->getAddress();

    $address = new \Ups\Entity\Address();
    $shipFrom = new \Ups\Entity\ShipFrom();


    $shipTo = $shipment->getShipTo();
    $shipTo->setCompanyName('Test Ship To');
    $shipToAddress = $shipTo->getAddress();

    $package = new \Ups\Entity\Package();

    $dimensions = new \Ups\Entity\Dimensions();

    $unit = new \Ups\Entity\UnitOfMeasurement;



} catch (Exception $e) {


  • rateRequest Mandatory. rateRequest Object with shipment details

This Rate class is not finished yet! Parameter should be added when it will be finished.

TimeInTransit Class

The TimeInTransit Class allow you to get all transit times using the UPS TimeInTransit API.


$timeInTransit = new Ups\TimeInTransit($access, $userid, $passwd);

try {
    $request = new \Ups\Entity\TimeInTransitRequest;

    // Addresses
    $from = new \Ups\Entity\AddressArtifactFormat;

    $to = new \Ups\Entity\AddressArtifactFormat;

    // Weight
    $shipmentWeight = new \Ups\Entity\ShipmentWeight;
    $unit = new \Ups\Entity\UnitOfMeasurement;

    // Packages

    // InvoiceLines
    $invoiceLineTotal = new \Ups\Entity\InvoiceLineTotal;

    // Pickup date
    $request->setPickupDate(new DateTime);

    // Get data
    $times = $timeInTransit->getTimeInTransit($request);

    foreach($times->ServiceSummary as $serviceSummary) {

} catch (Exception $e) {


  • timeInTransitRequest Mandatory. timeInTransitRequest Object with shipment details, see example above.

Locator Class

The Locator class allows you to search for UPS Access Point locations.


$locatorRequest = new \Ups\Entity\LocatorRequest;

$originAddress = new \Ups\Entity\OriginAddress;
$address = new \Ups\Entity\AddressKeyFormat;

$geocode = new \Ups\Entity\GeoCode;

$translate = new \Ups\Entity\Translate;

$acccessPointSearch = new \Ups\Entity\AccessPointSearch;

$locationSearch = new \Ups\Entity\LocationSearchCriteria;


$unitOfMeasurement = new \Ups\Entity\UnitOfMeasurement;

try {
    // Get the locations
    $locator = new Ups\Locator($accessKey, $userId, $password);
    $locations = $locator->getLocations($locatorRequest, \Ups\Locator::OPTION_UPS_ACCESS_POINT_LOCATIONS);

    foreach($locations->SearchResults->DropLocation as $location) {
        // Your code here

} catch (Exception $e) {


Locator class parameters are:

  • locatorRequest Mandatory. locatorRequest object with request details, see example
  • requestOption Optional. Type of locations you are searching for.

Tradeability Class

The Tradeability class allows you to get data for international shipments:

  • Landed Costs (e.g. duties)
  • Denied Party Screener
  • Import Compliance
  • Export License Detection

Note: only the Landed Costs API is currently implemented.

WARNING: Tradeability is only available through a SOAP API. Therefore you are required to have the SOAP extension installed on your system.


// Build request
$landedCostRequest = new \Ups\Entity\Tradeability\LandedCostRequest;

// Build shipment
$shipment = new \Ups\Entity\Tradeability\Shipment;

// Build product
$product = new \Ups\Entity\Tradeability\Product;
$tariffInfo = new \Ups\Entity\Tradeability\TariffInfo;
$unitPrice = new \Ups\Entity\Tradeability\UnitPrice;
$weight = new Ups\Entity\Tradeability\Weight;
$unitOfMeasurement = new \Ups\Entity\Tradeability\UnitOfMeasurement;
$quantity = new \Ups\Entity\Tradeability\Quantity;
$unitOfMeasurement = new \Ups\Entity\Tradeability\UnitOfMeasurement;

// Add product to shipment

// Query request
$queryRequest = new \Ups\Entity\Tradeability\QueryRequest;

// Build

try {
    // Get the data
    $api = new Ups\Tradeability($accessKey, $userId, $password);
    $result = $api->getLandedCosts($landedCostRequest);

} catch (Exception $e) {


For the Landed Cost call, parameters are:

  • landedCostRequest Mandatory. landedCostRequest object with request details, see example.

Shipping Class.

The Shipping class allows you to register shipments. This also includes return shipments.

The shipping flow consists of 2 steps:

  • Confirm: Send information to UPS to get it validated and get a digest you can use to accept the shipment.
  • Accept: Finalise the shipment, mark it as it will be shipped. Get label and additional information.

Please note this is just an example. Your use case might demand more or less information to be sent to UPS.

In the example $return is used to show how a return could be handled.


    // Start shipment
    $shipment = new Ups\Entity\Shipment;

    // Set shipper
    $shipper = $shipment->getShipper();
    $shipperAddress = $shipper->getAddress();

    // To address
    $address = new \Ups\Entity\Address();
    $shipTo = new \Ups\Entity\ShipTo();

    // From address
    $address = new \Ups\Entity\Address();
    $shipFrom = new \Ups\Entity\ShipFrom();

    // Sold to
    $address = new \Ups\Entity\Address();
    $soldTo = new \Ups\Entity\SoldTo;

    // Set service
    $service = new \Ups\Entity\Service;

    // Mark as a return (if return)
    if ($return) {
        $returnService = new \Ups\Entity\ReturnService;

    // Set description

    // Add Package
    $package = new \Ups\Entity\Package();
    $unit = new \Ups\Entity\UnitOfMeasurement;

    // Set dimensions
    $dimensions = new \Ups\Entity\Dimensions();
    $unit = new \Ups\Entity\UnitOfMeasurement;

    // Add descriptions because it is a package

    // Add this package

    // Set Reference Number
    $referenceNumber = new \Ups\Entity\ReferenceNumber;
    if ($return) {
    } else {

    // Set payment information
    $shipment->setPaymentInformation(new \Ups\Entity\PaymentInformation('prepaid', (object)array('AccountNumber' => 'XX')));

    // Ask for negotiated rates (optional)
    $rateInformation = new \Ups\Entity\RateInformation;

    // Get shipment info
    try {
        $api = new Ups\Shipping($accessKey, $userId, $password); 

        $confirm = $api->confirm(\Ups\Shipping::REQ_VALIDATE, $shipment);
        var_dump($confirm); // Confirm holds the digest you need to accept the result

        if ($confirm) {
            $accept = $api->accept($confirm->ShipmentDigest);
            var_dump($accept); // Accept holds the label and additional information
    } catch (\Exception $e) {


For the Shipping confirm call, the parameters are:

  • $validation A UPS_Shipping::REQ_* constant (or null). Required
  • $shipment Shipment data container. Required
  • $labelSpec LabelSpecification data. Optional
  • $receiptSpec ShipmentRequestReceiptSpecification data. Optional

For the Shipping accept call, the parameters are:

  • $shipmentDigest The UPS Shipment Digest received from a ShipConfirm request. Required


All constructors take a PSR-3 compatible logger.

Besides that, the main UPS class has a public method setLogger to set it after the constructor ran.

Requests & responses (including XML, no access keys) are logged at DEBUG level. At INFO level only the event is reported, not the XML content. More severe problems (e.g. no connection) are logged with higher severity.

Example using Monolog

// Create logger
$log = new \Monolog\Logger('ups');
$log->pushHandler(new \Monolog\Handler\StreamHandler('logs/ups.log', \Monolog\Logger::DEBUG));

// Create Rate object + insert logger
$rate = new Ups\Rate($key, $username, $password, $useIntegration, $log);


PHP UPS API is licensed under The MIT License (MIT).