Giter Site home page Giter Site logo

php-ups-api's Introduction

PHP UPS API

CI StyleCI Scrutinizer Code Quality Code Coverage Code Climate Latest Stable Version Total Downloads License Join the chat at https://gitter.im/gabrielbull/php-ups-api

This library wrap 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. Simple Address Validation Class
  5. QuantumView Class
  6. Tracking Class
  7. Rate Class
  8. RateTimeInTransit Class
  9. TimeInTransit Class
  10. Locator Class
  11. Tradeability Class
  12. Shipping Class
  13. Shipment Service Options
  14. Logging
  15. License

Requirements

This library uses PHP 7.1+.

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.

Installation

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

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

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 & Puerto Rico are supported.

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

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

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

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 & Puerto Rico are supported.

Example

$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

Simple Address Validation parameters are:

  • address Address object as constructed in example

QuantumView Class

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

Example

$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

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

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

Parameters

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

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

Parameters

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

$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

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

Example

$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

  • 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

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

Example

$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

  • 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

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

Example

$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

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

Locator Class

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

Example

$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

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.

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

Example

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

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.

Example

// 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) ['AccountNumber' => $shipper->getShipperNumber()]));

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

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

Shipment Service Options

The Shipment Service Options class allows you to register shipments additional options. This also includes.

  • Add or Modify email notifications: Manage updates for this shipment.
  • Saturday Commericial: Get weekend delivery of your shipment.
  • Deliver only to receiver's address: Do not reroute for customer pickup at a UPS location.
  • UPS Carbon Neutral Shipments Thanks for offsetting the environmental impact of your shipment! : at a nominal fee for domestic and international shipments.

In the example ShipmentServiceOptions class is used to show how a Shipment Additional Option can be added to Shipment.

Shipment Service Options Example

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

// Create Shipment Service Options Class
    $shipmentOptions = new Ups\Entity\ShipmentServiceOptions;
    // Setting the Carbon Neutral Additional Option, you can set your desired one.
    $shipmentOptions->setUPScarbonneutralIndicator();
// Set Shipment Service Options Class
    $shipment->setShipmentServiceOptions($shipmentOptions);

Logging

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

License

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

php-ups-api's People

Contributors

beaudierman avatar biwerr avatar deryabinsergey avatar dyszczo avatar gabrielbull avatar gitter-badger avatar jaimz22 avatar jasonbar avatar kraag22 avatar leettastic avatar mtotheikle avatar n8man avatar pepijnsenders avatar ptondereau avatar rud5g avatar ryross avatar scottcwilson avatar scottsb avatar sebvergnes avatar sergey-nechaev avatar shahariaazam avatar shehryar2 avatar stefandoorn avatar stephenjwinn avatar straversy avatar svergnes avatar tarcisioq avatar thijsw avatar vinkla avatar xerc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-ups-api's Issues

how do you set the service type?

I am trying to get a rate and would like to set different service type. I think the current service type is set to ground and I am not able to change it even though I tried doing the below
$obj-> \Ups\Entity\Service();
$obj->setCode(14);

I don't see any changes in the price.. any thoughts?

Also another issue...is there any way to get the overall summary of the package status while tracking? I mean like it gives you an array of every activity but there is no one object or class which shows the overall status of the package, I am using activity array[0] but not getting what I want.

Failure: Invalid Access License number (250003)

Hi! Thanks for this great lib! Unfortunately I am not able to get it running. I tried out the address validation example, but always getting:

Failure: Invalid Access License number (250003)

Do you have any idea what could be the issue?

Thanks!

How to manage InvalidResponseException

Hello,

We use the return service for UPS in different countries. Sometimes we have cases where the standard service can not be use from Origin to Destination. In this case an InvalidResponseException is returned.
But this can in most of the cases be solved by switching from

InvalidResponseException in Request.php line 131:
Failure: The selected service is not available from the origin to the destination. (121210)

How can I catch this error and return a page to the customer with the given error Message ?
Because this is not really an exception it's a standard UPS error that is returned.

Passwords contains ! occurs problems

I have got the following exception because my UPS account password contains '!'

ErrorException in Ups.php line 142:
DOMDocument::createElement(): unterminated entity reference

Multiple rates with 1 call to API

Hello,

I wanted to know if it were possible to fetch multiple rates for various services using your API but with only one call to UPS.

I found the method to change the selected shipping service, and the default is "Ground", but can't find the method for multiple services.

Maybe I am missing something big or simple, but any help or example would be greatly appreciated.

Thank You.

typo error in ShipTo.php

if (isset($attributesTaxIdentificationNumber)) on line 117 (ShipTo.php)
should be
if (isset($attributes->TaxIdentificationNumber))

Failure: Invalid tracking number (150022)

When I try to use your api I get this error with valid tracking numbers. From what I can tell, your api looks good. Have there been any changes to the UPS api service lately that could break your API?

