Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Data Fields | Protected Member Functions | Protected Attributes
Carrier Class Reference
Inheritance diagram for Carrier:
AbstractCarrierOnline CarrierInterface AbstractCarrier DataObject AbstractCarrierInterface

Public Member Functions

 __construct (\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, Security $xmlSecurity, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, \Magento\Directory\Model\RegionFactory $regionFactory, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Helper\Data $directoryData, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, CarrierHelper $carrierHelper, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory, array $data=[])
 
 collectRates (RateRequest $request)
 
 setRequest (\Magento\Quote\Model\Quote\Address\RateRequest $request)
 
 getResult ()
 
 isShippingLabelsAvailable ()
 
 getCode ($type, $code='')
 
 getTracking ($trackings)
 
 getResponse ()
 
 getAllowedMethods ()
 
 getContainerTypes (\Magento\Framework\DataObject $params=null)
 
 getContainerTypesAll ()
 
 getContainerTypesFilter ()
 
 getDeliveryConfirmationTypes (\Magento\Framework\DataObject $params=null)
 
 isGirthAllowed ($countyDest=null, $carrierMethodCode=null)
 
 getContentTypes (\Magento\Framework\DataObject $params)
 
- Public Member Functions inherited from AbstractCarrierOnline
 __construct (\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, Security $xmlSecurity, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, \Magento\Directory\Model\RegionFactory $regionFactory, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Helper\Data $directoryData, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, array $data=[])
 
 setActiveFlag ($code='active')
 
 getCarrierCode ()
 
 getTrackingInfo ($tracking)
 
 isTrackingAvailable ()
 
 isCityRequired ()
 
 isZipCodeRequired ($countryId=null)
 
 isShippingLabelsAvailable ()
 
 getAllItems (RateRequest $request)
 
 proccessAdditionalValidation (\Magento\Framework\DataObject $request)
 
 requestToShipment ($request)
 
 returnOfShipment ($request)
 
 rollBack ($data)
 
 isGirthAllowed ($countyDest=null, $carrierMethodCode=null)
 
 setRawRequest ($request)
 
 getMethodPrice ($cost, $method='')
 
 parseXml ($xmlContent, $customSimplexml='SimpleXMLElement')
 
 canCollectRates ()
 
- Public Member Functions inherited from AbstractCarrier
 __construct (\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, array $data=[])
 
 getConfigData ($field)
 
 getConfigFlag ($field)
 
 requestToShipment ($request)
 
 returnOfShipment ($request)
 
 getContainerTypes (\Magento\Framework\DataObject $params=null)
 
 getCustomizableContainerTypes ()
 
 getDeliveryConfirmationTypes (\Magento\Framework\DataObject $params=null)
 
 processAdditionalValidation (\Magento\Framework\DataObject $request)
 
 proccessAdditionalValidation (\Magento\Framework\DataObject $request)
 
 isActive ()
 
 isFixed ()
 
 isTrackingAvailable ()
 
 isShippingLabelsAvailable ()
 
 getSortOrder ()
 
 getFinalPriceWithHandlingFee ($cost)
 
 getTotalNumOfBoxes ($weight)
 
 isStateProvinceRequired ()
 
 isCityRequired ()
 
 isZipCodeRequired ($countryId=null)
 
 getDebugFlag ()
 
 debugData ($debugData)
 
 getCarrierCode ()
 
 getContentTypes (\Magento\Framework\DataObject $params)
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 
- Public Member Functions inherited from AbstractCarrierInterface
 checkAvailableShipCountries (\Magento\Framework\DataObject $request)
 
- Public Member Functions inherited from CarrierInterface
 isTrackingAvailable ()
 

Data Fields

const CONTAINER_VARIABLE = 'VARIABLE'
 
const CONTAINER_FLAT_RATE_BOX = 'FLAT RATE BOX'
 
const CONTAINER_FLAT_RATE_ENVELOPE = 'FLAT RATE ENVELOPE'
 
const CONTAINER_RECTANGULAR = 'RECTANGULAR'
 
const CONTAINER_NONRECTANGULAR = 'NONRECTANGULAR'
 
const SIZE_REGULAR = 'REGULAR'
 
const SIZE_LARGE = 'LARGE'
 
const DEFAULT_REVISION = 2
 
const CODE = 'usps'
 
const OUNCES_POUND = 16
 
- Data Fields inherited from AbstractCarrierOnline
const USA_COUNTRY_ID = 'US'
 
const PUERTORICO_COUNTRY_ID = 'PR'
 
const GUAM_COUNTRY_ID = 'GU'
 
const GUAM_REGION_CODE = 'GU'
 
- Data Fields inherited from AbstractCarrier
const DEBUG_KEYS_MASK = '****'
 
const USA_COUNTRY_ID = 'US'
 
const CANADA_COUNTRY_ID = 'CA'
 
const MEXICO_COUNTRY_ID = 'MX'
 
const HANDLING_TYPE_PERCENT = 'P'
 
const HANDLING_TYPE_FIXED = 'F'
 
const HANDLING_ACTION_PERPACKAGE = 'P'
 
const HANDLING_ACTION_PERORDER = 'O'
 

Protected Member Functions

 _getQuotes ()
 
 _setFreeMethodRequest ($freeMethod)
 
 _getXmlQuotes ()
 
 _parseXmlResponse ($response)
 
 setTrackingReqeust ()
 
 _getXmlTracking ($trackings)
 
 _parseXmlTrackingResponse ($trackingvalue, $response)
 
 _getCountryName ($countryId)
 
 _filterServiceName ($name)
 
 _formUsExpressShipmentRequest (\Magento\Framework\DataObject $request)
 
 _formUsSignatureConfirmationShipmentRequest (\Magento\Framework\DataObject $request, $serviceType)
 
 _convertPoundOunces ($weightInPounds)
 
 _formIntlShipmentRequest (\Magento\Framework\DataObject $request)
 
 _doShipmentRequest (\Magento\Framework\DataObject $request)
 
 _parseZip ($zipString, $returnFull=false)
 
- Protected Member Functions inherited from AbstractCarrierOnline
 _getQuotesCacheKey ($requestParams)
 
 _getCachedQuotes ($requestParams)
 
 _setCachedQuotes ($requestParams, $response)
 
 _prepareServiceName ($name)
 
 _prepareShipmentRequest (\Magento\Framework\DataObject $request)
 
 _doShipmentRequest (\Magento\Framework\DataObject $request)
 
 _isUSCountry ($countyId)
 
 debugErrors ($errors)
 
 getErrorMessage ()
 
- Protected Member Functions inherited from AbstractCarrier
 _getAllowedContainers (\Magento\Framework\DataObject $params=null)
 
 _updateFreeMethodQuote ($request)
 
 _getPerpackagePrice ($cost, $handlingType, $handlingFee)
 
 _getPerorderPrice ($cost, $handlingType, $handlingFee)
 
 _debug ($debugData)
 
 filterDebugData ($data)
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_code = self::CODE
 
 $_request = null
 
 $_result = null
 
 $_defaultGatewayUrl = 'http://production.shippingapis.com/ShippingAPI.dll'
 
 $_customizableContainerTypes = ['VARIABLE', 'RECTANGULAR', 'NONRECTANGULAR']
 
 $_carrierHelper
 
 $_productCollectionFactory
 
 $_httpClientFactory
 
 $_debugReplacePrivateDataKeys
 
- Protected Attributes inherited from AbstractCarrierOnline
 $_activeFlag = 'active'
 
 $_directoryData = null
 
 $_xmlElFactory
 
 $_rateFactory
 
 $_rateMethodFactory
 
 $_trackFactory
 
 $_trackErrorFactory
 
 $_trackStatusFactory
 
 $_regionFactory
 
 $_countryFactory
 
 $_currencyFactory
 
 $stockRegistry
 
 $_rawRequest = null
 
 $xmlSecurity
 
- Protected Attributes inherited from AbstractCarrier
 $_code
 
 $_rates
 
 $_numBoxes = 1
 
 $_freeMethod = 'free_method'
 
 $_isFixed = false
 
 $_customizableContainerTypes = []
 
 $_debugReplacePrivateDataKeys = []
 
 $_scopeConfig
 
 $_rateErrorFactory
 
 $_logger
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Protected Attributes inherited from AbstractCarrierOnline
static $_quotesCache = []
 
- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

USPS shipping @SuppressWarnings(PHPMD.ExcessiveClassComplexity) @SuppressWarnings(PHPMD.CouplingBetweenObjects)

Definition at line 22 of file Carrier.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Framework\App\Config\ScopeConfigInterface  $scopeConfig,
\Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory  $rateErrorFactory,
\Psr\Log\LoggerInterface  $logger,
Security  $xmlSecurity,
\Magento\Shipping\Model\Simplexml\ElementFactory  $xmlElFactory,
\Magento\Shipping\Model\Rate\ResultFactory  $rateFactory,
\Magento\Quote\Model\Quote\Address\RateResult\MethodFactory  $rateMethodFactory,
\Magento\Shipping\Model\Tracking\ResultFactory  $trackFactory,
\Magento\Shipping\Model\Tracking\Result\ErrorFactory  $trackErrorFactory,
\Magento\Shipping\Model\Tracking\Result\StatusFactory  $trackStatusFactory,
\Magento\Directory\Model\RegionFactory  $regionFactory,
\Magento\Directory\Model\CountryFactory  $countryFactory,
\Magento\Directory\Model\CurrencyFactory  $currencyFactory,
\Magento\Directory\Helper\Data  $directoryData,
\Magento\CatalogInventory\Api\StockRegistryInterface  $stockRegistry,
CarrierHelper  $carrierHelper,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory  $productCollectionFactory,
\Magento\Framework\HTTP\ZendClientFactory  $httpClientFactory,
array  $data = [] 
)
Parameters
\Magento\Framework\App\Config\ScopeConfigInterface$scopeConfig
\Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory$rateErrorFactory
\Psr\Log\LoggerInterface$logger
Security$xmlSecurity
\Magento\Shipping\Model\Simplexml\ElementFactory$xmlElFactory
\Magento\Shipping\Model\Rate\ResultFactory$rateFactory
\Magento\Quote\Model\Quote\Address\RateResult\MethodFactory$rateMethodFactory
\Magento\Shipping\Model\Tracking\ResultFactory$trackFactory
\Magento\Shipping\Model\Tracking\Result\ErrorFactory$trackErrorFactory
\Magento\Shipping\Model\Tracking\Result\StatusFactory$trackStatusFactory
\Magento\Directory\Model\RegionFactory$regionFactory
\Magento\Directory\Model\CountryFactory$countryFactory
\Magento\Directory\Model\CurrencyFactory$currencyFactory
\Magento\Directory\Helper\Data$directoryData
\Magento\CatalogInventory\Api\StockRegistryInterface$stockRegistry
\Magento\Shipping\Helper\Carrier$carrierHelper
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory$productCollectionFactory
\Magento\Framework\HTTP\ZendClientFactory$httpClientFactory
array$data@SuppressWarnings(PHPMD.ExcessiveParameterList)

Definition at line 159 of file Carrier.php.

