PHPackages                             gregpunla/ups-api - 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. [API Development](/categories/api)
4. /
5. gregpunla/ups-api

ActiveLibrary[API Development](/categories/api)

gregpunla/ups-api
=================

PHP UPS API

0.8.9(6y ago)11.5k1MITPHPPHP ^5.5 || ^7.0

Since Jan 23Pushed 6y agoCompare

[ Source](https://github.com/gregpunla/php-ups-api)[ Packagist](https://packagist.org/packages/gregpunla/ups-api)[ RSS](/packages/gregpunla-ups-api/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (9)Dependencies (3)Versions (64)Used By (0)

[![PHP UPS API](https://camo.githubusercontent.com/559891ecd77871dc17acf45d5fb7aa76d84023c8b1b66242649ec69839e3623d/68747470733a2f2f7261776769742e636f6d2f6761627269656c62756c6c2f7068702d7570732d6170692f646576656c6f702f7068702d7570732d6170692d6c6f676f2e737667 "PHP UPS API")](https://camo.githubusercontent.com/559891ecd77871dc17acf45d5fb7aa76d84023c8b1b66242649ec69839e3623d/68747470733a2f2f7261776769742e636f6d2f6761627269656c62756c6c2f7068702d7570732d6170692f646576656c6f702f7068702d7570732d6170692d6c6f676f2e737667)
======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#)

[![Build Status](https://camo.githubusercontent.com/b0bcf5405d99213a2f4f1049f49a0721ef66911c8a7590fa77b12e70d667ebb7/68747470733a2f2f6170692e7472617669732d63692e6f72672f6761627269656c62756c6c2f7068702d7570732d6170692e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/gabrielbull/php-ups-api)[![StyleCI](https://camo.githubusercontent.com/d26d58b5342e122f6e14fd51532d6265da4708ca07787327943be2885d7c9755/68747470733a2f2f7374796c6563692e696f2f7265706f732f373737343738382f736869656c64)](https://styleci.io/repos/7774788)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/350983135abf7c584a38e4fd56e1ab202b923829f7f49c4b588e1f932c04de7f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6761627269656c62756c6c2f7068702d7570732d6170692f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/gabrielbull/php-ups-api/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/e75f848c7edee87b848a3deddb3f79dca527b34c1e741c4aa3f637fceacf025a/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6761627269656c62756c6c2f7068702d7570732d6170692f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/gabrielbull/php-ups-api/?branch=master)[![Code Climate](https://camo.githubusercontent.com/7e350b6398ce99d4859c1b0cbf7d56ce64e8dfba2ed7e5775d2b61a3bd44f103/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6761627269656c62756c6c2f7068702d7570732d6170692f6261646765732f6770612e737667)](https://codeclimate.com/github/gabrielbull/php-ups-api)[![Latest Stable Version](https://camo.githubusercontent.com/fa81b3d6262990a763290fa24fcaca0abb0e8455b642bacd22cf911e338a58b4/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6761627269656c62756c6c2f7570732d6170692e7376673f7374796c653d666c6174)](https://packagist.org/packages/gabrielbull/ups-api)[![Total Downloads](https://camo.githubusercontent.com/013d805f0bcab850e2082d4534a893ed4ae1b99892feaa3f7a56b9e416bba4b8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6761627269656c62756c6c2f7570732d6170692e7376673f7374796c653d666c6174)](https://packagist.org/packages/gabrielbull/ups-api)[![License](https://camo.githubusercontent.com/1f1c7c6d97ee8391cf47647775adecc0d132f20989ea0eebeb6dffab9ae4d19f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6761627269656c62756c6c2f7570732d6170692e7376673f7374796c653d666c6174)](https://packagist.org/packages/gabrielbull/ups-api)[![SensioLabsInsight](https://camo.githubusercontent.com/0b2b29a7515f1daaf43ecb7315c6a5b63562ca57d665220ddfe915711c8f32ea/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f32326532393334332d656530312d346364312d383739362d6331393135326333633139352f6d696e692e706e67)](https://insight.sensiolabs.com/projects/22e29343-ee01-4cd1-8796-c19152c3c195)[![Join the chat at https://gitter.im/gabrielbull/php-ups-api](https://camo.githubusercontent.com/abe08b740a4156153736f791393ec4da6619c4be73212e75769f52edacc0e2b5/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667)](https://gitter.im/gabrielbull/php-ups-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

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

[](#table-of-content)

1. [Requirements](#requirements)
2. [Installation](#installation)
3. [Address Validation Class](#addressvalidation-class)
    - [Example](#addressvalidation-class-example)
    - [Parameters](#addressvalidation-class-parameters)
4. [Simple Address Validation Class](#simple-addressvalidation-class)
    - [Example](#simple-addressvalidation-class-example)
    - [Parameters](#simple-addressvalidation-class-parameters)
5. [QuantumView Class](#quantumview-class)
    - [Example](#quantumview-class-example)
    - [Parameters](#quantumview-class-parameters)
6. [Tracking Class](#tracking-class)
    - [Example](#tracking-class-example)
    - [Parameters](#tracking-class-parameters)
7. [Rate Class](#rate-class)
    - [Example](#rate-class-example)
    - [Parameters](#rate-class-parameters)
8. [RateTimeInTransit Class](#ratetimeintransit-class)
    - [Example](#ratetimeintransit-class-example)
    - [Parameters](#ratetimeintransit-class-parameters)
9. [TimeInTransit Class](#timeintransit-class)
    - [Example](#timeintransit-class-example)
    - [Parameters](#timeintransit-class-parameters)
10. [Locator Class](#locator-class)
    - [Example](#locator-class-example)
    - [Parameters](#locator-class-parameters)
11. [Tradeability Class](#tradeability-class)
    - [Example](#tradeability-class-example)
    - [Parameters](#tradeability-class-parameters)
12. [Shipping Class](#shipping-class)
    - [Example](#shipping-class-example)
    - [Parameters](#shipping-class-parameters)
13. [Logging](#logging)
14. [License](#license-section)

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

[](#requirements)

This library uses PHP 5.5+.

To use the UPS API, you have to [request an access key from UPS](https://www.ups.com/upsdeveloperkit). For every request, you will have to provide the Access Key, your UPS User ID and Password.

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

[](#installation)

It is recommended that you install the PHP UPS API library [through composer](http://getcomposer.org/). To do so, run the Composer command to install the latest stable version of PHP UPS API:

```
composer require gregpunla/ups-api
```

If not using composer, you must also include these libraries: [Guzzle](https://github.com/guzzle/guzzle), [Guzzle Promises](https://github.com/guzzle/promises), \[Guzzle PSR7\] (), [PHP-Fig PSR Log](https://github.com/php-fig/log), and [PHP-Fig HTTP Message](https://github.com/php-fig/http-message).

Address Validation Class (Street Level)
---------------------------------------

[](#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.

Currently only US &amp; Puerto Rico are supported.

### Example

[](#example)

```
$address = new \Ups\Entity\Address();
$address->setAttentionName('Test Test');
$address->setBuildingName('Test');
$address->setAddressLine1('Address Line 1');
$address->setAddressLine2('Address Line 2');
$address->setAddressLine3('Address Line 3');
$address->setStateProvinceCode('NY');
$address->setCity('New York');
$address->setCountryCode('US');
$address->setPostalCode('10000');

$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) {
    var_dump($e);
}
```

#### AddressValidation::validateReturnAVObject()

[](#addressvalidationvalidatereturnavobject)

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...
}
```

### Parameters

[](#parameters)

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

Simple Address Validation Class
-------------------------------

[](#simple-address-validation-class)

The Simple Address Validation Class allow you to validate less extensive as the previous class. It returns a quality score of the supplied address and provides alternatives.

Note: UPS has two Address Validations. This is the Simple option.

Currently only US &amp; Puerto Rico are supported.

### Example

[](#example-1)

```
$address = new \Ups\Entity\Address();
$address->setStateProvinceCode('NY');
$address->setCity('New York');
$address->setCountryCode('US');
$address->setPostalCode('10000');

$av = new \Ups\SimpleAddressValidation($accessKey, $userId, $password);
try {
 $response = $av->validate($address);
 var_dump($response);
} catch (Exception $e) {
 var_dump($e);
}
```

### Parameters

[](#parameters-1)

Simple Address Validation parameters are:

- `address` Address object as constructed in example

QuantumView Class
-----------------

[](#quantumview-class)

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

### Example

[](#example-2)

```
$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) {
	var_dump($e);
}
```

### Parameters

[](#parameters-2)

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

[](#tracking-class)

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

### Example using Tracking Number / Mail Innovations tracking number

[](#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) {
		var_dump($activity);
	}

} catch (Exception $e) {
	var_dump($e);
}
```

### Parameters

[](#parameters-3)

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

[](#example-using-reference-number)

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

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

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

} catch (Exception $e) {
    var_dump($e);
}
```

### Parameters

[](#parameters-4)

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

[](#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');

$tracking->setBeginDate($beginDate);
$tracking->setEndDate($endDate);

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

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

} catch (Exception $e) {
    var_dump($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
----------

[](#rate-class)

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

### Example

[](#example-3)

```
$rate = new Ups\Rate(
	$accessKey,
	$userId,
	$password
);

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

    $shipperAddress = $shipment->getShipper()->getAddress();
    $shipperAddress->setPostalCode('99205');

    $address = new \Ups\Entity\Address();
    $address->setPostalCode('99205');
    $shipFrom = new \Ups\Entity\ShipFrom();
    $shipFrom->setAddress($address);

    $shipment->setShipFrom($shipFrom);

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

    $package = new \Ups\Entity\Package();
    $package->getPackagingType()->setCode(\Ups\Entity\PackagingType::PT_PACKAGE);
    $package->getPackageWeight()->setWeight(10);

    // if you need this (depends of the shipper country)
    $weightUnit = new \Ups\Entity\UnitOfMeasurement;
    $weightUnit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_KGS);
    $package->getPackageWeight()->setUnitOfMeasurement($weightUnit);

    $dimensions = new \Ups\Entity\Dimensions();
    $dimensions->setHeight(10);
    $dimensions->setWidth(10);
    $dimensions->setLength(10);

    $unit = new \Ups\Entity\UnitOfMeasurement;
    $unit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_IN);

    $dimensions->setUnitOfMeasurement($unit);
    $package->setDimensions($dimensions);

    $shipment->addPackage($package);

    var_dump($rate->getRate($shipment));
} catch (Exception $e) {
    var_dump($e);
}
```

### Parameters

[](#parameters-5)

- `rateRequest` Mandatory. rateRequest Object with shipment details

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

RateTimeInTransit Class
-----------------------

[](#ratetimeintransit-class)

The RateTimeInTransit Class allow you to get shipment rates like the Rate Class, but the response will also include TimeInTransit data.

### Example

[](#example-4)

```
$rate = new Ups\RateTimeInTransit(
	$accessKey,
	$userId,
	$password
);

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

    $shipperAddress = $shipment->getShipper()->getAddress();
    $shipperAddress->setPostalCode('99205');

    $address = new \Ups\Entity\Address();
    $address->setPostalCode('99205');
    $shipFrom = new \Ups\Entity\ShipFrom();
    $shipFrom->setAddress($address);

    $shipment->setShipFrom($shipFrom);

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

    $package = new \Ups\Entity\Package();
    $package->getPackagingType()->setCode(\Ups\Entity\PackagingType::PT_PACKAGE);
    $package->getPackageWeight()->setWeight(10);

    // if you need this (depends of the shipper country)
    $weightUnit = new \Ups\Entity\UnitOfMeasurement;
    $weightUnit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_KGS);
    $package->getPackageWeight()->setUnitOfMeasurement($weightUnit);

    $dimensions = new \Ups\Entity\Dimensions();
    $dimensions->setHeight(10);
    $dimensions->setWidth(10);
    $dimensions->setLength(10);

    $unit = new \Ups\Entity\UnitOfMeasurement;
    $unit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_IN);

    $dimensions->setUnitOfMeasurement($unit);
    $package->setDimensions($dimensions);

    $shipment->addPackage($package);

    $deliveryTimeInformation = new \Ups\Entity\DeliveryTimeInformation();
    $deliveryTimeInformation->setPackageBillType(\Ups\Entity\DeliveryTimeInformation::PBT_NON_DOCUMENT);

    $pickup = new \Ups\Entity\Pickup();
    $pickup->setDate("20170520");
    $pickup->setTime("160000");
    $shipment->setDeliveryTimeInformation($deliveryTimeInformation);

    var_dump($rate->shopRatesTimeInTransit($shipment));
} catch (Exception $e) {
    var_dump($e);
}
```

### Parameters

[](#parameters-6)

- `rateRequest` Mandatory. rateRequest Object with shipment details

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

TimeInTransit Class
-------------------

[](#timeintransit-class)

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

### Example

[](#example-5)

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

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

    // Addresses
    $from = new \Ups\Entity\AddressArtifactFormat;
    $from->setPoliticalDivision3('Amsterdam');
    $from->setPostcodePrimaryLow('1000AA');
    $from->setCountryCode('NL');
    $request->setTransitFrom($from);

    $to = new \Ups\Entity\AddressArtifactFormat;
    $to->setPoliticalDivision3('Amsterdam');
    $to->setPostcodePrimaryLow('1000AA');
    $to->setCountryCode('NL');
    $request->setTransitTo($to);

    // Weight
    $shipmentWeight = new \Ups\Entity\ShipmentWeight;
    $shipmentWeight->setWeight($totalWeight);
    $unit = new \Ups\Entity\UnitOfMeasurement;
    $unit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_KGS);
    $shipmentWeight->setUnitOfMeasurement($unit);
    $request->setShipmentWeight($shipmentWeight);

    // Packages
    $request->setTotalPackagesInShipment(2);

    // InvoiceLines
    $invoiceLineTotal = new \Ups\Entity\InvoiceLineTotal;
    $invoiceLineTotal->setMonetaryValue(100.00);
    $invoiceLineTotal->setCurrencyCode('EUR');
    $request->setInvoiceLineTotal($invoiceLineTotal);

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

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

	foreach($times->ServiceSummary as $serviceSummary) {
		var_dump($serviceSummary);
	}

} catch (Exception $e) {
    var_dump($e);
}
```

### Parameters

[](#parameters-7)

- `timeInTransitRequest` Mandatory. timeInTransitRequest Object with shipment details, see example above.

Locator Class
-------------

[](#locator-class)

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

### Example

[](#example-6)

```
$locatorRequest = new \Ups\Entity\LocatorRequest;

$originAddress = new \Ups\Entity\OriginAddress;
$address = new \Ups\Entity\AddressKeyFormat;
$address->setCountryCode('NL');
$originAddress->setAddressKeyFormat($address);

$geocode = new \Ups\Entity\GeoCode;
$geocode->setLatitude(52.0000);
$geocode->setLongitude(4.0000);
$originAddress->setGeoCode($geocode);
$locatorRequest->setOriginAddress($originAddress);

$translate = new \Ups\Entity\Translate;
$translate->setLanguageCode('ENG');
$locatorRequest->setTranslate($translate);

$acccessPointSearch = new \Ups\Entity\AccessPointSearch;
$acccessPointSearch->setAccessPointStatus(\Ups\Entity\AccessPointSearch::STATUS_ACTIVE_AVAILABLE);

$locationSearch = new \Ups\Entity\LocationSearchCriteria;
$locationSearch->setAccessPointSearch($acccessPointSearch);
$locationSearch->setMaximumListSize(25);

$locatorRequest->setLocationSearchCriteria($locationSearch);

$unitOfMeasurement = new \Ups\Entity\UnitOfMeasurement;
$unitOfMeasurement->setCode(\Ups\Entity\UnitOfMeasurement::UOM_KM);
$unitOfMeasurement->setDescription('Kilometers');
$locatorRequest->setUnitOfMeasurement($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
		var_dump($location);
	}

} catch (Exception $e) {
	var_dump($e);
}
```

### Parameters

[](#parameters-8)

Locator class parameters are:

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

Tradeability Class
------------------

[](#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](http://php.net/manual/en/book.soap.php) installed on your system.

### Example

[](#example-7)

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

// Build shipment
$shipment = new \Ups\Entity\Tradeability\Shipment;
$shipment->setOriginCountryCode('NL');
$shipment->setDestinationCountryCode('US');
$shipment->setDestinationStateProvinceCode('TX');
$shipment->setResultCurrencyCode('EUR');
$shipment->setTariffCodeAlert(1);
$shipment->setTransportationMode(\Ups\Entity\Tradeability\Shipment::TRANSPORT_MODE_AIR);
$shipment->setTransactionReferenceId('1');

// Build product
$product = new \Ups\Entity\Tradeability\Product;
$product->setProductName('Test');
$tariffInfo = new \Ups\Entity\Tradeability\TariffInfo;
$tariffInfo->setTariffCode('5109.90.80.00');
$product->setTariffInfo($tariffInfo);
$product->setProductCountryCodeOfOrigin('BD');
$unitPrice = new \Ups\Entity\Tradeability\UnitPrice;
$unitPrice->setMonetaryValue(250);
$unitPrice->setCurrencyCode('EUR');
$product->setUnitPrice($unitPrice);
$weight = new Ups\Entity\Tradeability\Weight;
$weight->setValue(0.83);
$unitOfMeasurement = new \Ups\Entity\Tradeability\UnitOfMeasurement;
$unitOfMeasurement->setCode('kg');
$weight->setUnitOfMeasurement($unitOfMeasurement);
$product->setWeight($weight);
$quantity = new \Ups\Entity\Tradeability\Quantity;
$quantity->setValue(5);
$unitOfMeasurement = new \Ups\Entity\Tradeability\UnitOfMeasurement;
$unitOfMeasurement->setCode(\Ups\Entity\Tradeability\UnitOfMeasurement::PROD_PIECES);
$quantity->setUnitOfMeasurement($unitOfMeasurement);
$product->setQuantity($quantity);
$product->setTariffCodeAlert(1);

// Add product to shipment
$shipment->addProduct($product);

// Query request
$queryRequest = new \Ups\Entity\Tradeability\QueryRequest;
$queryRequest->setShipment($shipment);
$queryRequest->setSuppressQuestionIndicator(true);

// Build
$landedCostRequest->setQueryRequest($queryRequest);

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

    var_dump($result);
} catch (Exception $e) {
    var_dump($e);
}
```

### Parameters

[](#parameters-9)

For the Landed Cost call, parameters are:

- `landedCostRequest` Mandatory. landedCostRequest object with request details, see example.

Shipping Class
--------------

[](#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.

### Example

[](#example-8)

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

    // Set shipper
    $shipper = $shipment->getShipper();
    $shipper->setShipperNumber('XX');
    $shipper->setName('XX');
    $shipper->setAttentionName('XX');
    $shipperAddress = $shipper->getAddress();
    $shipperAddress->setAddressLine1('XX');
    $shipperAddress->setPostalCode('XX');
    $shipperAddress->setCity('XX');
    $shipperAddress->setStateProvinceCode('XX'); // required in US
    $shipperAddress->setCountryCode('XX');
    $shipper->setAddress($shipperAddress);
    $shipper->setEmailAddress('XX');
    $shipper->setPhoneNumber('XX');
    $shipment->setShipper($shipper);

    // To address
    $address = new \Ups\Entity\Address();
    $address->setAddressLine1('XX');
    $address->setPostalCode('XX');
    $address->setCity('XX');
    $address->setStateProvinceCode('XX');  // Required in US
    $address->setCountryCode('XX');
    $shipTo = new \Ups\Entity\ShipTo();
    $shipTo->setAddress($address);
    $shipTo->setCompanyName('XX');
    $shipTo->setAttentionName('XX');
    $shipTo->setEmailAddress('XX');
    $shipTo->setPhoneNumber('XX');
    $shipment->setShipTo($shipTo);

    // From address
    $address = new \Ups\Entity\Address();
    $address->setAddressLine1('XX');
    $address->setPostalCode('XX');
    $address->setCity('XX');
    $address->setStateProvinceCode('XX');
    $address->setCountryCode('XX');
    $shipFrom = new \Ups\Entity\ShipFrom();
    $shipFrom->setAddress($address);
    $shipFrom->setName('XX');
    $shipFrom->setAttentionName($shipFrom->getName());
    $shipFrom->setCompanyName($shipFrom->getName());
    $shipFrom->setEmailAddress('XX');
    $shipFrom->setPhoneNumber('XX');
    $shipment->setShipFrom($shipFrom);

    // Sold to
    $address = new \Ups\Entity\Address();
    $address->setAddressLine1('XX');
    $address->setPostalCode('XX');
    $address->setCity('XX');
    $address->setCountryCode('XX');
    $address->setStateProvinceCode('XX');
    $soldTo = new \Ups\Entity\SoldTo;
    $soldTo->setAddress($address);
    $soldTo->setAttentionName('XX');
    $soldTo->setCompanyName($soldTo->getAttentionName());
    $soldTo->setEmailAddress('XX');
    $soldTo->setPhoneNumber('XX');
    $shipment->setSoldTo($soldTo);

    // Set service
    $service = new \Ups\Entity\Service;
    $service->setCode(\Ups\Entity\Service::S_STANDARD);
    $service->setDescription($service->getName());
    $shipment->setService($service);

    // Mark as a return (if return)
    if ($return) {
        $returnService = new \Ups\Entity\ReturnService;
        $returnService->setCode(\Ups\Entity\ReturnService::PRINT_RETURN_LABEL_PRL);
        $shipment->setReturnService($returnService);
    }

    // Set description
    $shipment->setDescription('XX');

    // Add Package
    $package = new \Ups\Entity\Package();
    $package->getPackagingType()->setCode(\Ups\Entity\PackagingType::PT_PACKAGE);
    $package->getPackageWeight()->setWeight(10);
    $unit = new \Ups\Entity\UnitOfMeasurement;
    $unit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_KGS);
    $package->getPackageWeight()->setUnitOfMeasurement($unit);

    // Set Package Service Options
    $packageServiceOptions = new \Ups\Entity\PackageServiceOptions();
    $packageServiceOptions->setShipperReleaseIndicator(true);
    $package->setPackageServiceOptions($packageServiceOptions);

    // Set dimensions
    $dimensions = new \Ups\Entity\Dimensions();
    $dimensions->setHeight(50);
    $dimensions->setWidth(50);
    $dimensions->setLength(50);
    $unit = new \Ups\Entity\UnitOfMeasurement;
    $unit->setCode(\Ups\Entity\UnitOfMeasurement::UOM_CM);
    $dimensions->setUnitOfMeasurement($unit);
    $package->setDimensions($dimensions);

    // Add descriptions because it is a package
    $package->setDescription('XX');

    // Add this package
    $shipment->addPackage($package);

    // Set Reference Number
    $referenceNumber = new \Ups\Entity\ReferenceNumber;
    if ($return) {
        $referenceNumber->setCode(\Ups\Entity\ReferenceNumber::CODE_RETURN_AUTHORIZATION_NUMBER);
        $referenceNumber->setValue($return_id);
    } else {
        $referenceNumber->setCode(\Ups\Entity\ReferenceNumber::CODE_INVOICE_NUMBER);
        $referenceNumber->setValue($order_id);
    }
    $shipment->setReferenceNumber($referenceNumber);

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

    // Ask for negotiated rates (optional)
    $rateInformation = new \Ups\Entity\RateInformation;
    $rateInformation->setNegotiatedRatesIndicator(1);
    $shipment->setRateInformation($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) {
        var_dump($e);
    }
```

If you wanted to create a printable file from the UPS Shipping label image data that came back with $accept, you would use something like the following:

```
    $label_file = $order_id . ".gif";
    $base64_string = $accept->PackageResults->LabelImage->GraphicImage;
    $ifp = fopen($label_file, 'wb');
    fwrite($ifp, base64_decode($base64_string));
    fclose($ifp);

```

### Parameters

[](#parameters-10)

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

Logging
-------

[](#logging)

All constructors take a [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) compatible logger.

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

Requests &amp; 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](https://github.com/Seldaek/monolog)

[](#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);

```

License
-------

[](#license)

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

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~52 days

Recently: every ~34 days

Total

51

Last Release

2229d ago

PHP version history (4 changes)0.1.0PHP &gt;=5.4.0

0.1.3PHP &gt;=5.3

0.5.0PHP &gt;=5.5

0.7.7PHP ^5.5 || ^7.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/34452261?v=4)[gregpunla](/maintainers/gregpunla)[@gregpunla](https://github.com/gregpunla)

---

Top Contributors

[![stefandoorn](https://avatars.githubusercontent.com/u/4903082?v=4)](https://github.com/stefandoorn "stefandoorn (190 commits)")[![gabrielbull](https://avatars.githubusercontent.com/u/671923?v=4)](https://github.com/gabrielbull "gabrielbull (80 commits)")[![scottcwilson](https://avatars.githubusercontent.com/u/4391638?v=4)](https://github.com/scottcwilson "scottcwilson (40 commits)")[![jasonbar](https://avatars.githubusercontent.com/u/1088631?v=4)](https://github.com/jasonbar "jasonbar (9 commits)")[![kraag22](https://avatars.githubusercontent.com/u/1721419?v=4)](https://github.com/kraag22 "kraag22 (9 commits)")[![stephenjwinn](https://avatars.githubusercontent.com/u/4694799?v=4)](https://github.com/stephenjwinn "stephenjwinn (8 commits)")[![gregpunla](https://avatars.githubusercontent.com/u/34452261?v=4)](https://github.com/gregpunla "gregpunla (8 commits)")[![sebvergnes](https://avatars.githubusercontent.com/u/7450520?v=4)](https://github.com/sebvergnes "sebvergnes (6 commits)")[![mtotheikle](https://avatars.githubusercontent.com/u/195964?v=4)](https://github.com/mtotheikle "mtotheikle (5 commits)")[![svergnes](https://avatars.githubusercontent.com/u/7011368?v=4)](https://github.com/svergnes "svergnes (4 commits)")[![leettastic](https://avatars.githubusercontent.com/u/3512843?v=4)](https://github.com/leettastic "leettastic (3 commits)")[![jaimz22](https://avatars.githubusercontent.com/u/5921193?v=4)](https://github.com/jaimz22 "jaimz22 (3 commits)")[![n8man](https://avatars.githubusercontent.com/u/551672?v=4)](https://github.com/n8man "n8man (3 commits)")[![sergey-nechaev](https://avatars.githubusercontent.com/u/3796512?v=4)](https://github.com/sergey-nechaev "sergey-nechaev (3 commits)")[![dyszczo](https://avatars.githubusercontent.com/u/1263190?v=4)](https://github.com/dyszczo "dyszczo (2 commits)")[![biwerr](https://avatars.githubusercontent.com/u/6122710?v=4)](https://github.com/biwerr "biwerr (2 commits)")[![thijsw](https://avatars.githubusercontent.com/u/28638?v=4)](https://github.com/thijsw "thijsw (2 commits)")[![gitter-badger](https://avatars.githubusercontent.com/u/8518239?v=4)](https://github.com/gitter-badger "gitter-badger (2 commits)")[![PepijnSenders](https://avatars.githubusercontent.com/u/2052659?v=4)](https://github.com/PepijnSenders "PepijnSenders (2 commits)")[![Radeq](https://avatars.githubusercontent.com/u/2742214?v=4)](https://github.com/Radeq "Radeq (1 commits)")

---

Tags

apitrackingwrapperRateshippingRatingupsquantum viewtime in transittradeability

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/gregpunla-ups-api/health.svg)

```
[![Health](https://phpackages.com/badges/gregpunla-ups-api/health.svg)](https://phpackages.com/packages/gregpunla-ups-api)
```

###  Alternatives

[gabrielbull/ups-api

PHP UPS API

4642.4M10](/packages/gabrielbull-ups-api)[gavroche/ups-api

PHP UPS API

45613.2k](/packages/gavroche-ups-api)[ivanmitrikeski/laravel-shipping

Shipping package for Laravel. Supported providers: CanadaPost, USPS, UPS, FedEx and Purolator.

206.8k2](/packages/ivanmitrikeski-laravel-shipping)[maxirus/fedex

FedEx API wrapper

176.6k](/packages/maxirus-fedex)[michaelb/ship-station

A php wrapper for ship station's api

101.9k](/packages/michaelb-ship-station)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