<?php
date_default_timezone_set('America/Phoenix');
require_once('vendor/autoload.php');

$accessKey="secret";
$userId="secret";
$password="secret";

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

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

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

        var_dump($activity);
    }

} catch (Exception $e) {
    echo "exception thrown";
    var_dump($e);
}

How to add a second Reference to shippment?

Hi,
I use this code in my shippment to add a reference

$referencenumber=new ReferenceNumber;
$referencenumber->setValue($strPackageRef1);
$referencenumber->setBarCodeIndicator(true);
$shipment->setReferenceNumber($referencenumber);

This is shown as "Reference No.1:" on the label.

But how to add a second reference ? to have "Reference No.2:" on the label?

CU Online

Documentation for Shipping Method

Hello can you help with an exemple on using the Shipping method.
Tracking is working well, but i need to implement the Shipment now.

Thanks

'String could not be parsed as XML'

Today I came across an issue where the response of the TimeInTransit API was giving problems, mainly SimpleXMLElement throwing an error: String could not be parsed as XML. Example XML is below.

In //TransitResponse/TransitTo/AddressArtifactFormat/PoliticalDivision3 you will find that Amsterdam is written with a Ë. I did that on purpose for testing, as a client was using that letter. In building the request I used ë btw for both PoliticalDivision2 and PoliticalDivision3.

Using utf8_encode() on the string before creating the SimpleXMLElement object does solve the problem I'm facing, but I'm not sure whether that is a suitable solution for all responses.

@gabrielbull Do you have a suggestion?

<?xml version="1.0"?>
<TimeInTransitResponse>
   <Response>
      <TransactionReference />
      <ResponseStatusCode>1</ResponseStatusCode>
      <ResponseStatusDescription>Success</ResponseStatusDescription>
   </Response>
   <TransitResponse>
      <PickupDate>2015-08-26</PickupDate>
      <TransitFrom>
         <AddressArtifactFormat>
            <PoliticalDivision3>AMSTERDAM</PoliticalDivision3>
            <PoliticalDivision2>AMSTERDAM</PoliticalDivision2>
            <Country>NETHERLANDS</Country>
            <CountryCode>NL</CountryCode>
            <PostcodePrimaryLow>1000AA</PostcodePrimaryLow>
         </AddressArtifactFormat>
      </TransitFrom>
      <TransitTo>
         <AddressArtifactFormat>
            <PoliticalDivision3>AMSTËRDAM</PoliticalDivision3>
            <PoliticalDivision2>AMSTERDAM</PoliticalDivision2>
            <Country>NETHERLANDS</Country>
            <CountryCode>NL</CountryCode>
            <PostcodePrimaryLow>1000AA</PostcodePrimaryLow>
         </AddressArtifactFormat>
      </TransitTo>
      <AutoDutyCode>02</AutoDutyCode>
      <ShipmentWeight>
         <UnitOfMeasurement>
            <Code>KGS</Code>
         </UnitOfMeasurement>
         <Weight>1.8</Weight>
      </ShipmentWeight>
      <InvoiceLineTotal>
         <CurrencyCode>EUR</CurrencyCode>
         <MonetaryValue>250.00</MonetaryValue>
      </InvoiceLineTotal>
      <Disclaimer>Services listed as guaranteed are backed by a money-back guarantee for transportation charges only. See Terms and Conditions in the Service Guide for details. Certain commodities and high value shipments may require additional transit time for customs clearance.</Disclaimer>
      <Disclaimer>For packages shipped from and delivered to a UPS Access Point&amp;trade; location. Days in transit is based on a drop-off prior to a location's collection time.</Disclaimer>
      <ServiceSummary>
         <Service>
            <Code>23</Code>
            <Description>UPS Express Plus</Description>
         </Service>
         <Guaranteed>
            <Code>Y</Code>
         </Guaranteed>
         <EstimatedArrival>
            <BusinessTransitDays>1</BusinessTransitDays>
            <Time>09:00:00</Time>
            <PickupDate>2015-08-26</PickupDate>
            <PickupTime>17:30:00</PickupTime>
            <HolidayCount>0</HolidayCount>
            <DelayCount>0</DelayCount>
            <Date>2015-08-27</Date>
            <DayOfWeek>THU</DayOfWeek>
            <TotalTransitDays>1</TotalTransitDays>
            <CustomerCenterCutoff>16:30:00</CustomerCenterCutoff>
            <RestDays>0</RestDays>
         </EstimatedArrival>
      </ServiceSummary>
      <ServiceSummary>
         <Service>
            <Code>24</Code>
            <Description>UPS Express</Description>
         </Service>
         <Guaranteed>
            <Code>Y</Code>
         </Guaranteed>
         <EstimatedArrival>
            <BusinessTransitDays>1</BusinessTransitDays>
            <Time>10:30:00</Time>
            <PickupDate>2015-08-26</PickupDate>
            <PickupTime>17:30:00</PickupTime>
            <HolidayCount>0</HolidayCount>
            <DelayCount>0</DelayCount>
            <Date>2015-08-27</Date>
            <DayOfWeek>THU</DayOfWeek>
            <TotalTransitDays>1</TotalTransitDays>
            <CustomerCenterCutoff>16:30:00</CustomerCenterCutoff>
            <RestDays>0</RestDays>
         </EstimatedArrival>
      </ServiceSummary>
      <ServiceSummary>
         <Service>
            <Code>26</Code>
            <Description>UPS Express Saver</Description>
         </Service>
         <Guaranteed>
            <Code>Y</Code>
         </Guaranteed>
         <EstimatedArrival>
            <BusinessTransitDays>1</BusinessTransitDays>
            <Time>23:30:00</Time>
            <PickupDate>2015-08-26</PickupDate>
            <PickupTime>17:30:00</PickupTime>
            <HolidayCount>0</HolidayCount>
            <DelayCount>0</DelayCount>
            <Date>2015-08-27</Date>
            <DayOfWeek>THU</DayOfWeek>
            <TotalTransitDays>1</TotalTransitDays>
            <CustomerCenterCutoff>16:30:00</CustomerCenterCutoff>
            <RestDays>0</RestDays>
         </EstimatedArrival>
      </ServiceSummary>
      <ServiceSummary>
         <Service>
            <Code>25</Code>
            <Description>UPS Standard</Description>
         </Service>
         <Guaranteed>
            <Code>N</Code>
         </Guaranteed>
         <EstimatedArrival>
            <BusinessTransitDays>1</BusinessTransitDays>
            <Time>23:30:00</Time>
            <PickupDate>2015-08-26</PickupDate>
            <PickupTime>17:30:00</PickupTime>
            <HolidayCount>0</HolidayCount>
            <DelayCount>0</DelayCount>
            <Date>2015-08-27</Date>
            <DayOfWeek>THU</DayOfWeek>
            <TotalTransitDays>1</TotalTransitDays>
            <CustomerCenterCutoff>16:30:00</CustomerCenterCutoff>
            <RestDays>0</RestDays>
         </EstimatedArrival>
      </ServiceSummary>
      <ServiceSummary>
         <Service>
            <Code>39</Code>
            <Description>UPS Access Point&amp;trade; Economy</Description>
         </Service>
         <Guaranteed>
            <Code>N</Code>
         </Guaranteed>
         <EstimatedArrival>
            <BusinessTransitDays>3</BusinessTransitDays>
            <Time>23:30:00</Time>
            <PickupDate>2015-08-26</PickupDate>
            <PickupTime>18:00:00</PickupTime>
            <HolidayCount>0</HolidayCount>
            <DelayCount>0</DelayCount>
            <Date>2015-08-29</Date>
            <DayOfWeek>SAT</DayOfWeek>
            <TotalTransitDays>3</TotalTransitDays>
            <CustomerCenterCutoff>16:00:00</CustomerCenterCutoff>
            <RestDays>0</RestDays>
         </EstimatedArrival>
      </ServiceSummary>
      <MaximumListSize>35</MaximumListSize>
   </TransitResponse>