179  {
180  $this->_carrierHelper = $carrierHelper;
181  $this->_productCollectionFactory = $productCollectionFactory;
182  $this->_httpClientFactory = $httpClientFactory;
183  parent::__construct(
184  $scopeConfig,
185  $rateErrorFactory,
186  $logger,
187  $xmlSecurity,
188  $xmlElFactory,
189  $rateFactory,
190  $rateMethodFactory,
191  $trackFactory,
192  $trackErrorFactory,
193  $trackStatusFactory,
194  $regionFactory,
195  $countryFactory,
196  $currencyFactory,
197  $directoryData,
199  $data
200  );
201  }
$logger

Member Function Documentation

◆ _convertPoundOunces()

_convertPoundOunces (   $weightInPounds)
protected

Convert decimal weight into pound-ounces format

Parameters
float$weightInPounds
Returns
float[]

Definition at line 1593 of file Carrier.php.

1594  {
1595  $weightInOunces = ceil($weightInPounds * self::OUNCES_POUND);
1596  $pounds = floor($weightInOunces / self::OUNCES_POUND);
1597  $ounces = $weightInOunces % self::OUNCES_POUND;
1598 
1599  return [$pounds, $ounces];
1600  }

◆ _doShipmentRequest()

_doShipmentRequest ( \Magento\Framework\DataObject  $request)
protected

Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response

Parameters
\Magento\Framework\DataObject$request
Returns
\Magento\Framework\DataObject @SuppressWarnings(PHPMD.CyclomaticComplexity)
Deprecated:
100.2.1 This method must not be used anymore. Starting from 23.02.2018 USPS elimates API usage for free shipping labels generating.

Definition at line 1870 of file Carrier.php.

1871  {
1873  $result = new \Magento\Framework\DataObject();
1874  $service = $this->getCode('service_to_code', $request->getShippingMethod());
1875  $recipientUSCountry = $this->_isUSCountry($request->getRecipientAddressCountryCode());
1876 
1877  if ($recipientUSCountry && $service == 'Priority Express') {
1878  $requestXml = $this->_formUsExpressShipmentRequest($request);
1879  $api = 'ExpressMailLabel';
1880  } else {
1881  if ($recipientUSCountry) {
1883  if ($this->getConfigData('mode')) {
1884  $api = 'SignatureConfirmationV3';
1885  } else {
1886  $api = 'SignatureConfirmationCertifyV3';
1887  }
1888  } else {
1889  if ($service == 'First Class') {
1890  $requestXml = $this->_formIntlShipmentRequest($request);
1891  $api = 'FirstClassMailIntl';
1892  } else {
1893  if ($service == 'Priority') {
1894  $requestXml = $this->_formIntlShipmentRequest($request);
1895  $api = 'PriorityMailIntl';
1896  } else {
1897  $requestXml = $this->_formIntlShipmentRequest($request);
1898  $api = 'ExpressMailIntl';
1899  }
1900  }
1901  }
1902  }
1903 
1904  $debugData = ['request' => $this->filterDebugData($requestXml)];
1905  $url = $this->getConfigData('gateway_secure_url');
1906  if (!$url) {
1908  }
1909  $client = $this->_httpClientFactory->create();
1910  $client->setUri($url);
1911  $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
1912  $client->setParameterGet('API', $api);
1913  $client->setParameterGet('XML', $requestXml);
1914  $response = $client->request()->getBody();
1915 
1916  $response = $this->parseXml($response);
1917 
1918  if ($response !== false) {
1919  if ($response->getName() == 'Error') {
1920  $debugData['result'] = [
1921  'error' => $response->Description,
1922  'code' => $response->Number,
1923  'xml' => $response->asXML(),
1924  ];
1925  $this->_debug($debugData);
1926  $result->setErrors($debugData['result']['error']);
1927  } else {
1928  if ($recipientUSCountry && $service == 'Priority Express') {
1929  $labelContent = base64_decode((string)$response->EMLabel);
1930  $trackingNumber = (string)$response->EMConfirmationNumber;
1931  } elseif ($recipientUSCountry) {
1932  $labelContent = base64_decode((string)$response->SignatureConfirmationLabel);
1933  $trackingNumber = (string)$response->SignatureConfirmationNumber;
1934  } else {
1935  $labelContent = base64_decode((string)$response->LabelImage);
1936  $trackingNumber = (string)$response->BarcodeNumber;
1937  }
1938  $result->setShippingLabelContent($labelContent);
1939  $result->setTrackingNumber($trackingNumber);
1940  }
1941  }
1942 
1943  $result->setGatewayResponse($response);
1944  $debugData['result'] = $response;
1945  $this->_debug($debugData);
1946 
1947  return $result;
1948  }
_prepareShipmentRequest(\Magento\Framework\DataObject $request)
$response
Definition: 404.php:11
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
_formUsSignatureConfirmationShipmentRequest(\Magento\Framework\DataObject $request, $serviceType)
Definition: Carrier.php:1508
_formIntlShipmentRequest(\Magento\Framework\DataObject $request)
Definition: Carrier.php:1615
getCode($type, $code='')
Definition: Carrier.php:649
parseXml($xmlContent, $customSimplexml='SimpleXMLElement')
_formUsExpressShipmentRequest(\Magento\Framework\DataObject $request)
Definition: Carrier.php:1438

◆ _filterServiceName()

_filterServiceName (   $name)
protected

Clean service name from unsupported strings and characters

Parameters
string$name
Returns
string

Definition at line 1416 of file Carrier.php.

1417  {
1418  $name = (string)preg_replace(
1419  ['~<[^/!][^>]+>.*</[^>]+>~sU', '~<!--.*-->~isU', '~<[^>]+>~is'],
1420  '',
1421  html_entity_decode($name)
1422  );
1423  $name = str_replace('*', '', $name);
1424 
1425  return $name;
1426  }
if(!isset($_GET['name'])) $name
Definition: log.php:14

◆ _formIntlShipmentRequest()

_formIntlShipmentRequest ( \Magento\Framework\DataObject  $request)
protected

Form XML for international shipment request As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName> must be after <FromFirstName>

Parameters
\Magento\Framework\DataObject$request
Returns
string @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity) @SuppressWarnings(PHPMD.ExcessiveMethodLength)
Deprecated:
100.2.1 Should not be used anymore.
See also
\Magento\Usps\Model\Carrier::_doShipmentRequest doc block.

Definition at line 1615 of file Carrier.php.

