onetikk/ot-ups-api
Composer 安装命令:
composer require onetikk/ot-ups-api
包简介
PHP UPS API
README 文档
README
UPS PHP Api
This is modified version of gabrielbull's PHP UPS API, also included laravel wrapper as well. We made some custom changes as per our need. If you want gabrielbull 's PHP API please visit 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
- Requirements
- Installation
- Address Validation Class
- Simple Address Validation Class
- QuantumView Class
- Tracking Class
- Rate Class
- RateTimeInTransit Class
- TimeInTransit Class
- Locator Class
- Tradeability Class
- Shipping Class
- Logging
- 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.
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:
addressAddress object as constructed in examplerequestOptionOne of the three request options. See documentation. Default = Address Validation.maxSuggestionMaximum 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:
addressAddress 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:
nameName of subscription requested by user. If null, all events will be returned.beginDateTimeBeginning date time for the retrieval criteria of the subscriptions. Format: Y-m-d H:i:s or Unix timestamp.endDateTimeEnding date time for the retrieval criteria of the subscriptions. Format: Y-m-d H:i:s or Unix timestamp.fileNameFile name of specific subscription requested by user.bookmarkBookmarks 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:
trackingNumberThe package’s tracking number.requestOptionOptional 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:
referenceNumberThe 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.requestOptionOptional 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
rateRequestMandatory. 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
rateRequestMandatory. 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
timeInTransitRequestMandatory. 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:
locatorRequestMandatory. locatorRequest object with request details, see examplerequestOptionOptional. Type of locations you are searching for.
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)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
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
License
PHP UPS API is licensed under The MIT License (MIT).
onetikk/ot-ups-api 适用场景与选型建议
onetikk/ot-ups-api 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 9 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 03 月 18 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「shipping」 「ups」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 onetikk/ot-ups-api 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 onetikk/ot-ups-api 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 onetikk/ot-ups-api 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Fetch rates, track packages and verify addresses via the UPS API
PHP SDK for the Parcel Monkey UK API
The PHP SDK of TrackingMore API
A PSR-7 compatible library for making CRUD API endpoints
PHP wrapper for DPD Germany SOAP API
Metamel Addresses is a polymorphic Laravel package, for address book management. You can add addresses to any eloquent model with ease.
统计信息
- 总下载量: 9
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-03-18