</TimeInTransitResponse>

Error License 250003

Hello

I try to validate address (with AddressValidation class) but I get error message :
Failure: Invalid Access License number (250003).

However, it works well with the Tracking class...
Furthermore, on UPS website, it seems that the API is valid for Adress validation.

Do you have any idea ?

Unterminated entity reference in DOMDocument::createElement().

Warning: DOMDocument::createElement(): unterminated entity reference B ENTERPRISES in Ups\Entity\Address->toNode() (line 270 of /path/to/gabrielbull/ups-api/src/Entity/Address.php).

The offending value was "A & B ENTERPRISES" in the customer's address.
#73 appears to be a similar issue, solved using createTextNode().

It seems a little weird to me that the user entered a business name in an address field (with street information in the second line), but it looks like the same issue would have occurred if they used that same name in the CompanyName element instead.

Address Validation Missing Data

Hi,

When I attempt to do address validation on an ambiguous address, the response is only being returned with one of the, what I know to be, three suggested addresses.

As an example:

$address = new Address();
$address->setAddressLine1("1902 stonebridge blvd");
$address->setCity("ALPHARETTA");
$address->setStateProvinceCode('GA');
$address->setCountryCode('US');
$address->setPostalCode('30005');

I expect to get back a response with 3 suggested addresses from the AddressKeyFormat property of the response. However, I'm only being returned the first element in the array.

When I dump the response prior to ->convertXmlObject on Line 186 I get this Object:

SimpleXMLElement {#797 ▼
  +"Response": SimpleXMLElement {#786 ▶}
  +"AmbiguousAddressIndicator": SimpleXMLElement {#785}
  +"AddressClassification": SimpleXMLElement {#776 ▼
    +"Code": "0"
    +"Description": "Unknown"
  }
  +"AddressKeyFormat": array:3 [▼
    0 => SimpleXMLElement {#775 ▼
      +"AddressClassification": SimpleXMLElement {#767 ▼
        +"Code": "0"
        +"Description": "Unknown"
      }
      +"AddressLine": "400-498 STAMBRIDGE CT"
      +"Region": "ALPHARETTA GA 30005-2567"
      +"PoliticalDivision2": "ALPHARETTA"
      +"PoliticalDivision1": "GA"
      +"PostcodePrimaryLow": "30005"
      +"PostcodeExtendedLow": "2567"
      +"CountryCode": "US"
    }
    1 => SimpleXMLElement {#774 ▼
      +"AddressClassification": SimpleXMLElement {#782 ▼
        +"Code": "0"
        +"Description": "Unknown"
      }
      +"AddressLine": "401-499 STAMBRIDGE CT"
      +"Region": "ALPHARETTA GA 30005-2565"
      +"PoliticalDivision2": "ALPHARETTA"
      +"PoliticalDivision1": "GA"
      +"PostcodePrimaryLow": "30005"
      +"PostcodeExtendedLow": "2565"
      +"CountryCode": "US"
    }
    2 => SimpleXMLElement {#772 ▼
      +"AddressClassification": SimpleXMLElement {#783 ▼
        +"Code": "0"
        +"Description": "Unknown"
      }
      +"AddressLine": "500-599 STAMBRIDGE CT"
      +"Region": "ALPHARETTA GA 30005-2568"
      +"PoliticalDivision2": "ALPHARETTA"
      +"PoliticalDivision1": "GA"
      +"PostcodePrimaryLow": "30005"
      +"PostcodeExtendedLow": "2568"
      +"CountryCode": "US"
    }
  ]
}

However, what is actually returned from the convertXmlObject() method is:

{#784 ▼
  +"AddressClassification": {#781 ▼
    +"Code": "0"
    +"Description": "Unknown"
  }
  +"AddressLine": "400-498 STAMBRIDGE CT"
  +"Region": "ALPHARETTA GA 30005-2567"
  +"PoliticalDivision2": "ALPHARETTA"
  +"PoliticalDivision1": "GA"
  +"PostcodePrimaryLow": "30005"
  +"PostcodeExtendedLow": "2567"
  +"CountryCode": "US"
}

So, all that said, is there a reason to know return the full response as an array? Instead of doing this return $this->convertXmlObject($response->AddressKeyFormat); can you not do this return $this->convertXmlObject($response);? This returns the full context of the response.

An additional problem this would solve is in the case of an address that is so badly formatted that UPS is unable to even find a suggestion. Using the above address as an example, If I make the same call but without including the street address (so I'm just sending city, state, zip, and country), the actually response is:

SimpleXMLElement {#797 ▼
  +"Response": SimpleXMLElement {#786 ▶}
  +"NoCandidatesIndicator": SimpleXMLElement {#785}
  +"AddressClassification": SimpleXMLElement {#776 ▼
    +"Code": "0"
    +"Description": "Unknown"
  }
}

What is returned from this is an empty object that contains no properties

{#768}

That empty object is extraordinarily unhelpful.

So, that is a long way to say, is it possible to return the full response instead of just the tiny subset?

TimeInTransit issue

Hi,

I am trying to get the estimated delivery times on my website using the TimeInTransit API. Everything seems to work well but I have this issue and I can't figure out why :

Failure (Hard): The XML document is well formed but the document is not valid

Any idea?
Thanks!

How to know if it is in production or integration mode?

UPS is giving API access in 2 modes: Production and Integration (Testing) modes. There is no option here to decide if I am using it in which mode.

I am using this to create a return label. API is working good, no issues with that. All I need to know is this. How to switch from/to Production/Integration.

No tracking information available error

Hello, I am receiving the following error:
InvalidResponseException in Request.php line 131:
Failure: No tracking information available (151044)

when trying to track an order that UPS does not have tracking info for. The error is preventing my code from executing further. After tracing the error, I found that it occurs at line 94 of Tracking.php:

$this->response = $this->getRequest()->request($access, $request, $this->compileEndpointUrl(self::ENDPOINT));

I've managed to correct the error by putting a try catch around that section of code but I doubt that's an "ideal" solution. It looks like there may be some error handling set up for that function already but most of the code is over my head so I haven't been able to make sense of it.

Charges class gives a Notice on some cases

Charges class gives the following Notice:

Notice: Object of class stdClass could not be converted to double in Ups/Entity/Charges.php on line 19

This happens because it receives $response->MonetaryValue equal to null or empty array, while String is expected

Stack calls that cause the notice:
Ups\Rate->shopRates
Ups\Rate->sendRequest
Ups\Rate->formatResponse
Ups\Entity\RateResponse->__construct
Ups\Entity\RatedShipment->__construct
Ups\Entity\RatedPackage->__construct
Ups\Entity\Charges->__construct( $response = class stdClass { public $CurrencyCode = class stdClass { }; public $MonetaryValue = class stdClass { } } )

Temporary fix, replace line 19 with line: if (isset($response->MonetaryValue) && $response->MonetaryValue instanceof String) {

Proper fix should investigate the sources of Class initilaization with null and empty array values passes

Using ShipFrom emits notices

Using the ShipFrom attribute causes notices to be emitted. This is due to not using isset() around various attributes when assembling the XML document for UPS. The following diff to Ups/Shipping.php fixes this.

@@ -178,15 +178,15 @@ class Shipping extends Ups

             $shipFromNode->appendChild($xml->createElement('CompanyName', $shipment->ShipFrom->CompanyName));

-            if ($shipment->ShipFrom->AttentionName) {
+            if (isset($shipment->ShipFrom->AttentionName)) {
                 $shipFromNode->appendChild($xml->createElement('AttentionName', $shipment->ShipFrom->AttentionName));
             }

-            if ($shipment->ShipFrom->PhoneNumber) {
+            if (isset($shipment->ShipFrom->PhoneNumber)) {
                 $shipFromNode->appendChild($xml->createElement('PhoneNumber', $shipment->ShipFrom->PhoneNumber));
             }

-            if ($shipment->ShipFrom->FaxNumber) {
+            if (isset($shipment->ShipFrom->FaxNumber)) {
                 $shipFromNode->appendChild($xml->createElement('FaxNumber', $shipment->ShipFrom->FaxNumber));
             }

@@ -197,25 +197,25 @@ class Shipping extends Ups
         if (isset($shipment->SoldTo)) {
             $soldToNode = $shipmentNode->appendChild($xml->createElement('SoldTo'));

-            if ($shipment->SoldTo->Option) {
+            if (isset($shipment->SoldTo->Option)) {
                 $soldToNode->appendChild($xml->createElement('Option', $shipment->SoldTo->Option));
             }

             $soldToNode->appendChild($xml->createElement('CompanyName', $shipment->SoldTo->CompanyName));

-            if ($shipment->SoldTo->AttentionName) {
+            if (isset($shipment->SoldTo->AttentionName)) {
                 $soldToNode->appendChild($xml->createElement('AttentionName', $shipment->SoldTo->AttentionName));
             }

-            if ($shipment->SoldTo->PhoneNumber) {
+            if (isset($shipment->SoldTo->PhoneNumber)) {
                 $soldToNode->appendChild($xml->createElement('PhoneNumber', $shipment->SoldTo->PhoneNumber));
             }

-            if ($shipment->SoldTo->FaxNumber) {
+            if (isset($shipment->SoldTo->FaxNumber)) {
                 $soldToNode->appendChild($xml->createElement('FaxNumber', $shipment->SoldTo->FaxNumber));
             }

-            if ($shipment->SoldTo->Address) {
+            if (isset($shipment->SoldTo->Address)) {
                 $addressNode = $xml->importNode($this->compileAddressNode($shipment->SoldTo->Address), true);
                 $soldToNode->appendChild($addressNode);
             }

PoliticalDivision1 and PoliticalDivision2 are mismatched

I've had some issues with address validation almost always returning 0 or "Unknown" for addresses that I know are defined as commercial. After some digging around, I've found that in AddressValidation.php

if ($this->address->getStateProvinceCode()) {
    $addressNode->appendChild($xml->createElement('PoliticalDivision2',
        $this->address->getStateProvinceCode()));
}
if ($this->address->getCity()) {
    $addressNode->appendChild($xml->createElement('PoliticalDivision1', $this->address->getCity()));
}

The use of PoliticalDivision2 for state/province and PoliticalDivision1 for city, are actually mismatched.

As per the UPS Address Validation Street Level XML Developers Guide, PoliticalDivision2 is for City or town name, and PoliticalDivision1 is for State or Province/Territory name.

Shipping class refactoring is not finished

Hey,

it seems that You are using old public properties during confirmRequest creation, but using getters and setters when preparing Shipping class does not populate them. ConfirmRequest ends up almost empty and of course that request is not accepted by UPS.

Also, PaymentInformation entity is missing both as class and in Shippment class.

Specify Residential vs Business

Is there a way to specify a residential address vs a business address in the getRate function?

I am assuming it would be some flag to set in

$shipTo = $shipment->getShipTo();
$shipTo->setCompanyName('Test Ship To');
$shipToAddress = $shipTo->getAddress();
$shipToAddress->setPostalCode($inputs['shippingZip']);

Any help would be greatly appreciated!

Set node value for entity RateInformation

Hi
It seems that nodeValue is not set is toNode function of the RateInformation entity.
Second parameter of createElement is not set.

Patch example :

$negociatedRatesIndicator = $this->getNegotiatedRatesIndicator();
if ($this->getNegotiatedRatesIndicator()) {
    $node->appendChild($document->createElement('NegotiatedRatesIndicator', $negociatedRatesIndicator));
}

Pickup-API

Hi thanks for the awesome work! Is the Pickup-API supported with this Package?

Shipping weight > 150lbs...?

Hi,

Does the class handle weight > 150lbs? From what I understand, anything over 150lbs needs to use LTL or Freight, but I don't see any reference to that in the code.

Cheers,
Michael.

Label as PDF

is it possible to get the label as pdf.

anyone knows the LabelPrintType param?

Failure: Missing or invalid shipper number (120100)

I have linked the ups account in Manage Accounts and I got the shipper number in hands. But where to add it in the code? And why am I getting the error

Failure: Missing or invalid shipper number (120100)

Getting rate information from Tracking object

I am using this function in order to get my tracking object $tracking->track($order->provider->providers_tracking);

When using this I need to get the Rate of the package that I looked up. Is there a way to get this information?

Here is the package information - Replaced information with %%

object(stdClass)[1154]
public 'Shipper' =>
object(stdClass)[1155]
public 'ShipperNumber' => string '%%' (length=6)
public 'Address' =>
object(stdClass)[1156]
public 'AddressLine1' => string '%%' (length=15)
public 'City' => string '%%' (length=6)
public 'StateProvinceCode' => string '%%' (length=2)
public 'PostalCode' => string '%%' (length=12)
public 'CountryCode' => string 'US' (length=2)
public 'ShipTo' =>
object(stdClass)[1157]
public 'Address' =>
object(stdClass)[1158]
public 'City' => string '%%' (length=16)
public 'StateProvinceCode' => string '%%' (length=2)
public 'PostalCode' => string '%%' (length=5)
public 'CountryCode' => string 'US' (length=2)
public 'ShipmentWeight' =>
object(stdClass)[1159]
public 'UnitOfMeasurement' =>
object(stdClass)[1160]
public 'Code' => string '%%' (length=3)
public 'Weight' => string '%%' (length=4)
public 'Service' =>
object(stdClass)[1161]
public 'Code' => string '%%' (length=3)
public 'Description' => string '%%' (length=6)
public 'ReferenceNumber' =>
array (size=2)
0 =>
object(stdClass)[1162]
public 'Code' => string '%%' (length=2)
public 'Value' => string '%%' (length=5)
1 =>
object(stdClass)[1163]
public 'Code' => string '%%' (length=2)
public 'Value' => string '%%' (length=5)
public 'ShipmentIdentificationNumber' => string '%%' (length=18)
public 'PickupDate' => string '%%' (length=8)
public 'DeliveryDateUnavailable' =>
object(stdClass)[1164]
public 'Type' => string 'Scheduled Delivery' (length=18)
public 'Description' => string 'Scheduled Delivery Date is not currently available, please try back later' (length=73)
public 'Package' =>
object(stdClass)[1165]
public 'TrackingNumber' => string '%%' (length=18)
public 'Activity' =>
array (size=6)
0 =>
object(stdClass)[1166]
...
1 =>
object(stdClass)[1172]
...
2 =>
object(stdClass)[1178]
...
3 =>
object(stdClass)[1184]
...
4 =>
object(stdClass)[1190]
...
5 =>
object(stdClass)[1196]
...
public 'PackageWeight' =>
object(stdClass)[1202]
public 'UnitOfMeasurement' =>
object(stdClass)[1203]
...
public 'Weight' => string '3.00' (length=4)
public 'ReferenceNumber' =>
array (size=2)
0 =>
object(stdClass)[1204]
...
1 =>
object(stdClass)[1205]
...

How to set unit for weight in package

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

Failure: The requested service is invalid for the shipment origin (121100)

// To address
$address = new \Ups\Entity\Address();
$address->setAddressLine1('AlterKnit New York');
$address->setAddressLine2('245 W');
$address->setAddressLine3('29th St');
$address->setPostalCode('10001');
$address->setCity('New York');
$address->setCountryCode('US');
$address->setStateProvinceCode('NY');
$shipTo = new \Ups\Entity\ShipTo();
$shipTo->setAddress($address);
$shipTo->setCompanyName('KNIT NY LLC');
$shipTo->setAttentionName('AlterKnit New York');
$shipTo->setEmailAddress('[email protected]'); 
$shipTo->setPhoneNumber('2124736363');
$shipment->setShipTo($shipTo);

// From address

$address = new \Ups\Entity\Address();
$address->setAddressLine1('CHRIS NISWANDEE, SMALLSYS INC');
$address->setAddressLine2('795 E DRAGRAM');
$address->setPostalCode('85705');
$address->setCity('TUCSON');
$address->setCountryCode('US');
$address->setStateProvinceCode('AZ');
$shipFrom = new \Ups\Entity\ShipFrom();
$shipFrom->setAddress($address);
$shipFrom->setName('Joseph Daniel');
$shipFrom->setAttentionName($shipFrom->getName());
$shipFrom->setCompanyName($shipFrom->getName());
$shipFrom->setEmailAddress('[email protected]');
$shipFrom->setPhoneNumber('8903444595');
$shipment->setShipFrom($shipFrom);

I have no idea where I am doing a mistake. I am getting Failure: The requested service is invalid for the shipment origin (121100). Please help.

Shipping class

Is there any problem with it or it is ready to use but not documented?

Can someone please provide sample code if it is safe to use?

Thank you.

Display ErrorLocation

Can you please add ErrorLocation field, to the message of InvalidResponseException, that is thrown in /src/Request.php on line 131? It will help a lot, as ErrorCode and ErrorDescription is not enough to understand where is the problem.

XML not properly formatted for Webservers. Works for xml but not webservices

For example a request for rate at ups.app/xml/Rate is properly formatted but a request to /webservices/Tradeability is not properly formatted. We used your tradeability example to test with and it would not go through to ups when requesting the endpoint https://wwwcie.ups.com/webservices/LandedCost

Thanks for any help on this.

ups.app/xml/Rate expects something like

            <?xml version=\"1.0\"?>
            <AccessRequest xml:lang=\"en-US\">
                <AccessLicenseNumber>" . $this->access_key . "</AccessLicenseNumber>
                <UserId>" . $this->ups_account_username . "</UserId>
                <Password>" . $this->ups_account_password . "</Password>
            </AccessRequest>
            <?xml version=\"1.0\"?>
            <AddressValidationRequest xml:lang=\"en-US\">
                <Request>
                    <TransactionReference>
                        <CustomerContext>Address Validation Request From " . $_SERVER['HTTP_HOST'] . "</CustomerContext>
                        <XpciVersion>1.0001</XpciVersion>
                    </TransactionReference>
                    <RequestAction>AV</RequestAction>
                </Request>
                <Address>
                    <City>".$city."</City>
                    <StateProvinceCode>".$state."</StateProvinceCode>
                    <PostalCode>".$zip."</PostalCode>
                </Address>
            </AddressValidationRequest>

but /webservices/Tradeability expects something like

<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:auth="http://www.ups.com/schema/xpci/1.0/auth"
              xmlns:lc="http://www.ups.com/schema/xpci/1.0/lc" xmlns:wsf="http://www.ups.com/schema/wsf">
    <env:Header>
        <auth:AccessRequest xml:lang="en-US">
            <auth:AccessLicenseNumber></auth:AccessLicenseNumber>
            <auth:UserId></auth:UserId>
            <auth:Password></auth:Password>
        </auth:AccessRequest>
    </env:Header>
    <env:Body>
        <lc:LandedCostRequest xml:lang="en-US">
            <lc:Request>
                <lc:TransactionReference/>
                <lc:RequestAction>LandedCost</lc:RequestAction>
            </lc:Request>
            <lc:QueryRequest>
                <lc:Shipment>
                    <lc:OriginCountryCode>US</lc:OriginCountryCode>
                    <lc:DestinationCountryCode>CA</lc:DestinationCountryCode>
                    <lc:DestinationStateProvinceCode>ON</lc:DestinationStateProvinceCode>
                    <lc:TransportationMode>1</lc:TransportationMode>
                    <lc:ResultCurrencyCode>USD</lc:ResultCurrencyCode>
                    <lc:TariffCodeAlert>1</lc:TariffCodeAlert>
                    <lc:TransactionReferenceID>1</lc:TransactionReferenceID>
                    <lc:Product>
                        <lc:TariffInfo>
                            <lc:TariffCode>4911.99.0050</lc:TariffCode>
                        </lc:TariffInfo>
                        <lc:UnitPrice>
                            <lc:MonetaryValue>500</lc:MonetaryValue>
                            <lc:CurrencyCode>USD</lc:CurrencyCode>
                        </lc:UnitPrice>
                        <lc:Quantity>
                            <lc:Value>5000</lc:Value>
                            <lc:UnitOfMeasure>
                                <lc:UnitCode>PCS</lc:UnitCode>
                            </lc:UnitOfMeasure>
                        </lc:Quantity>
                        <lc:ProductName>Labels</lc:ProductName>
                        <lc:ProductCountryCodeOfOrigin>CA</lc:ProductCountryCodeOfOrigin>
                        <lc:Weight>
                            <lc:Value>6</lc:Value>
                            <lc:UnitOfMeasure>
                                <lc:UnitCode>lb</lc:UnitCode>
                            </lc:UnitOfMeasure>
                        </lc:Weight>
                        <lc:TariffCodeAlert>1</lc:TariffCodeAlert>
                    </lc:Product>
                </lc:Shipment>
                <lc:SuppressQuestionIndicator>Y</lc:SuppressQuestionIndicator>
            </lc:QueryRequest>
        </lc:LandedCostRequest>
    </env:Body>
</env:Envelope>

Shipping API

Hi

I'm trying to use the Shipping API but I must be missing something in my call, but I cannot find what.

Below is the error and XML I'm sending. If anyone could help out I'd be happy to write up some sample calls for the Readme.

The XML document is well formed but the document is not valid (10002)
<?xml version="1.0"?>
<ShipmentConfirmRequest>
  <Request>
    <TransactionReference/>
    <RequestAction>ShipConfirm</RequestAction>
    <RequestOption>nonvalidate</RequestOption>
  </Request>
  <Shipment>
    <Shipper>
      <Name/>
      <ShipperNumber>9W3461</ShipperNumber>
      <Address>
        <City>Fake City</City>
        <PostalCode>NR18 0WZ</PostalCode>
        <CountryCode>GB</CountryCode>
      </Address>
    </Shipper>
    <ShipTo>
      <CompanyName>Kennedy Limited</CompanyName>
      <Address>
        <AddressLine1>160 Isaac Burgs</AddressLine1>
        <AddressLine2>Jim Court</AddressLine2>
        <City>Port Lily</City>
        <PostalCode>G4U 2CU</PostalCode>
        <CountryCode>GB</CountryCode>
      </Address>
    </ShipTo>
    <ShipFrom>
      <CompanyName/>
      <Address>
        <City>Fake City</City>
        <PostalCode>NR18 0WZ</PostalCode>
        <CountryCode>GB</CountryCode>
      </Address>
    </ShipFrom>
    <PaymentInformation>
      <ConsigneeBilled/>
    </PaymentInformation>
    <Service>
      <Code>11</Code>
    </Service>
    <RateInformation>
      <NegotiatedRatesIndicator/>
    </RateInformation>
    <Package>
      <PackagingType>
        <Code>02</Code>
        <Description/>
      </PackagingType>
      <PackageWeight>
        <Weight>3.000</Weight>
        <UnitOfMeasurement>
          <Code>KGS</Code>
          <Description/>
        </UnitOfMeasurement>
      </PackageWeight>
      <Dimensions>
        <Length>40</Length>
        <Height>50</Height>
        <Width>30</Width>
        <UnitOfMeasurement>
          <Code>CM</Code>
          <Description/>
        </UnitOfMeasurement>
      </Dimensions>
      <PackageServiceOptions/>
    </Package>
    <ShipmentServiceOptions/>
    <ReferenceNumber>
      <Code>ON</Code>
      <Value>142</Value>
    </ReferenceNumber>
  </Shipment>
</ShipmentConfirmRequest>

Create a return label

How to create a return label? I tried so hard to understand, but the documentation is missing!! Can you provide an example of how to create return label?

Are services for domestic shipping within Sweden also here?

Hi,
I come across methods for Sweden:
http://www.ups.com/content/se/sv/shipping/time/service/index.html?WT.svl=SubNav
UPS Express Plus
UPS Express
UPS Express Saver

But In here I've found those:
EXPRESS (75)
EXPRESSPLUS (54)
NEXTDAYAIRSAVER (13)

Naming similar but not quite, I'm not sure about NEXTDAYAIRSAVER - seems it's US only.
Is there any info as to whether I can use it for a company based in Sweden as well?
Which service are you using in order to get the list of tranportation services?
Thank you!

Failure: Multiple shipper numbers found with trackByReference

Hi!

To track shipments I am using track() (which works fine) and trackByReference(). With trackByReference I am getting "Failure: Multiple shipper numbers found (151085)."

Do you know what might cause this error and how I can solve this issue?

Thanks!

$rate->getRates($shipment) is showing error

From today when I updated this repo then $rate->getRates($shipment) is showing me error. The Stack Trace is here:

Stack trace:
#0 /var/www/ups-php/vendor/gabrielbull/ups-api/src/Ups/Rate.php(47): Ups\Rate->sendRequest(Object(stdClass))
#1 /var/www/ups-php/index.php(49): Ups\Rate->getRate(Object(stdClass))
#2 {main}
  thrown in /var/www/ups-php/vendor/gabrielbull/ups-api/src/Ups/Rate.php on line 64" while reading response header from upstream, client: 127.0.0.1, server: ups-php.dev, request: "GET /favicon.ico HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "ups-php.dev"
2014/05/12 19:43:14 [error] 1271#0: *56 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught exception 'Exception' with message 'Failure (Hard): The XML document is well formed but the document is not valid' in /var/www/ups-php/vendor/gabrielbull/ups-api/src/Ups/Rate.php:64

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.