1616  {
1617  $packageParams = $request->getPackageParams();
1618  $height = $packageParams->getHeight();
1619  $width = $packageParams->getWidth();
1620  $length = $packageParams->getLength();
1621  $girth = $packageParams->getGirth();
1622  $packageWeight = $request->getPackageWeight();
1623  if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) {
1624  $packageWeight = $this->_carrierHelper->convertMeasureWeight(
1625  (float)$request->getPackageWeight(),
1626  $packageParams->getWeightUnits(),
1628  );
1629  }
1630  if ($packageParams->getDimensionUnits() != \Zend_Measure_Length::INCH) {
1631  $length = round(
1632  $this->_carrierHelper->convertMeasureDimension(
1633  (float)$packageParams->getLength(),
1634  $packageParams->getDimensionUnits(),
1636  )
1637  );
1638  $width = round(
1639  $this->_carrierHelper->convertMeasureDimension(
1640  (float)$packageParams->getWidth(),
1641  $packageParams->getDimensionUnits(),
1643  )
1644  );
1645  $height = round(
1646  $this->_carrierHelper->convertMeasureDimension(
1647  (float)$packageParams->getHeight(),
1648  $packageParams->getDimensionUnits(),
1650  )
1651  );
1652  }
1653  if ($packageParams->getGirthDimensionUnits() != \Zend_Measure_Length::INCH) {
1654  $girth = round(
1655  $this->_carrierHelper->convertMeasureDimension(
1656  (float)$packageParams->getGirth(),
1657  $packageParams->getGirthDimensionUnits(),
1659  )
1660  );
1661  }
1662 
1663  $container = $request->getPackagingType();
1664  switch ($container) {
1665  case 'VARIABLE':
1666  $container = 'VARIABLE';
1667  break;
1668  case 'FLAT RATE ENVELOPE':
1669  $container = 'FLATRATEENV';
1670  break;
1671  case 'FLAT RATE BOX':
1672  $container = 'FLATRATEBOX';
1673  break;
1674  case 'RECTANGULAR':
1675  $container = 'RECTANGULAR';
1676  break;
1677  case 'NONRECTANGULAR':
1678  $container = 'NONRECTANGULAR';
1679  break;
1680  default:
1681  $container = 'VARIABLE';
1682  }
1683  $shippingMethod = $request->getShippingMethod();
1684  list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode());
1685 
1686  // the wrap node needs for remove xml declaration above
1687  $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']);
1688  $method = '';
1689  $service = $this->getCode('service_to_code', $shippingMethod);
1690  if ($service == 'Priority') {
1691  $method = 'Priority';
1692  $rootNode = 'PriorityMailIntlRequest';
1693  $xml = $xmlWrap->addChild($rootNode);
1694  } else {
1695  if ($service == 'First Class') {
1696  $method = 'FirstClass';
1697  $rootNode = 'FirstClassMailIntlRequest';
1698  $xml = $xmlWrap->addChild($rootNode);
1699  } else {
1700  $method = 'Express';
1701  $rootNode = 'ExpressMailIntlRequest';
1702  $xml = $xmlWrap->addChild($rootNode);
1703  }
1704  }
1705 
1706  $xml->addAttribute('USERID', $this->getConfigData('userid'));
1707  $xml->addAttribute('PASSWORD', $this->getConfigData('password'));
1708  $xml->addChild('Option');
1709  $xml->addChild('Revision', self::DEFAULT_REVISION);
1710  $xml->addChild('ImageParameters');
1711  $xml->addChild('FromFirstName', $request->getShipperContactPersonFirstName());
1712  $xml->addChild('FromLastName', $request->getShipperContactPersonLastName());
1713  $xml->addChild('FromFirm', $request->getShipperContactCompanyName());
1714  $xml->addChild('FromAddress1', $request->getShipperAddressStreet2());
1715  $xml->addChild('FromAddress2', $request->getShipperAddressStreet1());
1716  $xml->addChild('FromCity', $request->getShipperAddressCity());
1717  $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode());
1718  $xml->addChild('FromZip5', $fromZip5);
1719  $xml->addChild('FromZip4', $fromZip4);
1720  $xml->addChild('FromPhone', $request->getShipperContactPhoneNumber());
1721  if ($method != 'FirstClass') {
1722  if ($request->getReferenceData()) {
1723  $referenceData = $request->getReferenceData() . ' P' . $request->getPackageId();
1724  } else {
1725  $referenceData = $request->getOrderShipment()->getOrder()->getIncrementId() .
1726  ' P' .
1727  $request->getPackageId();
1728  }
1729  $xml->addChild('FromCustomsReference', 'Order #' . $referenceData);
1730  }
1731  $xml->addChild('ToFirstName', $request->getRecipientContactPersonFirstName());
1732  $xml->addChild('ToLastName', $request->getRecipientContactPersonLastName());
1733  $xml->addChild('ToFirm', $request->getRecipientContactCompanyName());
1734  $xml->addChild('ToAddress1', $request->getRecipientAddressStreet1());
1735  $xml->addChild('ToAddress2', $request->getRecipientAddressStreet2());
1736  $xml->addChild('ToCity', $request->getRecipientAddressCity());
1737  $xml->addChild('ToProvince', $request->getRecipientAddressStateOrProvinceCode());
1738  $xml->addChild('ToCountry', $this->_getCountryName($request->getRecipientAddressCountryCode()));
1739  $xml->addChild('ToPostalCode', $request->getRecipientAddressPostalCode());
1740  $xml->addChild('ToPOBoxFlag', 'N');
1741  $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber());
1742  $xml->addChild('ToFax');
1743  $xml->addChild('ToEmail');
1744  if ($method != 'FirstClass') {
1745  $xml->addChild('NonDeliveryOption', 'Return');
1746  }
1747  if ($method == 'FirstClass') {
1748  if (stripos($shippingMethod, 'Letter') !== false) {
1749  $xml->addChild('FirstClassMailType', 'LETTER');
1750  } else {
1751  if (stripos($shippingMethod, 'Flat') !== false) {
1752  $xml->addChild('FirstClassMailType', 'FLAT');
1753  } else {
1754  $xml->addChild('FirstClassMailType', 'PARCEL');
1755  }
1756  }
1757  }
1758  if ($method != 'FirstClass') {
1759  $xml->addChild('Container', $container);
1760  }
1761  $shippingContents = $xml->addChild('ShippingContents');
1762  $packageItems = $request->getPackageItems();
1763  // get countries of manufacture
1764  $countriesOfManufacture = [];
1765  $productIds = [];
1766  foreach ($packageItems as $itemShipment) {
1767  $item = new \Magento\Framework\DataObject();
1768  $item->setData($itemShipment);
1769 
1770  $productIds[] = $item->getProductId();
1771  }
1772  $productCollection = $this->_productCollectionFactory->create()->addStoreFilter(
1773  $request->getStoreId()
1774  )->addFieldToFilter(
1775  'entity_id',
1776  ['in' => $productIds]
1777  )->addAttributeToSelect(
1778  'country_of_manufacture'
1779  );
1780  foreach ($productCollection as $product) {
1781  $countriesOfManufacture[$product->getId()] = $product->getCountryOfManufacture();
1782  }
1783 
1784  $packagePoundsWeight = $packageOuncesWeight = 0;
1785  // for ItemDetail
1786  foreach ($packageItems as $itemShipment) {
1787  $item = new \Magento\Framework\DataObject();
1788  $item->setData($itemShipment);
1789 
1790  $itemWeight = $item->getWeight() * $item->getQty();
1791  if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) {
1792  $itemWeight = $this->_carrierHelper->convertMeasureWeight(
1793  $itemWeight,
1794  $packageParams->getWeightUnits(),
1796  );
1797  }
1798  if (!empty($countriesOfManufacture[$item->getProductId()])) {
1799  $countryOfManufacture = $this->_getCountryName($countriesOfManufacture[$item->getProductId()]);
1800  } else {
1801  $countryOfManufacture = '';
1802  }
1803  $itemDetail = $shippingContents->addChild('ItemDetail');
1804  $itemDetail->addChild('Description', $item->getName());
1805  $ceiledQty = ceil($item->getQty());
1806  if ($ceiledQty < 1) {
1807  $ceiledQty = 1;
1808  }
1809  $individualItemWeight = $itemWeight / $ceiledQty;
1810  $itemDetail->addChild('Quantity', $ceiledQty);
1811  $itemDetail->addChild('Value', sprintf('%.2F', $item->getCustomsValue() * $item->getQty()));
1812  list($individualPoundsWeight, $individualOuncesWeight) = $this->_convertPoundOunces($individualItemWeight);
1813  $itemDetail->addChild('NetPounds', $individualPoundsWeight);
1814  $itemDetail->addChild('NetOunces', sprintf('%.2F', $individualOuncesWeight));
1815  $itemDetail->addChild('HSTariffNumber', 0);
1816  $itemDetail->addChild('CountryOfOrigin', $countryOfManufacture);
1817 
1818  list($itemPoundsWeight, $itemOuncesWeight) = $this->_convertPoundOunces($itemWeight);
1819  $packagePoundsWeight += $itemPoundsWeight;
1820  $packageOuncesWeight += $itemOuncesWeight;
1821  }
1822  $additionalPackagePoundsWeight = floor($packageOuncesWeight / self::OUNCES_POUND);
1823  $packagePoundsWeight += $additionalPackagePoundsWeight;
1824  $packageOuncesWeight -= $additionalPackagePoundsWeight * self::OUNCES_POUND;
1825  if ($packagePoundsWeight + $packageOuncesWeight / self::OUNCES_POUND < $packageWeight) {
1826  list($packagePoundsWeight, $packageOuncesWeight) = $this->_convertPoundOunces($packageWeight);
1827  }
1828 
1829  $xml->addChild('GrossPounds', $packagePoundsWeight);
1830  $xml->addChild('GrossOunces', $packageOuncesWeight);
1831  if ($packageParams->getContentType() == 'OTHER' && $packageParams->getContentTypeOther() != null) {
1832  $xml->addChild('ContentType', $packageParams->getContentType());
1833  $xml->addChild('ContentTypeOther ', $packageParams->getContentTypeOther());
1834  } else {
1835  $xml->addChild('ContentType', $packageParams->getContentType());
1836  }
1837 
1838  $xml->addChild('Agreement', 'y');
1839  $xml->addChild('ImageType', 'PDF');
1840  $xml->addChild('ImageLayout', 'ALLINONEFILE');
1841  if ($method == 'FirstClass') {
1842  $xml->addChild('Container', $container);
1843  }
1844  // set size
1845  if ($packageParams->getSize()) {
1846  $xml->addChild('Size', $packageParams->getSize());
1847  }
1848  // set dimensions
1849  $xml->addChild('Length', $length);
1850  $xml->addChild('Width', $width);
1851  $xml->addChild('Height', $height);
1852  if ($girth) {
1853  $xml->addChild('Girth', $girth);
1854  }
1855 
1856  $xml = $xmlWrap->{$rootNode}->asXML();
1857 
1858  return $xml;
1859  }
getCode($type, $code='')
Definition: Carrier.php:649
_getCountryName($countryId)
Definition: Carrier.php:1176
_convertPoundOunces($weightInPounds)
Definition: Carrier.php:1593
$method
Definition: info.phtml:13
_parseZip($zipString, $returnFull=false)
Definition: Carrier.php:2049
$shippingMethod
Definition: popup.phtml:12

◆ _formUsExpressShipmentRequest()

_formUsExpressShipmentRequest ( \Magento\Framework\DataObject  $request)
protected

Form XML for US shipment request As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName> must be after <FromFirstName>

Parameters
\Magento\Framework\DataObject$request
Returns
string
Deprecated:
100.2.1 This method should not be used anymore.
See also
\Magento\Usps\Model\Carrier::_doShipmentRequest method doc block.

Definition at line 1438 of file Carrier.php.

1439  {
1440  $packageParams = $request->getPackageParams();
1441 
1442  $packageWeight = $request->getPackageWeight();
1443  if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::OUNCE) {
1444  $packageWeight = round(
1445  $this->_carrierHelper->convertMeasureWeight(
1446  (float)$request->getPackageWeight(),
1447  $packageParams->getWeightUnits(),
1449  )
1450  );
1451  }
1452 
1453  list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode());
1454  list($toZip5, $toZip4) = $this->_parseZip($request->getRecipientAddressPostalCode(), true);
1455 
1456  $rootNode = 'ExpressMailLabelRequest';
1457  // the wrap node needs for remove xml declaration above
1458  $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']);
1459  $xml = $xmlWrap->addChild($rootNode);
1460  $xml->addAttribute('USERID', $this->getConfigData('userid'));
1461  $xml->addAttribute('PASSWORD', $this->getConfigData('password'));
1462  $xml->addChild('Option');
1463  $xml->addChild('Revision');
1464  $xml->addChild('EMCAAccount');
1465  $xml->addChild('EMCAPassword');
1466  $xml->addChild('ImageParameters');
1467  $xml->addChild('FromFirstName', $request->getShipperContactPersonFirstName());
1468  $xml->addChild('FromLastName', $request->getShipperContactPersonLastName());
1469  $xml->addChild('FromFirm', $request->getShipperContactCompanyName());
1470  $xml->addChild('FromAddress1', $request->getShipperAddressStreet2());
1471  $xml->addChild('FromAddress2', $request->getShipperAddressStreet1());
1472  $xml->addChild('FromCity', $request->getShipperAddressCity());
1473  $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode());
1474  $xml->addChild('FromZip5', $fromZip5);
1475  $xml->addChild('FromZip4', $fromZip4);
1476  $xml->addChild('FromPhone', $request->getShipperContactPhoneNumber());
1477  $xml->addChild('ToFirstName', $request->getRecipientContactPersonFirstName());
1478  $xml->addChild('ToLastName', $request->getRecipientContactPersonLastName());
1479  $xml->addChild('ToFirm', $request->getRecipientContactCompanyName());
1480  $xml->addChild('ToAddress1', $request->getRecipientAddressStreet2());
1481  $xml->addChild('ToAddress2', $request->getRecipientAddressStreet1());
1482  $xml->addChild('ToCity', $request->getRecipientAddressCity());
1483  $xml->addChild('ToState', $request->getRecipientAddressStateOrProvinceCode());
1484  $xml->addChild('ToZip5', $toZip5);
1485  $xml->addChild('ToZip4', $toZip4);
1486  $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber());
1487  $xml->addChild('WeightInOunces', $packageWeight);
1488  $xml->addChild('WaiverOfSignature', $packageParams->getDeliveryConfirmation());
1489  $xml->addChild('POZipCode');
1490  $xml->addChild('ImageType', 'PDF');
1491 
1492  $xml = $xmlWrap->{$rootNode}->asXML();
1493 
1494  return $xml;
1495  }
_parseZip($zipString, $returnFull=false)
Definition: Carrier.php:2049

◆ _formUsSignatureConfirmationShipmentRequest()

_formUsSignatureConfirmationShipmentRequest ( \Magento\Framework\DataObject  $request,
  $serviceType 
)
protected

Form XML for US Signature Confirmation request As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName> must be after <FromFirstName>

Parameters
\Magento\Framework\DataObject$request
string$serviceType
Returns
string
Exceptions

Definition at line 1508 of file Carrier.php.

