PHP code example of gregpunla / ups-api

1. Go to this page and download the library: Download gregpunla/ups-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gregpunla / ups-api example snippets


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


if ($response->noCandidates()) {
    //Do something clever and helpful to let the use know the address is invalid
}
if ($response->isAmbiguous()) {
    $candidateAddresses = $response->getCandidateAddressList();
    foreach($candidateAddresses as $address) {
        //Present user with list of candidate addresses so they can pick the correct one        
    }
}
if ($response->isValid()) {
    $validAddress = $response->getValidatedAddress();
    
    //Show user validated address or update their address with the 'official' address
    //Or do something else helpful...
}

$address = 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);
}

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

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

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

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

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

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

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

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

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

    // 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'); // e('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);
    }

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