1509  {
1510  switch ($serviceType) {
1511  case 'PRIORITY':
1512  case 'Priority':
1513  $serviceType = 'Priority';
1514  break;
1515  case 'FIRST CLASS':
1516  case 'First Class':
1517  $serviceType = 'First Class';
1518  break;
1519  case 'STANDARD':
1520  case 'Standard Post':
1521  case 'Retail Ground':
1522  $serviceType = 'Retail Ground';
1523  break;
1524  case 'MEDIA':
1525  case 'Media':
1526  $serviceType = 'Media Mail';
1527  break;
1528  case 'LIBRARY':
1529  case 'Library':
1530  $serviceType = 'Library Mail';
1531  break;
1532  default:
1533  throw new \Exception(__('Service type does not match'));
1534  }
1535  $packageParams = $request->getPackageParams();
1536  $packageWeight = $request->getPackageWeight();
1537  if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::OUNCE) {
1538  $packageWeight = round(
1539  $this->_carrierHelper->convertMeasureWeight(
1540  (float)$request->getPackageWeight(),
1541  $packageParams->getWeightUnits(),
1543  )
1544  );
1545  }
1546 
1547  list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode());
1548  list($toZip5, $toZip4) = $this->_parseZip($request->getRecipientAddressPostalCode(), true);
1549 
1550  if ($this->getConfigData('mode')) {
1551  $rootNode = 'SignatureConfirmationV3.0Request';
1552  } else {
1553  $rootNode = 'SigConfirmCertifyV3.0Request';
1554  }
1555  // the wrap node needs for remove xml declaration above
1556  $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']);
1557  $xml = $xmlWrap->addChild($rootNode);
1558  $xml->addAttribute('USERID', $this->getConfigData('userid'));
1559  $xml->addChild('Option', 1);
1560  $xml->addChild('ImageParameters');
1561  $xml->addChild('FromName', $request->getShipperContactPersonName());
1562  $xml->addChild('FromFirm', $request->getShipperContactCompanyName());
1563  $xml->addChild('FromAddress1', $request->getShipperAddressStreet2());
1564  $xml->addChild('FromAddress2', $request->getShipperAddressStreet1());
1565  $xml->addChild('FromCity', $request->getShipperAddressCity());
1566  $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode());
1567  $xml->addChild('FromZip5', $fromZip5);
1568  $xml->addChild('FromZip4', $fromZip4);
1569  $xml->addChild('ToName', $request->getRecipientContactPersonName());
1570  $xml->addChild('ToFirm', $request->getRecipientContactCompanyName());
1571  $xml->addChild('ToAddress1', $request->getRecipientAddressStreet2());
1572  $xml->addChild('ToAddress2', $request->getRecipientAddressStreet1());
1573  $xml->addChild('ToCity', $request->getRecipientAddressCity());
1574  $xml->addChild('ToState', $request->getRecipientAddressStateOrProvinceCode());
1575  $xml->addChild('ToZip5', $toZip5);
1576  $xml->addChild('ToZip4', $toZip4);
1577  $xml->addChild('WeightInOunces', $packageWeight);
1578  $xml->addChild('ServiceType', $serviceType);
1579  $xml->addChild('WaiverOfSignature', $packageParams->getDeliveryConfirmation());
1580  $xml->addChild('ImageType', 'PDF');
1581 
1582  $xml = $xmlWrap->{$rootNode}->asXML();
1583 
1584  return $xml;
1585  }
__()
Definition: __.php:13
_parseZip($zipString, $returnFull=false)
Definition: Carrier.php:2049

◆ _getCountryName()

_getCountryName (   $countryId)
protected

Return USPS county name by country ISO 3166-1-alpha-2 code Return false for unknown countries

Parameters
string$countryId
Returns
string|false @SuppressWarnings(PHPMD.ExcessiveMethodLength)

Definition at line 1176 of file Carrier.php.

1177  {
1178  $countries = [
1179  'AD' => 'Andorra',
1180  'AE' => 'United Arab Emirates',
1181  'AF' => 'Afghanistan',
1182  'AG' => 'Antigua and Barbuda',
1183  'AI' => 'Anguilla',
1184  'AL' => 'Albania',
1185  'AM' => 'Armenia',
1186  'AN' => 'Netherlands Antilles',
1187  'AO' => 'Angola',
1188  'AR' => 'Argentina',
1189  'AT' => 'Austria',
1190  'AU' => 'Australia',
1191  'AW' => 'Aruba',
1192  'AX' => 'Aland Island (Finland)',
1193  'AZ' => 'Azerbaijan',
1194  'BA' => 'Bosnia-Herzegovina',
1195  'BB' => 'Barbados',
1196  'BD' => 'Bangladesh',
1197  'BE' => 'Belgium',
1198  'BF' => 'Burkina Faso',
1199  'BG' => 'Bulgaria',
1200  'BH' => 'Bahrain',
1201  'BI' => 'Burundi',
1202  'BJ' => 'Benin',
1203  'BM' => 'Bermuda',
1204  'BN' => 'Brunei Darussalam',
1205  'BO' => 'Bolivia',
1206  'BR' => 'Brazil',
1207  'BS' => 'Bahamas',
1208  'BT' => 'Bhutan',
1209  'BW' => 'Botswana',
1210  'BY' => 'Belarus',
1211  'BZ' => 'Belize',
1212  'CA' => 'Canada',
1213  'CC' => 'Cocos Island (Australia)',
1214  'CD' => 'Congo, Democratic Republic of the',
1215  'CF' => 'Central African Republic',
1216  'CG' => 'Congo, Republic of the',
1217  'CH' => 'Switzerland',
1218  'CI' => 'Ivory Coast (Cote d Ivoire)',
1219  'CK' => 'Cook Islands (New Zealand)',
1220  'CL' => 'Chile',
1221  'CM' => 'Cameroon',
1222  'CN' => 'China',
1223  'CO' => 'Colombia',
1224  'CR' => 'Costa Rica',
1225  'CU' => 'Cuba',
1226  'CV' => 'Cape Verde',
1227  'CX' => 'Christmas Island (Australia)',
1228  'CY' => 'Cyprus',
1229  'CZ' => 'Czech Republic',
1230  'DE' => 'Germany',
1231  'DJ' => 'Djibouti',
1232  'DK' => 'Denmark',
1233  'DM' => 'Dominica',
1234  'DO' => 'Dominican Republic',
1235  'DZ' => 'Algeria',
1236  'EC' => 'Ecuador',
1237  'EE' => 'Estonia',
1238  'EG' => 'Egypt',
1239  'ER' => 'Eritrea',
1240  'ES' => 'Spain',
1241  'ET' => 'Ethiopia',
1242  'FI' => 'Finland',
1243  'FJ' => 'Fiji',
1244  'FK' => 'Falkland Islands',
1245  'FM' => 'Micronesia, Federated States of',
1246  'FO' => 'Faroe Islands',
1247  'FR' => 'France',
1248  'GA' => 'Gabon',
1249  'GB' => 'Great Britain and Northern Ireland',
1250  'GD' => 'Grenada',
1251  'GE' => 'Georgia, Republic of',
1252  'GF' => 'French Guiana',
1253  'GH' => 'Ghana',
1254  'GI' => 'Gibraltar',
1255  'GL' => 'Greenland',
1256  'GM' => 'Gambia',
1257  'GN' => 'Guinea',
1258  'GP' => 'Guadeloupe',
1259  'GQ' => 'Equatorial Guinea',
1260  'GR' => 'Greece',
1261  'GS' => 'South Georgia (Falkland Islands)',
1262  'GT' => 'Guatemala',
1263  'GW' => 'Guinea-Bissau',
1264  'GY' => 'Guyana',
1265  'HK' => 'Hong Kong',
1266  'HN' => 'Honduras',
1267  'HR' => 'Croatia',
1268  'HT' => 'Haiti',
1269  'HU' => 'Hungary',
1270  'ID' => 'Indonesia',
1271  'IE' => 'Ireland',
1272  'IL' => 'Israel',
1273  'IN' => 'India',
1274  'IQ' => 'Iraq',
1275  'IR' => 'Iran',
1276  'IS' => 'Iceland',
1277  'IT' => 'Italy',
1278  'JM' => 'Jamaica',
1279  'JO' => 'Jordan',
1280  'JP' => 'Japan',
1281  'KE' => 'Kenya',
1282  'KG' => 'Kyrgyzstan',
1283  'KH' => 'Cambodia',
1284  'KI' => 'Kiribati',
1285  'KM' => 'Comoros',
1286  'KN' => 'Saint Kitts (Saint Christopher and Nevis)',
1287  'KP' => 'North Korea (Korea, Democratic People\'s Republic of)',
1288  'KR' => 'South Korea (Korea, Republic of)',
1289  'KW' => 'Kuwait',
1290  'KY' => 'Cayman Islands',
1291  'KZ' => 'Kazakhstan',
1292  'LA' => 'Laos',
1293  'LB' => 'Lebanon',
1294  'LC' => 'Saint Lucia',
1295  'LI' => 'Liechtenstein',
1296  'LK' => 'Sri Lanka',
1297  'LR' => 'Liberia',
1298  'LS' => 'Lesotho',
1299  'LT' => 'Lithuania',
1300  'LU' => 'Luxembourg',
1301  'LV' => 'Latvia',
1302  'LY' => 'Libya',
1303  'MA' => 'Morocco',
1304  'MC' => 'Monaco (France)',
1305  'MD' => 'Moldova',
1306  'MG' => 'Madagascar',
1307  'MK' => 'Macedonia, Republic of',
1308  'ML' => 'Mali',
1309  'MM' => 'Burma',
1310  'MN' => 'Mongolia',
1311  'MO' => 'Macao',
1312  'MQ' => 'Martinique',
1313  'MR' => 'Mauritania',
1314  'MS' => 'Montserrat',
1315  'MT' => 'Malta',
1316  'MU' => 'Mauritius',
1317  'MV' => 'Maldives',
1318  'MW' => 'Malawi',
1319  'MX' => 'Mexico',
1320  'MY' => 'Malaysia',
1321  'MZ' => 'Mozambique',
1322  'NA' => 'Namibia',
1323  'NC' => 'New Caledonia',
1324  'NE' => 'Niger',
1325  'NG' => 'Nigeria',
1326  'NI' => 'Nicaragua',
1327  'NL' => 'Netherlands',
1328  'NO' => 'Norway',
1329  'NP' => 'Nepal',
1330  'NR' => 'Nauru',
1331  'NZ' => 'New Zealand',
1332  'OM' => 'Oman',
1333  'PA' => 'Panama',
1334  'PE' => 'Peru',
1335  'PF' => 'French Polynesia',
1336  'PG' => 'Papua New Guinea',
1337  'PH' => 'Philippines',
1338  'PK' => 'Pakistan',
1339  'PL' => 'Poland',
1340  'PM' => 'Saint Pierre and Miquelon',
1341  'PN' => 'Pitcairn Island',
1342  'PT' => 'Portugal',
1343  'PY' => 'Paraguay',
1344  'QA' => 'Qatar',
1345  'RE' => 'Reunion',
1346  'RO' => 'Romania',
1347  'RS' => 'Serbia',
1348  'RU' => 'Russia',
1349  'RW' => 'Rwanda',
1350  'SA' => 'Saudi Arabia',
1351  'SB' => 'Solomon Islands',
1352  'SC' => 'Seychelles',
1353  'SD' => 'Sudan',
1354  'SE' => 'Sweden',
1355  'SG' => 'Singapore',
1356  'SH' => 'Saint Helena',
1357  'SI' => 'Slovenia',
1358  'SK' => 'Slovak Republic',
1359  'SL' => 'Sierra Leone',
1360  'SM' => 'San Marino',
1361  'SN' => 'Senegal',
1362  'SO' => 'Somalia',
1363  'SR' => 'Suriname',
1364  'ST' => 'Sao Tome and Principe',
1365  'SV' => 'El Salvador',
1366  'SY' => 'Syrian Arab Republic',
1367  'SZ' => 'Swaziland',
1368  'TC' => 'Turks and Caicos Islands',
1369  'TD' => 'Chad',
1370  'TG' => 'Togo',
1371  'TH' => 'Thailand',
1372  'TJ' => 'Tajikistan',
1373  'TK' => 'Tokelau (Union Group) (Western Samoa)',
1374  'TL' => 'East Timor (Timor-Leste, Democratic Republic of)',
1375  'TM' => 'Turkmenistan',
1376  'TN' => 'Tunisia',
1377  'TO' => 'Tonga',
1378  'TR' => 'Turkey',
1379  'TT' => 'Trinidad and Tobago',
1380  'TV' => 'Tuvalu',
1381  'TW' => 'Taiwan',
1382  'TZ' => 'Tanzania',
1383  'UA' => 'Ukraine',
1384  'UG' => 'Uganda',
1385  'UY' => 'Uruguay',
1386  'UZ' => 'Uzbekistan',
1387  'VA' => 'Vatican City',
1388  'VC' => 'Saint Vincent and the Grenadines',
1389  'VE' => 'Venezuela',
1390  'VG' => 'British Virgin Islands',
1391  'VN' => 'Vietnam',
1392  'VU' => 'Vanuatu',
1393  'WF' => 'Wallis and Futuna Islands',
1394  'WS' => 'Western Samoa',
1395  'YE' => 'Yemen',
1396  'YT' => 'Mayotte (France)',
1397  'ZA' => 'South Africa',
1398  'ZM' => 'Zambia',
1399  'ZW' => 'Zimbabwe',
1400  'US' => 'United States',
1401  ];
1402 
1403  if (isset($countries[$countryId])) {
1404  return $countries[$countryId];
1405  }
1406 
1407  return false;
1408  }

◆ _getQuotes()

_getQuotes ( )
protected

Get quotes

Returns
Result

Definition at line 381 of file Carrier.php.

382  {
383  return $this->_getXmlQuotes();
384  }

◆ _getXmlQuotes()

_getXmlQuotes ( )
protected

Build RateV3 request, send it to USPS gateway and retrieve quotes in XML format

Result (PHPMD.CyclomaticComplexity) (PHPMD.NPathComplexity) (PHPMD.ExcessiveMethodLength)

Definition at line 412 of file Carrier.php.

413  {
414  $r = $this->_rawRequest;
415 
416  // The origin address(shipper) must be only in USA
417  if (!$this->_isUSCountry($r->getOrigCountryId())) {
418  $responseBody = '';
419 
420  return $this->_parseXmlResponse($responseBody);
421  }
422 
423  if ($this->_isUSCountry($r->getDestCountryId())) {
424  $xml = $this->_xmlElFactory->create(
425  ['data' => '<?xml version="1.0" encoding="UTF-8"?><RateV4Request/>']
426  );
427  $xml->addAttribute('USERID', $r->getUserId());
428  // according to usps v4 documentation
429  $xml->addChild('Revision', '2');
430 
431  $package = $xml->addChild('Package');
432  $package->addAttribute('ID', 0);
433  $service = $this->getCode('service_to_code', $r->getService());
434  if (!$service) {
435  $service = $r->getService();
436  }
437 
438  if (strpos($r->getContainer(), 'FLAT RATE ENVELOPE') !== false ||
439  strpos($r->getContainer(), 'FLAT RATE BOX') !== false
440  ) {
441  $service = 'Priority';
442  }
443 
444  $package->addChild('Service', $service);
445 
446  // no matter Letter, Flat or Parcel, use Parcel
447  if ($r->getService() == 'FIRST CLASS' || $r->getService() == 'FIRST CLASS HFP COMMERCIAL') {
448  $package->addChild('FirstClassMailType', 'PARCEL');
449  }
450  $package->addChild('ZipOrigination', $r->getOrigPostal());
451  //only 5 chars avaialble
452  $package->addChild('ZipDestination', substr($r->getDestPostal(), 0, 5));
453  $package->addChild('Pounds', $r->getWeightPounds());
454  $package->addChild('Ounces', $r->getWeightOunces());
455  // Because some methods don't accept VARIABLE and (NON)RECTANGULAR containers
456  $package->addChild('Container', $r->getContainer());
457  $package->addChild('Size', $r->getSize());
458  if ($r->getSize() == 'LARGE') {
459  $package->addChild('Width', $r->getWidth());
460  $package->addChild('Length', $r->getLength());
461  $package->addChild('Height', $r->getHeight());
462  if ($r->getContainer() == 'NONRECTANGULAR' || $r->getContainer() == 'VARIABLE') {
463  $package->addChild('Girth', $r->getGirth());
464  }
465  }
466  $package->addChild('Machinable', $r->getMachinable());
467 
468  $api = 'RateV4';
469  } else {
470  $xml = $this->_xmlElFactory->create(
471  ['data' => '<?xml version = "1.0" encoding = "UTF-8"?><IntlRateV2Request/>']
472  );
473  $xml->addAttribute('USERID', $r->getUserId());
474  // according to usps v4 documentation
475  $xml->addChild('Revision', '2');
476 
477  $package = $xml->addChild('Package');
478  $package->addAttribute('ID', 0);
479  $package->addChild('Pounds', $r->getWeightPounds());
480  $package->addChild('Ounces', $r->getWeightOunces());
481  $package->addChild('MailType', 'All');
482  $package->addChild('ValueOfContents', $r->getValue());
483  $package->addChild('Country', $r->getDestCountryName());
484  $package->addChild('Container', $r->getContainer());
485  $package->addChild('Size', $r->getSize());
486  $width = $length = $height = $girth = '';
487  if ($r->getSize() == 'LARGE') {
488  $width = $r->getWidth();
489  $length = $r->getLength();
490  $height = $r->getHeight();
491  if ($r->getContainer() == 'NONRECTANGULAR') {
492  $girth = $r->getGirth();
493  }
494  }
495  $package->addChild('Width', $width);
496  $package->addChild('Length', $length);
497  $package->addChild('Height', $height);
498  $package->addChild('Girth', $girth);
499 
500  $package->addChild('OriginZip', $r->getOrigPostal());
501  $package->addChild('AcceptanceDateTime', date('c'));
502  $package->addChild('DestinationPostalCode', $r->getDestPostal());
503 
504  $api = 'IntlRateV2';
505  }
506  $request = $xml->asXML();
507 
508  $responseBody = $this->_getCachedQuotes($request);
509  if ($responseBody === null) {
510  $debugData = ['request' => $this->filterDebugData($request)];
511  try {
512  $url = $this->getConfigData('gateway_url');
513  if (!$url) {
515  }
516  $client = $this->_httpClientFactory->create();
517  $client->setUri($url);
518  $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
519  $client->setParameterGet('API', $api);
520  $client->setParameterGet('XML', $request);
521  $response = $client->request();
522  $responseBody = $response->getBody();
523 
524  $debugData['result'] = $responseBody;
525  $this->_setCachedQuotes($request, $responseBody);
526  } catch (\Exception $e) {
527  $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
528  $responseBody = '';
529  }
530  $this->_debug($debugData);
531  }
532 
533  return $this->_parseXmlResponse($responseBody);
534  }
$response
Definition: 404.php:11
_parseXmlResponse($response)
Definition: Carrier.php:545
getCode($type, $code='')
Definition: Carrier.php:649

◆ _getXmlTracking()

_getXmlTracking (   $trackings)
protected

Send request for tracking

Parameters
string[]$trackings
Returns
void

Definition at line 1024 of file Carrier.php.

1025  {
1026  $r = $this->_rawTrackRequest;
1027 
1028  foreach ($trackings as $tracking) {
1029  $xml = $this->_xmlElFactory->create(
1030  ['data' => '<?xml version = "1.0" encoding = "UTF-8"?><TrackRequest/>']
1031  );
1032  $xml->addAttribute('USERID', $r->getUserId());
1033 
1034  $trackid = $xml->addChild('TrackID');
1035  $trackid->addAttribute('ID', $tracking);
1036 
1037  $api = 'TrackV2';
1038  $request = $xml->asXML();
1039  $debugData = ['request' => $this->filterDebugData($request)];
1040 
1041  try {
1042  $url = $this->getConfigData('gateway_url');
1043  if (!$url) {
1045  }
1046  $client = $this->_httpClientFactory->create();
1047  $client->setUri($url);
1048  $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
1049  $client->setParameterGet('API', $api);
1050  $client->setParameterGet('XML', $request);
1051  $response = $client->request();
1052  $responseBody = $response->getBody();
1053  $debugData['result'] = $responseBody;
1054  } catch (\Exception $e) {
1055  $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
1056  $responseBody = '';
1057  }
1058 
1059  $this->_debug($debugData);
1060  $this->_parseXmlTrackingResponse($tracking, $responseBody);
1061  }
1062  }
$response
Definition: 404.php:11
_parseXmlTrackingResponse($trackingvalue, $response)
Definition: Carrier.php:1073

◆ _parseXmlResponse()

_parseXmlResponse (   $response)
protected

Parse calculated rates

Parameters
string$response
Returns
Result (PHPMD.CyclomaticComplexity) (PHPMD.NPathComplexity)

US Rates

Definition at line 545 of file Carrier.php.

546  {
547  $r = $this->_rawRequest;
548  $costArr = [];
549  $priceArr = [];
550  if (strlen(trim($response)) > 0) {
551  if (strpos(trim($response), '<?xml') === 0) {
552  if (strpos($response, '<?xml version="1.0"?>') !== false) {
553  $response = str_replace(
554  '<?xml version="1.0"?>',
555  '<?xml version="1.0" encoding="ISO-8859-1"?>',
556  $response
557  );
558  }
559  $xml = $this->parseXml($response);
560 
561  if (is_object($xml)) {
562  $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
563  $serviceCodeToActualNameMap = [];
567  if ($this->_isUSCountry($r->getDestCountryId())) {
568  if (is_object($xml->Package) && is_object($xml->Package->Postage)) {
569  foreach ($xml->Package->Postage as $postage) {
570  $serviceName = $this->_filterServiceName((string)$postage->MailService);
571  $_serviceCode = $this->getCode('method_to_code', $serviceName);
572  $serviceCode = $_serviceCode ? $_serviceCode : (string)$postage->attributes()->CLASSID;
573  $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
574  if (in_array($serviceCode, $allowedMethods)) {
575  $costArr[$serviceCode] = (string)$postage->Rate;
576  $priceArr[$serviceCode] = $this->getMethodPrice(
577  (string)$postage->Rate,
578  $serviceCode
579  );
580  }
581  }
582  asort($priceArr);
583  }
584  } else {
585  /*
586  * International Rates
587  */
588  if (is_object($xml->Package) && is_object($xml->Package->Service)) {
589  foreach ($xml->Package->Service as $service) {
590  $serviceName = $this->_filterServiceName((string)$service->SvcDescription);
591  $serviceCode = 'INT_' . (string)$service->attributes()->ID;
592  $serviceCodeToActualNameMap[$serviceCode] = $serviceName;
593  if (!$this->isServiceAvailable($service)) {
594  continue;
595  }
596  if (in_array($serviceCode, $allowedMethods)) {
597  $costArr[$serviceCode] = (string)$service->Postage;
598  $priceArr[$serviceCode] = $this->getMethodPrice(
599  (string)$service->Postage,
600  $serviceCode
601  );
602  }
603  }
604  asort($priceArr);
605  }
606  }
607  }
608  }
609  }
610 
611  $result = $this->_rateFactory->create();
612  if (empty($priceArr)) {
613  $error = $this->_rateErrorFactory->create();
614  $error->setCarrier('usps');
615  $error->setCarrierTitle($this->getConfigData('title'));
616  $error->setErrorMessage($this->getConfigData('specificerrmsg'));
617  $result->append($error);
618  } else {
619  foreach ($priceArr as $method => $price) {
620  $rate = $this->_rateMethodFactory->create();
621  $rate->setCarrier('usps');
622  $rate->setCarrierTitle($this->getConfigData('title'));
623  $rate->setMethod($method);
624  $rate->setMethodTitle(
625  isset(
626  $serviceCodeToActualNameMap[$method]
627  ) ? $serviceCodeToActualNameMap[$method] : $this->getCode(
628  'method',
629  $method
630  )
631  );
632  $rate->setCost($costArr[$method]);
633  $rate->setPrice($price);
634  $result->append($rate);
635  }
636  }
637 
638  return $result;
639  }
$response
Definition: 404.php:11
$price
getCode($type, $code='')
Definition: Carrier.php:649
parseXml($xmlContent, $customSimplexml='SimpleXMLElement')
$method
Definition: info.phtml:13

◆ _parseXmlTrackingResponse()

_parseXmlTrackingResponse (   $trackingvalue,
  $response 
)
protected

Parse xml tracking response

Parameters
string$trackingvalue
string$response
Returns
void @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.UnusedLocalVariable)

Definition at line 1073 of file Carrier.php.

1074  {
1075  $errorTitle = __('For some reason we can\'t retrieve tracking info right now.');
1076  $resultArr = [];
1077  if (strlen(trim($response)) > 0) {
1078  if (strpos(trim($response), '<?xml') === 0) {
1079  $xml = $this->parseXml($response);
1080  if (is_object($xml)) {
1081  if (isset($xml->Number) && isset($xml->Description) && (string)$xml->Description != '') {
1082  $errorTitle = (string)$xml->Description;
1083  } elseif (isset($xml->TrackInfo)
1084  && isset($xml->TrackInfo->Error)
1085  && isset($xml->TrackInfo->Error->Description)
1086  && (string)$xml->TrackInfo->Error->Description != ''
1087  ) {
1088  $errorTitle = (string)$xml->TrackInfo->Error->Description;
1089  } else {
1090  $errorTitle = __(
1091  'Sorry, something went wrong. Please try again or contact us and we\'ll try to help.'
1092  );
1093  }
1094 
1095  if (isset($xml->TrackInfo) && isset($xml->TrackInfo->TrackSummary)) {
1096  $resultArr['tracksummary'] = (string)$xml->TrackInfo->TrackSummary;
1097  }
1098  }
1099  }
1100  }
1101 
1102  if (!$this->_result) {
1103  $this->_result = $this->_trackFactory->create();
1104  }
1105  $defaults = $this->getDefaults();
1106 
1107  if ($resultArr) {
1108  $tracking = $this->_trackStatusFactory->create();
1109  $tracking->setCarrier('usps');
1110  $tracking->setCarrierTitle($this->getConfigData('title'));
1111  $tracking->setTracking($trackingvalue);
1112  $tracking->setTrackSummary($resultArr['tracksummary']);
1113  $this->_result->append($tracking);
1114  } else {
1115  $error = $this->_trackErrorFactory->create();
1116  $error->setCarrier('usps');
1117  $error->setCarrierTitle($this->getConfigData('title'));
1118  $error->setTracking($trackingvalue);
1119  $error->setErrorMessage($errorTitle);
1120  $this->_result->append($error);
1121  }
1122  }
$response
Definition: 404.php:11
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
__()
Definition: __.php:13
parseXml($xmlContent, $customSimplexml='SimpleXMLElement')

◆ _parseZip()

_parseZip (   $zipString,
  $returnFull = false 
)
protected

Parse zip from string to zip5-zip4

Parameters
string$zipString
bool$returnFull
Returns
string[]

Definition at line 2049 of file Carrier.php.

2050  {
2051  $zip4 = '';
2052  $zip5 = '';
2053  $zip = [$zipString];
2054  if (preg_match('/[\\d\\w]{5}\\-[\\d\\w]{4}/', $zipString) != 0) {
2055  $zip = explode('-', $zipString);
2056  }
2057  $count = count($zip);
2058  for ($i = 0; $i < $count; ++$i) {
2059  if (strlen($zip[$i]) == 5) {
2060  $zip5 = $zip[$i];
2061  } elseif (strlen($zip[$i]) == 4) {
2062  $zip4 = $zip[$i];
2063  }
2064  }
2065  if (empty($zip5) && empty($zip4) && $returnFull) {
2066  $zip5 = $zipString;
2067  }
2068 
2069  return [$zip5, $zip4];
2070  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$count
Definition: recent.phtml:13
$i
Definition: gallery.phtml:31

◆ _setFreeMethodRequest()

_setFreeMethodRequest (   $freeMethod)
protected

Set free method request

Parameters
string$freeMethod
Returns
void

Definition at line 392 of file Carrier.php.

393  {
394  $r = $this->_rawRequest;
395 
396  $weight = $this->getTotalNumOfBoxes($r->getFreeMethodWeight());
397  $r->setWeightPounds(floor($weight));
398  $ounces = ($weight - floor($weight)) * self::OUNCES_POUND;
399  $r->setWeightOunces(sprintf('%.' . self::$weightPrecision . 'f', $ounces));
400  $r->setService($freeMethod);
401  }

◆ collectRates()

collectRates ( RateRequest  $request)

Collect and get rates

Parameters
RateRequest$request
Returns
\Magento\Quote\Model\Quote\Address\RateResult\Error|bool|Result

Implements AbstractCarrierInterface.

Definition at line 209 of file Carrier.php.

210  {
211  if (!$this->canCollectRates()) {
212  return $this->getErrorMessage();
213  }
214 
215  $this->setRequest($request);
216  $this->_result = $this->_getQuotes();
218 
219  return $this->getResult();
220  }
setRequest(\Magento\Quote\Model\Quote\Address\RateRequest $request)
Definition: Carrier.php:231

◆ getAllowedMethods()

getAllowedMethods ( )

Get allowed shipping methods

Returns
array

Implements CarrierInterface.

Definition at line 1157 of file Carrier.php.

1158  {
1159  $allowed = explode(',', $this->getConfigData('allowed_methods'));
1160  $arr = [];
1161  foreach ($allowed as $k) {
1162  $arr[$k] = $this->getCode('method', $k);
1163  }
1164 
1165  return $arr;
1166  }
getCode($type, $code='')
Definition: Carrier.php:649

◆ getCode()

getCode (   $type,
  $code = '' 
)

Get configuration data of carrier

Parameters
string$type
string$code
Returns
array|false @SuppressWarnings(PHPMD.ExcessiveMethodLength)

Definition at line 649 of file Carrier.php.

650  {
651  $codes = [
652  'method' => [
653  '0_FCLE' => __('First-Class Mail Large Envelope'),
654  '0_FCL' => __('First-Class Mail Letter'),
655  '0_FCP' => __('First-Class Package Service - Retail'),
656  '0_FCPC' => __('First-Class Mail Postcards'),
657  '1' => __('Priority Mail'),
658  '2' => __('Priority Mail Express Hold For Pickup'),
659  '3' => __('Priority Mail Express'),
660  '4' => __('Retail Ground'),
661  '6' => __('Media Mail'),
662  '7' => __('Library Mail'),
663  '13' => __('Priority Mail Express Flat Rate Envelope'),
664  '15' => __('First-Class Mail Large Postcards'),
665  '16' => __('Priority Mail Flat Rate Envelope'),
666  '17' => __('Priority Mail Medium Flat Rate Box'),
667  '22' => __('Priority Mail Large Flat Rate Box'),
668  '23' => __('Priority Mail Express Sunday/Holiday Delivery'),
669  '25' => __('Priority Mail Express Sunday/Holiday Delivery Flat Rate Envelope'),
670  '27' => __('Priority Mail Express Flat Rate Envelope Hold For Pickup'),
671  '28' => __('Priority Mail Small Flat Rate Box'),
672  '29' => __('Priority Mail Padded Flat Rate Envelope'),
673  '30' => __('Priority Mail Express Legal Flat Rate Envelope'),
674  '31' => __('Priority Mail Express Legal Flat Rate Envelope Hold For Pickup'),
675  '32' => __('Priority Mail Express Sunday/Holiday Delivery Legal Flat Rate Envelope'),
676  '33' => __('Priority Mail Hold For Pickup'),
677  '34' => __('Priority Mail Large Flat Rate Box Hold For Pickup'),
678  '35' => __('Priority Mail Medium Flat Rate Box Hold For Pickup'),
679  '36' => __('Priority Mail Small Flat Rate Box Hold For Pickup'),
680  '37' => __('Priority Mail Flat Rate Envelope Hold For Pickup'),
681  '38' => __('Priority Mail Gift Card Flat Rate Envelope'),
682  '39' => __('Priority Mail Gift Card Flat Rate Envelope Hold For Pickup'),
683  '40' => __('Priority Mail Window Flat Rate Envelope'),
684  '41' => __('Priority Mail Window Flat Rate Envelope Hold For Pickup'),
685  '42' => __('Priority Mail Small Flat Rate Envelope'),
686  '43' => __('Priority Mail Small Flat Rate Envelope Hold For Pickup'),
687  '44' => __('Priority Mail Legal Flat Rate Envelope'),
688  '45' => __('Priority Mail Legal Flat Rate Envelope Hold For Pickup'),
689  '46' => __('Priority Mail Padded Flat Rate Envelope Hold For Pickup'),
690  '47' => __('Priority Mail Regional Rate Box A'),
691  '48' => __('Priority Mail Regional Rate Box A Hold For Pickup'),
692  '49' => __('Priority Mail Regional Rate Box B'),
693  '50' => __('Priority Mail Regional Rate Box B Hold For Pickup'),
694  '53' => __('First-Class Package Service Hold For Pickup'),
695  '57' => __('Priority Mail Express Sunday/Holiday Delivery Flat Rate Boxes'),
696  '58' => __('Priority Mail Regional Rate Box C'),
697  '59' => __('Priority Mail Regional Rate Box C Hold For Pickup'),
698  '61' => __('First-Class Package Service'),
699  '62' => __('Priority Mail Express Padded Flat Rate Envelope'),
700  '63' => __('Priority Mail Express Padded Flat Rate Envelope Hold For Pickup'),
701  '64' => __('Priority Mail Express Sunday/Holiday Delivery Padded Flat Rate Envelope'),
702  'INT_1' => __('Priority Mail Express International'),
703  'INT_2' => __('Priority Mail International'),
704  'INT_4' => __('Global Express Guaranteed (GXG)'),
705  'INT_5' => __('Global Express Guaranteed Document'),
706  'INT_6' => __('Global Express Guaranteed Non-Document Rectangular'),
707  'INT_7' => __('Global Express Guaranteed Non-Document Non-Rectangular'),
708  'INT_8' => __('Priority Mail International Flat Rate Envelope'),
709  'INT_9' => __('Priority Mail International Medium Flat Rate Box'),
710  'INT_10' => __('Priority Mail Express International Flat Rate Envelope'),
711  'INT_11' => __('Priority Mail International Large Flat Rate Box'),
712  'INT_12' => __('USPS GXG Envelopes'),
713  'INT_13' => __('First-Class Mail International Letter'),
714  'INT_14' => __('First-Class Mail International Large Envelope'),
715  'INT_15' => __('First-Class Package International Service'),
716  'INT_16' => __('Priority Mail International Small Flat Rate Box'),
717  'INT_17' => __('Priority Mail Express International Legal Flat Rate Envelope'),
718  'INT_18' => __('Priority Mail International Gift Card Flat Rate Envelope'),
719  'INT_19' => __('Priority Mail International Window Flat Rate Envelope'),
720  'INT_20' => __('Priority Mail International Small Flat Rate Envelope'),
721  'INT_21' => __('First-Class Mail International Postcard'),
722  'INT_22' => __('Priority Mail International Legal Flat Rate Envelope'),
723  'INT_23' => __('Priority Mail International Padded Flat Rate Envelope'),
724  'INT_24' => __('Priority Mail International DVD Flat Rate priced box'),
725  'INT_25' => __('Priority Mail International Large Video Flat Rate priced box'),
726  'INT_27' => __('Priority Mail Express International Padded Flat Rate Envelope'),
727  ],
728  'service_to_code' => [
729  '0_FCLE' => 'First Class',
730  '0_FCL' => 'First Class',
731  '0_FCP' => 'First Class',
732  '0_FCPC' => 'First Class',
733  '1' => 'Priority',
734  '2' => 'Priority Express',
735  '3' => 'Priority Express',
736  '4' => 'Retail Ground',
737  '6' => 'Media',
738  '7' => 'Library',
739  '13' => 'Priority Express',
740  '15' => 'First Class',
741  '16' => 'Priority',
742  '17' => 'Priority',
743  '22' => 'Priority',
744  '23' => 'Priority Express',
745  '25' => 'Priority Express',
746  '27' => 'Priority Express',
747  '28' => 'Priority',
748  '29' => 'Priority',
749  '30' => 'Priority Express',
750  '31' => 'Priority Express',
751  '32' => 'Priority Express',
752  '33' => 'Priority',
753  '34' => 'Priority',
754  '35' => 'Priority',
755  '36' => 'Priority',
756  '37' => 'Priority',
757  '38' => 'Priority',
758  '39' => 'Priority',
759  '40' => 'Priority',
760  '41' => 'Priority',
761  '42' => 'Priority',
762  '43' => 'Priority',
763  '44' => 'Priority',
764  '45' => 'Priority',
765  '46' => 'Priority',
766  '47' => 'Priority',
767  '48' => 'Priority',
768  '49' => 'Priority',
769  '50' => 'Priority',
770  '53' => 'First Class',
771  '57' => 'Priority Express',
772  '58' => 'Priority',
773  '59' => 'Priority',
774  '61' => 'First Class',
775  '62' => 'Priority Express',
776  '63' => 'Priority Express',
777  '64' => 'Priority Express',
778  'INT_1' => 'Priority Express',
779  'INT_2' => 'Priority',
780  'INT_4' => 'Priority Express',
781  'INT_5' => 'Priority Express',
782  'INT_6' => 'Priority Express',
783  'INT_7' => 'Priority Express',
784  'INT_8' => 'Priority',
785  'INT_9' => 'Priority',
786  'INT_10' => 'Priority Express',
787  'INT_11' => 'Priority',
788  'INT_12' => 'Priority Express',
789  'INT_13' => 'First Class',
790  'INT_14' => 'First Class',
791  'INT_15' => 'First Class',
792  'INT_16' => 'Priority',
793  'INT_17' => 'Priority',
794  'INT_18' => 'Priority',
795  'INT_19' => 'Priority',
796  'INT_20' => 'Priority',
797  'INT_21' => 'First Class',
798  'INT_22' => 'Priority',
799  'INT_23' => 'Priority',
800  'INT_24' => 'Priority',
801  'INT_25' => 'Priority',
802  'INT_27' => 'Priority Express',
803  ],
804  'method_to_code' => [
805  'First-Class Mail Large Envelope' => '0_FCLE',
806  'First-Class Mail Letter' => '0_FCL',
807  'First-Class Package Service - Retail' => '0_FCP',
808  ],
809  'first_class_mail_type' => ['LETTER' => __('Letter'), 'FLAT' => __('Flat'), 'PARCEL' => __('Parcel')],
810  'container' => [
811  'VARIABLE' => __('Variable'),
812  'SM FLAT RATE BOX' => __('Small Flat-Rate Box'),
813  'MD FLAT RATE BOX' => __('Medium Flat-Rate Box'),
814  'LG FLAT RATE BOX' => __('Large Flat-Rate Box'),
815  'FLAT RATE ENVELOPE' => __('Flat-Rate Envelope'),
816  'SM FLAT RATE ENVELOPE' => __('Small Flat-Rate Envelope'),
817  'WINDOW FLAT RATE ENVELOPE' => __('Window Flat-Rate Envelope'),
818  'GIFT CARD FLAT RATE ENVELOPE' => __('Gift Card Flat-Rate Envelope'),
819  'LEGAL FLAT RATE ENVELOPE' => __('Legal Flat-Rate Envelope'),
820  'PADDED FLAT RATE ENVELOPE' => __('Padded Flat-Rate Envelope'),
821  'RECTANGULAR' => __('Rectangular'),
822  'NONRECTANGULAR' => __('Non-rectangular'),
823  ],
824  'containers_filter' => [
825  [
826  'containers' => ['VARIABLE'],
827  'filters' => [
828  'within_us' => [
829  'method' => [
830  '13', '27', '16', '22', '17', '28', '2', '3', '1', '33', '34', '35',
831  '36', '37', '42', '43', '53', '4', '6', '15', '23', '25', '57'
832  ],
833  ],
834  'from_us' => [
835  'method' => [
836  'INT_10', 'INT_8', 'INT_11', 'INT_9', 'INT_16', 'INT_20', 'INT_4',
837  'INT_12', 'INT_1', 'INT_2', 'INT_13', 'INT_14', 'INT_15'
838  ],
839  ],
840  ],
841  ],
842  [
843  'containers' => ['SM FLAT RATE BOX'],
844  'filters' => [
845  'within_us' => [
846  'method' => ['28', '57'],
847  ],
848  'from_us' => [
849  'method' => ['INT_16', 'INT_24'],
850  ],
851  ]
852  ],
853  [
854  'containers' => ['MD FLAT RATE BOX'],
855  'filters' => [
856  'within_us' => [
857  'method' => ['17', '57'],
858  ],
859  'from_us' => [
860  'method' => ['INT_9', 'INT_24'],
861  ],
862  ]
863  ],
864  [
865  'containers' => ['LG FLAT RATE BOX'],
866  'filters' => [
867  'within_us' => [
868  'method' => ['22', '57'],
869  ],
870  'from_us' => [
871  'method' => ['INT_11', 'INT_24', 'INT_25'],
872  ],
873  ]
874  ],
875  [
876  'containers' => ['SM FLAT RATE ENVELOPE'],
877  'filters' => [
878  'within_us' => [
879  'method' => ['42', '43'],
880  ],
881  'from_us' => [
882  'method' => ['INT_20'],
883  ],
884  ]
885  ],
886  [
887  'containers' => ['WINDOW FLAT RATE ENVELOPE'],
888  'filters' => [
889  'within_us' => [
890  'method' => ['40', '41'],
891  ],
892  'from_us' => [
893  'method' => ['INT_19'],
894  ],
895  ]
896  ],
897  [
898  'containers' => ['GIFT CARD FLAT RATE ENVELOPE'],
899  'filters' => [
900  'within_us' => [
901  'method' => ['38', '39'],
902  ],
903  'from_us' => [
904  'method' => ['INT_18'],
905  ],
906  ]
907  ],
908  [
909  'containers' => ['PADDED FLAT RATE ENVELOPE'],
910  'filters' => [
911  'within_us' => [
912  'method' => ['62', '63', '64', '46', '29'],
913  ],
914  'from_us' => [
915  'method' => ['INT_27', 'INT_23'],
916  ],
917  ]
918  ],
919  [
920  'containers' => ['LEGAL FLAT RATE ENVELOPE'],
921  'filters' => [
922  'within_us' => [
923  'method' => ['44', '45', '30', '31', '32'],
924  ],
925  'from_us' => [
926  'method' => ['INT_17', 'INT_22'],
927  ],
928  ]
929  ],
930  [
931  'containers' => ['FLAT RATE ENVELOPE'],
932  'filters' => [
933  'within_us' => [
934  'method' => ['16', '13', '27', '16', '15', '37', '42', '43', '25', '62'],
935  ],
936  'from_us' => [
937  'method' => [
938  'INT_10', 'INT_8', 'INT_14', 'INT_20', 'INT_17', 'INT_18', 'INT_19', 'INT_22', 'INT_27'
939  ],
940  ],
941  ]
942  ],
943  [
944  'containers' => ['RECTANGULAR'],
945  'filters' => [
946  'within_us' => [
947  'method' => ['3', '1', '4', '6', '7', '61'],
948  ],
949  'from_us' => [
950  'method' => ['INT_12', 'INT_1', 'INT_2', 'INT_15'],
951  ],
952  ]
953  ],
954  [
955  'containers' => ['NONRECTANGULAR'],
956  'filters' => [
957  'within_us' => [
958  'method' => ['3', '1', '4', '6', '7'],
959  ],
960  'from_us' => [
961  'method' => ['INT_4', 'INT_1', 'INT_2', 'INT_15'],
962  ],
963  ]
964  ],
965  ],
966  'size' => ['REGULAR' => __('Regular'), 'LARGE' => __('Large')],
967  'machinable' => ['true' => __('Yes'), 'false' => __('No')],
968  'delivery_confirmation_types' => ['True' => __('Not Required'), 'False' => __('Required')],
969  ];
970 
971  if (!isset($codes[$type])) {
972  return false;
973  } elseif ('' === $code) {
974  return $codes[$type];
975  }
976 
977  if (!isset($codes[$type][$code])) {
978  return false;
979  } else {
980  return $codes[$type][$code];
981  }
982  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
__()
Definition: __.php:13
$type
Definition: item.phtml:13
$code
Definition: info.phtml:12

◆ getContainerTypes()

getContainerTypes ( \Magento\Framework\DataObject  $params = null)

Return container types of carrier

Parameters
\Magento\Framework\DataObject | null$params
Returns
array|bool

Definition at line 1956 of file Carrier.php.

1957  {
1958  if ($params === null) {
1959  return $this->_getAllowedContainers();
1960  }
1961 
1962  return $this->_isUSCountry($params->getCountryRecipient()) ? [] : $this->_getAllowedContainers($params);
1963  }
_getAllowedContainers(\Magento\Framework\DataObject $params=null)
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18

◆ getContainerTypesAll()

getContainerTypesAll ( )

Return all container types of carrier

Returns
array|bool

Definition at line 1970 of file Carrier.php.

1971  {
1972  return $this->getCode('container');
1973  }
getCode($type, $code='')
Definition: Carrier.php:649

◆ getContainerTypesFilter()

getContainerTypesFilter ( )

Return structured data of containers witch related with shipping methods

Returns
array|bool

Definition at line 1980 of file Carrier.php.

1981  {
1982  return $this->getCode('containers_filter');
1983  }
getCode($type, $code='')
Definition: Carrier.php:649

◆ getContentTypes()

getContentTypes ( \Magento\Framework\DataObject  $params)

Return content types of package

Parameters
\Magento\Framework\DataObject$params
Returns
array

Definition at line 2023 of file Carrier.php.

2024  {
2025  $countryShipper = $params->getCountryShipper();
2026  $countryRecipient = $params->getCountryRecipient();
2027 
2028  if ($countryShipper == self::USA_COUNTRY_ID && $countryRecipient != self::USA_COUNTRY_ID) {
2029  return [
2030  'MERCHANDISE' => __('Merchandise'),
2031  'SAMPLE' => __('Sample'),
2032  'GIFT' => __('Gift'),
2033  'DOCUMENTS' => __('Documents'),
2034  'RETURN' => __('Return'),
2035  'OTHER' => __('Other')
2036  ];
2037  }
2038 
2039  return [];
2040  }
__()
Definition: __.php:13
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18

◆ getDeliveryConfirmationTypes()

getDeliveryConfirmationTypes ( \Magento\Framework\DataObject  $params = null)

Return delivery confirmation types of carrier

Parameters
\Magento\Framework\DataObject | null$params
Returns
array

Definition at line 1991 of file Carrier.php.

1992  {
1993  if ($params == null) {
1994  return [];
1995  }
1996  $countryRecipient = $params->getCountryRecipient();
1997  if ($this->_isUSCountry($countryRecipient)) {
1998  return $this->getCode('delivery_confirmation_types');
1999  } else {
2000  return [];
2001  }
2002  }
getCode($type, $code='')
Definition: Carrier.php:649
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18

◆ getResponse()

getResponse ( )

Get tracking response

Returns
string

Definition at line 1129 of file Carrier.php.

1130  {
1131  $statuses = '';
1132  if ($this->_result instanceof \Magento\Shipping\Model\Tracking\Result) {
1133  if ($trackings = $this->_result->getAllTrackings()) {
1134  foreach ($trackings as $tracking) {
1135  if ($data = $tracking->getAllData()) {
1136  if (!empty($data['track_summary'])) {
1137  $statuses .= __($data['track_summary']);
1138  } else {
1139  $statuses .= __('Empty response');
1140  }
1141  }
1142  }
1143  }
1144  }
1145  if (empty($statuses)) {
1146  $statuses = __('Empty response');
1147  }
1148 
1149  return $statuses;
1150  }
__()
Definition: __.php:13

◆ getResult()

getResult ( )

Get result of request

Returns
Result|null

Definition at line 362 of file Carrier.php.

363  {
364  return $this->_result;
365  }

◆ getTracking()

getTracking (   $trackings)

Get tracking

Parameters
string|string[]$trackings
Returns
Result|null

Definition at line 990 of file Carrier.php.

991  {
992  $this->setTrackingReqeust();
993 
994  if (!is_array($trackings)) {
995  $trackings = [$trackings];
996  }
997 
998  $this->_getXmlTracking($trackings);
999 
1000  return $this->_result;
1001  }
_getXmlTracking($trackings)
Definition: Carrier.php:1024

◆ isGirthAllowed()

isGirthAllowed (   $countyDest = null,
  $carrierMethodCode = null 
)

Check whether girth is allowed for the USPS

Parameters
null | string$countyDest
null | string$carrierMethodCode
Returns
bool

Definition at line 2011 of file Carrier.php.

2012  {
2013  return $this->_isUSCountry($countyDest)
2014  && $this->getDataHelper()->displayGirthValue($carrierMethodCode) ? false : true;
2015  }
return false
Definition: gallery.phtml:36

◆ isShippingLabelsAvailable()

isShippingLabelsAvailable ( )

Check if carrier has shipping label option available

Returns
bool @api
Starting from 23.02.2018 USPS doesn't allow to create free shipping labels via their API.

Implements AbstractCarrierInterface.

Definition at line 371 of file Carrier.php.

372  {
373  return false;
374  }

◆ setRequest()

Prepare and set request to this instance

Parameters
\Magento\Quote\Model\Quote\Address\RateRequest$request
Returns
$this @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity) @SuppressWarnings(PHPMD.ExcessiveMethodLength)

Definition at line 231 of file Carrier.php.

232  {
233  $this->_request = $request;
234 
235  $r = new \Magento\Framework\DataObject();
236 
237  if ($request->getLimitMethod()) {
238  $r->setService($request->getLimitMethod());
239  } else {
240  $r->setService('ALL');
241  }
242 
243  if ($request->getUspsUserid()) {
244  $userId = $request->getUspsUserid();
245  } else {
246  $userId = $this->getConfigData('userid');
247  }
248  $r->setUserId($userId);
249 
250  if ($request->getUspsContainer()) {
251  $container = $request->getUspsContainer();
252  } else {
253  $container = $this->getConfigData('container');
254  }
255  $r->setContainer($container);
256 
257  if ($request->getUspsSize()) {
258  $size = $request->getUspsSize();
259  } else {
260  $size = $this->getConfigData('size');
261  }
262  $r->setSize($size);
263 
264  if ($request->getGirth()) {
265  $girth = $request->getGirth();
266  } else {
267  $girth = $this->getConfigData('girth');
268  }
269  $r->setGirth($girth);
270 
271  if ($request->getHeight()) {
272  $height = $request->getHeight();
273  } else {
274  $height = $this->getConfigData('height');
275  }
276  $r->setHeight($height);
277 
278  if ($request->getLength()) {
279  $length = $request->getLength();
280  } else {
281  $length = $this->getConfigData('length');
282  }
283  $r->setLength($length);
284 
285  if ($request->getWidth()) {
286  $width = $request->getWidth();
287  } else {
288  $width = $this->getConfigData('width');
289  }
290  $r->setWidth($width);
291 
292  if ($request->getUspsMachinable()) {
293  $machinable = $request->getUspsMachinable();
294  } else {
295  $machinable = $this->getConfigData('machinable');
296  }
297  $r->setMachinable($machinable);
298 
299  if ($request->getOrigPostcode()) {
300  $r->setOrigPostal($request->getOrigPostcode());
301  } else {
302  $r->setOrigPostal(
303  $this->_scopeConfig->getValue(
304  \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_ZIP,
305  \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
306  $request->getStoreId()
307  )
308  );
309  }
310 
311  if ($request->getOrigCountryId()) {
312  $r->setOrigCountryId($request->getOrigCountryId());
313  } else {
314  $r->setOrigCountryId(
315  $this->_scopeConfig->getValue(
316  \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID,
317  \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
318  $request->getStoreId()
319  )
320  );
321  }
322 
323  if ($request->getDestCountryId()) {
324  $destCountry = $request->getDestCountryId();
325  } else {
326  $destCountry = self::USA_COUNTRY_ID;
327  }
328 
329  $r->setDestCountryId($destCountry);
330 
331  if (!$this->_isUSCountry($destCountry)) {
332  $r->setDestCountryName($this->_getCountryName($destCountry));
333  }
334 
335  if ($request->getDestPostcode()) {
336  $r->setDestPostal($request->getDestPostcode());
337  }
338 
339  $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
340  $r->setWeightPounds(floor($weight));
341  $ounces = ($weight - floor($weight)) * self::OUNCES_POUND;
342  $r->setWeightOunces(sprintf('%.' . self::$weightPrecision . 'f', $ounces));
343  if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
344  $r->setFreeMethodWeight($request->getFreeMethodWeight());
345  }
346 
347  $r->setValue($request->getPackageValue());
348  $r->setValueWithDiscount($request->getPackageValueWithDiscount());
349 
350  $r->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
351 
352  $this->setRawRequest($r);
353 
354  return $this;
355  }
_getCountryName($countryId)
Definition: Carrier.php:1176

◆ setTrackingReqeust()

setTrackingReqeust ( )
protected

Set tracking request

Returns
void

Definition at line 1008 of file Carrier.php.

1009  {
1010  $r = new \Magento\Framework\DataObject();
1011 
1012  $userId = $this->getConfigData('userid');
1013  $r->setUserId($userId);
1014 
1015  $this->_rawTrackRequest = $r;
1016  }

Field Documentation

◆ $_carrierHelper

$_carrierHelper
protected

Definition at line 112 of file Carrier.php.

◆ $_code

$_code = self::CODE
protected

Definition at line 70 of file Carrier.php.

◆ $_customizableContainerTypes

$_customizableContainerTypes = ['VARIABLE', 'RECTANGULAR', 'NONRECTANGULAR']
protected

Definition at line 105 of file Carrier.php.

◆ $_debugReplacePrivateDataKeys

$_debugReplacePrivateDataKeys
protected
Initial value:
= [
'USERID'
]

Definition at line 127 of file Carrier.php.

◆ $_defaultGatewayUrl

$_defaultGatewayUrl = 'http://production.shippingapis.com/ShippingAPI.dll'
protected

Definition at line 98 of file Carrier.php.

◆ $_httpClientFactory

$_httpClientFactory
protected

Definition at line 122 of file Carrier.php.

◆ $_productCollectionFactory

$_productCollectionFactory
protected

Definition at line 117 of file Carrier.php.

◆ $_request

$_request = null
protected

Definition at line 84 of file Carrier.php.

◆ $_result

$_result = null
protected

Definition at line 91 of file Carrier.php.

◆ CODE

const CODE = 'usps'

Definition at line 58 of file Carrier.php.

◆ CONTAINER_FLAT_RATE_BOX

const CONTAINER_FLAT_RATE_BOX = 'FLAT RATE BOX'
Deprecated:

Definition at line 28 of file Carrier.php.

◆ CONTAINER_FLAT_RATE_ENVELOPE

const CONTAINER_FLAT_RATE_ENVELOPE = 'FLAT RATE ENVELOPE'
Deprecated:

Definition at line 31 of file Carrier.php.

◆ CONTAINER_NONRECTANGULAR

const CONTAINER_NONRECTANGULAR = 'NONRECTANGULAR'
Deprecated:

Definition at line 37 of file Carrier.php.

◆ CONTAINER_RECTANGULAR

const CONTAINER_RECTANGULAR = 'RECTANGULAR'
Deprecated:

Definition at line 34 of file Carrier.php.

◆ CONTAINER_VARIABLE

const CONTAINER_VARIABLE = 'VARIABLE'
Deprecated:

Definition at line 25 of file Carrier.php.

◆ DEFAULT_REVISION

const DEFAULT_REVISION = 2

Definition at line 51 of file Carrier.php.

◆ OUNCES_POUND

const OUNCES_POUND = 16

Ounces in one pound for conversion

Definition at line 63 of file Carrier.php.

◆ SIZE_LARGE

const SIZE_LARGE = 'LARGE'

Definition at line 44 of file Carrier.php.

◆ SIZE_REGULAR

const SIZE_REGULAR = 'REGULAR'

USPS size

Definition at line 42 of file Carrier.php.


The documentation for this class was generated from the following file: