Beispiel #1
0
 /**
  * doQuery
  *
  * @param array   $data        Data
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return array
  */
 protected function doQuery($data, $ignoreCache)
 {
     $rates = array();
     $key = $this->getConfigurationFingerPrint() . serialize($data);
     if (!$ignoreCache) {
         $cachedResponse = $this->getDataFromCache($key);
     }
     $response = null;
     if (isset($cachedResponse)) {
         $response = $cachedResponse;
     } elseif (!\XLite\Model\Shipping::isIgnoreLongCalculations()) {
         $APIConnector = $this->getAPIConnector();
         $this->setRequestData($data);
         $status = false;
         if (\XLite\Module\XC\AuctionInc\Main::isSSAvailable()) {
             $status = $APIConnector->GetItemShipRateSS($response);
         } elseif (\XLite\Module\XC\AuctionInc\Main::isXSAvailable()) {
             $methods = $this->getEnabledMethods();
             if (count($methods)) {
                 $status = $APIConnector->GetItemShipRateXS($response);
             }
         }
         $this->logResponse($status, $data, $response);
         if ($status) {
             $this->saveDataInCache($key, $response);
             // drop selected shipping method to set it to cheapest
             if (!\XLite::isAdminZone()) {
                 /** @var \XLite\Model\Cart $cart */
                 $cart = \XLite::getController()->getCart();
                 $cart->setShippingId(0);
                 if ($cart->getProfile()) {
                     $cart->getProfile()->setLastShippingId(0);
                 }
             }
         } elseif (isset($response['ErrorList'])) {
             // report error
             $errorMessages = array();
             foreach ($response['ErrorList'] as $error) {
                 $errorMessages[] = $error['Message'];
             }
             $this->errorMsg = implode('; ', $errorMessages);
         }
     }
     if ($response && empty($this->errorMsg)) {
         $rates = $this->parseResponse($response);
     } else {
         $this->saveDataInCache($key, $response, static::CACHE_TTL);
     }
     if (!$response || empty($rates)) {
         // Apply fallback rate
         if (empty($rates) && 'N' != \XLite\Core\Config::getInstance()->XC->AuctionInc->fallbackRate) {
             $rateValue = $this->getFallbackRateValue($data['package']);
             $rate = new \XLite\Model\Shipping\Rate();
             $rate->setBaseRate($rateValue);
             $method = $this->findMethod('FF', 'FIXEDFEE', 'Fixed fee');
             $rate->setMethod($method);
             $rates[] = $rate;
             $this->errorMsg = null;
         }
     }
     return $rates;
 }
Beispiel #2
0
 /**
  * Do request to AustraliaPost API and receive response
  *
  * @param string  $type        Request type
  * @param array   $params      Array of parameters
  * @param boolean $ignoreCache Flag: ignore cache
  *
  * @return array|null
  */
 protected function doRequest($type, $params = array(), $ignoreCache = false)
 {
     $result = null;
     $requestType = $this->getApiRequestType($type);
     $config = $this->getConfiguration();
     $methodName = 'getRequestData' . $type;
     $data = array();
     if (method_exists($this, $methodName)) {
         // Call method to prepare request data
         $data = $this->{$methodName}($params);
     }
     // Validate request data
     if ($this->validateRequestData($requestType, $data)) {
         // Prepare post data
         $postData = array();
         foreach ($data as $key => $value) {
             if (in_array($key, array('option_code', 'suboption_code'))) {
                 foreach ($value as $opcode) {
                     $postData[] = sprintf('%s=%s', $key, $opcode);
                 }
             } else {
                 $postData[] = sprintf('%s=%s', $key, $value);
             }
         }
         $postURL = $this->getApiURL() . $requestType['uri'] . '.json?' . implode('&', $postData);
         if (!$ignoreCache) {
             // Try to get cached result
             $cachedRate = $this->getDataFromCache($postURL . $this->getApiKey());
         }
         if (isset($cachedRate)) {
             // Get result from cache
             $result = $cachedRate;
         } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
             // Ignore rates calculation
             return array();
         } else {
             // Get result from AustraliaPost server
             try {
                 $headers = array('AUTH-KEY: ' . $this->getApiKey());
                 $ch = curl_init();
                 curl_setopt($ch, CURLOPT_URL, $postURL);
                 curl_setopt($ch, CURLOPT_HEADER, false);
                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                 if ($this->isTestMode()) {
                     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                 }
                 $response = curl_exec($ch);
                 if (!empty($response)) {
                     $result = json_decode($response, true);
                     if (!empty($result['error'])) {
                         $this->setError($result['error']['errorMessage']);
                     } else {
                         $this->saveDataInCache($postURL . $this->getApiKey(), $result);
                     }
                 } else {
                     $this->setError(sprintf('Error while connecting to the AustraliaPost host (%s)', $postURL));
                 }
                 if ($ignoreCache === true) {
                     // Prepare data to display on Test AustraliaPost page
                     $this->addApiCommunicationMessage(array('request_url' => $postURL, 'request_data' => $data, 'response' => $response, 'response_parsed' => $result));
                 }
                 if ($config->debug_enabled) {
                     $this->log(array('postURL' => $postURL, 'data' => $data, 'result' => $result));
                 }
             } catch (\Exception $e) {
                 $this->setError($e->getMessage());
             }
         }
     }
     return $result;
 }
Beispiel #3
0
 /**
  * Check - build options or not
  *
  * @return boolean
  */
 protected function isBuildOptions()
 {
     return !\XLite\Model\Shipping::isIgnoreLongCalculations();
 }
Beispiel #4
0
 /**
  * Performs request to USPS server and returns array of rates
  *
  * @param array   $data        Array of request parameters
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return array
  */
 protected function doQuery($data, $ignoreCache)
 {
     $result = null;
     $rates = array();
     $availableMethods = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->findMethodsByProcessor($this->getProcessorId());
     if ($availableMethods) {
         $xmlData = $this->getXMLData($data);
         $currencyRate = doubleval(\XLite\Core\Config::getInstance()->CDev->USPS->currency_rate);
         $currencyRate = 0 < $currencyRate ? $currencyRate : 1;
         $postURL = $this->getApiURL() . '?API=' . $this->getApiName() . '&XML=' . urlencode(preg_replace('/>(\\s+)</', '><', $xmlData));
         try {
             if (!$ignoreCache) {
                 $cachedRate = $this->getDataFromCache($postURL);
             }
             if (isset($cachedRate)) {
                 // Get rates from cache
                 $result = $cachedRate;
             } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
                 // Ignore rates calculation
                 return array();
             } else {
                 // Calculate rate
                 $bouncer = new \XLite\Core\HTTP\Request($postURL);
                 $bouncer->requestTimeout = 5;
                 $response = $bouncer->sendRequest();
                 if ($response && 200 == $response->code) {
                     $result = $response->body;
                     $this->saveDataInCache($postURL, $result);
                     if (\XLite\Core\Config::getInstance()->CDev->USPS->debug_enabled) {
                         \XLite\Logger::logCustom('USPS', var_export(array('Request URL' => $postURL, 'Request XML' => $xmlData, 'Response' => \XLite\Core\XML::getInstance()->getFormattedXML($result)), true));
                     }
                 } else {
                     $this->errorMsg = sprintf('Error while connecting to the USPS host (%s)', $this->getApiURL());
                 }
             }
             $response = isset($this->errorMsg) ? array() : $this->parseResponse($result);
             $this->apiCommunicationLog[] = array('request' => $postURL, 'xml' => htmlentities(preg_replace('/(USERID=")([^"]+)/', '\\1***', $xmlData)), 'response' => htmlentities(\XLite\Core\XML::getInstance()->getFormattedXML($result)));
             if (!isset($this->errorMsg) && !isset($response['err_msg']) && !empty($response['postage'])) {
                 foreach ($response['postage'] as $postage) {
                     $rate = new \XLite\Model\Shipping\Rate();
                     $method = $this->getShippingMethod($postage['CLASSID'], $availableMethods);
                     if (!isset($method)) {
                         // Unknown method received: add this to the database with disabled status
                         $method = $this->addShippingMethod($postage);
                     }
                     if ($method && $method->getEnabled()) {
                         // Method is registered and enabled
                         $rate->setMethod($method);
                         $codPrice = 0;
                         $rateValue = doubleval($postage['Rate']);
                         if (!$this->isStaticCODPrice() && isset($postage['SpecialServices'])) {
                             if (isset($postage['SpecialServices'][6]) && 'true' == $postage['SpecialServices'][6]['Available']) {
                                 // Shipping service supports COD
                                 $extraData = new \XLite\Core\CommonCell();
                                 $extraData->cod_supported = true;
                                 $extraData->cod_rate = ($rateValue + doubleval($postage['SpecialServices'][6]['Price'])) * $currencyRate;
                                 $rate->setExtraData($extraData);
                                 if ($data['cod_enabled']) {
                                     // Calculate COD fee if COD payment method is selected
                                     $codPrice = doubleval($postage['SpecialServices'][6]['Price']);
                                 }
                             }
                         } elseif ($this->isStaticCODPrice() && $this->isMethodSupportCOD($method)) {
                             $codStaticPrice = doubleval(\XLite\Core\Config::getInstance()->CDev->USPS->cod_price);
                             if (0 < $codStaticPrice) {
                                 // Shipping service supports COD
                                 $extraData = new \XLite\Core\CommonCell();
                                 $extraData->cod_supported = true;
                                 $extraData->cod_rate = ($rateValue + $codStaticPrice) * $currencyRate;
                                 $rate->setExtraData($extraData);
                                 if ($data['cod_enabled']) {
                                     // Calculate COD fee if COD payment method is selected
                                     $codPrice = $codStaticPrice;
                                 }
                             }
                         }
                         // Base rate is a sum of base rate and COD fee
                         $rate->setBaseRate(($rateValue + $codPrice) * $currencyRate);
                         if (isset($rates[$postage['MailService']])) {
                             // Multipackaging: sum base rate and COD fee for each rated packages
                             $rates[$postage['MailService']]->setBaseRate($rates[$postage['MailService']]->getBaseRate() + $rate->getBaseRate());
                             if ($rate->getExtraData()->cod_rate) {
                                 $extra = $rates[$postage['MailService']]->getExtraData();
                                 $extra->cod_rate = $extra->cod_rate + $rate->getExtraData()->cod_rate;
                                 $rates[$postage['MailService']]->setExtraData($extra);
                             }
                         } else {
                             $rates[$postage['MailService']] = $rate;
                         }
                     }
                 }
             } elseif (!isset($this->errorMsg)) {
                 $this->errorMsg = isset($response['err_msg']) ? $response['err_msg'] : 'Unknown error';
             }
         } catch (\Exception $e) {
             $this->errorMsg = 'Exception: ' . $e->getMessage();
         }
     }
     return $rates;
 }
Beispiel #5
0
 /**
  * Internal unconditional getRates() part
  * 
  * @param \XLite\Logic\Order\Modifier\Shipping $inputData   Shipping order modifier or array of data for request
  * @param boolean                              $ignoreCache Flag: if true then do not get rates from cache OPTIONAL
  *
  * @return array
  */
 protected function getGuaranteedRates($inputData, $ignoreCache = false)
 {
     $rates = array();
     $cachedRate = null;
     if (!$ignoreCache) {
         $cachedRate = $this->getDataFromCache($this->getGuaranteedCacheKey($inputData));
     }
     if (null !== $cachedRate) {
         $rates = $cachedRate;
     } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
         $rates = array();
     } else {
         $rates = $this->getGuaranteedRatesFromServer($inputData);
         if ($rates) {
             // Force translations lazy loading
             foreach ($rates as $rate) {
                 $rate->getMethod()->getName();
             }
             $this->saveDataInCache($this->getGuaranteedCacheKey($inputData), $rates, static::CREATE_ORDER_TTL);
         }
     }
     return $rates;
 }
Beispiel #6
0
 /**
  * doQuery
  *
  * lowlevel query
  *
  * @param mixed   $data        Array of prepared package data
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return void
  */
 protected function doQuery($data, $ignoreCache)
 {
     $rates = array();
     $availableMethods = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->findMethodsByProcessor($this->getProcessorId());
     $config = $this->getConfig();
     $XMLData = $this->getXMLData($data);
     try {
         if (!$ignoreCache) {
             $cachedRates = $this->getDataFromCache($XMLData);
         }
         if (isset($cachedRates)) {
             $result = $cachedRates;
         } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
             // Ignore rates calculation
             return array();
         } else {
             $postURL = \XLite\Module\XC\CanadaPost\Core\API::getInstance()->getGetRatesEndpoint();
             $bouncer = new \XLite\Core\HTTP\Request($postURL);
             $bouncer->requestTimeout = 5;
             $bouncer->body = $XMLData;
             $bouncer->verb = 'POST';
             $bouncer->setHeader('Authorization', 'Basic ' . base64_encode($config->user . ':' . $config->password));
             $bouncer->setHeader('Accept', 'application/vnd.cpc.ship.rate-v2+xml');
             $bouncer->setHeader('Content-Type', 'application/vnd.cpc.ship.rate-v2+xml');
             $bouncer->setHeader('Accept-language', \XLite\Module\XC\CanadaPost\Core\API::ACCEPT_LANGUAGE_EN);
             if (\XLite\Module\XC\CanadaPost\Core\API::isOnBehalfOfAMerchant()) {
                 $bouncer->setHeader('Platform-id', \XLite\Module\XC\CanadaPost\Core\API::getInstance()->getPlatformId());
             }
             $response = $bouncer->sendRequest();
             $result = $response->body;
             if (200 == $response->code) {
                 $this->saveDataInCache($XMLData, $result);
             } else {
                 $this->errorMsg = sprintf('Error while connecting to the Canada Post host (%s)', $postURL);
             }
             if (\XLite\Core\Config::getInstance()->XC->CanadaPost->debug_enabled) {
                 // Save debug log
                 \XLite\Module\XC\CanadaPost\Core\API::logApiCall($postURL, 'Get Rates', $XMLData, $result);
             }
         }
         // Save communication log for test request only (ignoreCache is set for test requests only)
         if ($ignoreCache === true) {
             $this->apiCommunicationLog[] = array('post URL' => $postURL, 'request' => htmlentities($XMLData), 'response' => htmlentities(\XLite\Core\XML::getInstance()->getFormattedXML($result)));
         }
         $response = $this->parseResponse($result);
         if (!isset($this->errorMsg) && !isset($response['err_msg']) && !empty($response['services'])) {
             $conversionRate = \XLite\Module\XC\CanadaPost\Core\API::getCurrencyConversionRate();
             foreach ($response['services'] as $service) {
                 $rate = new \XLite\Model\Shipping\Rate();
                 $method = $this->getShippingMethod($service['service_code'], $availableMethods);
                 if (!isset($method)) {
                     // Unknown method received: add this to the database with disabled status
                     $this->addShippingMethod($service);
                 } elseif ($method->getEnabled()) {
                     // Method is registered and enabled
                     $rate->setMethod($method);
                     $rate->setBaseRate($service['rate'] * $conversionRate);
                     $rates[$service['service_code']] = $rate;
                 }
             }
         } elseif (!isset($this->errorMsg) || isset($response['err_msg'])) {
             $this->errorMsg = isset($response['err_msg']) ? $response['err_msg'] : ($this->errorMsg ?: 'Unknown error');
         }
     } catch (\Exception $e) {
         $this->errorMsg = $e->getMessage();
     }
     return $rates;
 }
Beispiel #7
0
 /**
  * Performs request to carrier server and returns array of rates
  *
  * @param array   $data        Array of request parameters
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return \XLite\Model\Shipping\Rate[]
  */
 protected function performRequest($data, $ignoreCache)
 {
     $rates = array();
     $config = $this->getConfiguration();
     $xmlData = $this->getXMLData($data);
     try {
         if (!$ignoreCache) {
             $cachedRate = $this->getDataFromCache($xmlData);
         }
         $postURL = $this->getApiURL();
         $result = null;
         if (isset($cachedRate)) {
             $result = $cachedRate;
         } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
             // Ignore rates calculation
             return array();
         } else {
             $bouncer = new \XLite\Core\HTTP\Request($postURL);
             $bouncer->body = $xmlData;
             $bouncer->verb = 'POST';
             $bouncer->requestTimeout = 5;
             $response = $bouncer->sendRequest();
             if (200 == $response->code || !empty($response->body)) {
                 $result = $response->body;
                 if (200 == $response->code) {
                     $this->saveDataInCache($xmlData, $result);
                 }
                 if ($config->debug_enabled) {
                     $this->log(array('request_url' => $postURL, 'request_data' => $this->filterRequestData($xmlData), 'response' => \XLite\Core\XML::getInstance()->getFormattedXML($result)));
                 }
             } else {
                 $this->setError(sprintf('Error while connecting to the FedEx host (%s)', $postURL));
             }
         }
         $response = !$this->hasError() ? $this->parseResponse($result) : array();
         //save communication log for test request only (ignoreCache is set for test requests only)
         if ($ignoreCache === true) {
             $this->addApiCommunicationMessage(array('request_url' => $postURL, 'request_data' => $xmlData, 'response' => $result));
         }
         if (!$this->hasError() && !isset($response['err_msg'])) {
             foreach ($response as $code => $_rate) {
                 $rate = new \XLite\Model\Shipping\Rate();
                 $method = $this->getMethodByCode($code, static::STATE_ALL);
                 if ($method && $method->getEnabled()) {
                     // Method is registered and enabled
                     $rate->setMethod($method);
                     $rate->setBaseRate($_rate['amount']);
                     if (!empty($data['cod_enabled'])) {
                         $extraData = new \XLite\Core\CommonCell();
                         $extraData->cod_supported = true;
                         $extraData->cod_rate = $rate->getBaseRate();
                         $rate->setExtraData($extraData);
                     }
                     $rates[] = $rate;
                 }
             }
         } elseif (!$this->hasError()) {
             $this->setError(isset($response['err_msg']) ? $response['err_msg'] : 'Unknown error');
         }
     } catch (\Exception $e) {
         $this->setError('Exception: ' . $e->getMessage());
     }
     return $rates;
 }
Beispiel #8
0
 /**
  * doQuery
  *
  * @param mixed   $data        Can be either \XLite\Model\Order instance or an array
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return void
  */
 protected function doQuery($data, $ignoreCache)
 {
     $rates = array();
     // Get all available rates
     $availableMethods = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->findMethodsByProcessor($this->getProcessorId(), !$ignoreCache);
     if ($availableMethods) {
         // Do rates calculation if there are enabled shipping methods or calculation test is running
         $xmlData = $this->getXMLData($data);
         $postData = preg_split("/(\r\n|\r|\n)/", $xmlData, -1, PREG_SPLIT_NO_EMPTY);
         $postURL = $this->getApiURL();
         try {
             if (!$ignoreCache) {
                 $cachedRate = $this->getDataFromCache($xmlData);
             }
             if (isset($cachedRate)) {
                 $result = $cachedRate;
             } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
                 // Ignore rates calculation
                 return array();
             } else {
                 // Prepare request XML for logging
                 $xmlDataLog = preg_replace('|<AccessLicenseNumber>.+</AccessLicenseNumber>|i', '<AccessLicenseNumber>xxx</AccessLicenseNumber>', $xmlData);
                 $xmlDataLog = preg_replace('|<UserId>.+</UserId>|i', '<UserId>xxx</UserId>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<Password>.+</Password>|i', '<Password>xxx</Password>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<ShipperNumber>.+</ShipperNumber>|i', '<ShipperNumber>xxx</ShipperNumber>', $xmlDataLog);
                 // Do request
                 $bouncer = new \XLite\Core\HTTP\Request($postURL . '/Rate');
                 $bouncer->body = $xmlData;
                 $bouncer->verb = 'POST';
                 $bouncer->requestTimeout = 5;
                 $response = $bouncer->sendRequest();
                 if (200 == $response->code || !empty($response->body)) {
                     $result = $response->body;
                     if (200 == $response->code) {
                         $this->saveDataInCache($xmlData, $result);
                     }
                     if (\XLite\Core\Config::getInstance()->XC->UPS->debug_enabled) {
                         \XLite\Logger::logCustom('UPS', var_export(array('Request URL' => $postURL, 'Request XML' => $xmlDataLog, 'Response XML' => \XLite\Core\XML::getInstance()->getFormattedXML($result)), true));
                     }
                 } else {
                     $this->errorMsg = sprintf('Error while connecting to the UPS server (%s)', $this->getApiURL());
                 }
             }
             if (!isset($this->errorMsg)) {
                 $response = $this->parseResponse($result);
             } else {
                 $response = array();
             }
             // Save communication log for test request only (ignoreCache is set for test requests only)
             if ($ignoreCache === true) {
                 $this->apiCommunicationLog[] = array('post URL' => $postURL, 'request' => htmlentities($xmlDataLog), 'response' => htmlentities(\XLite\Core\XML::getInstance()->getFormattedXML($result)));
             }
             if (!isset($this->errorMsg) && !isset($response['err_msg'])) {
                 foreach ($response as $row) {
                     $method = $this->getShippingMethod($row['serviceCode'], $data['srcAddress']['country'], $availableMethods);
                     if ($method) {
                         $rate = new \XLite\Model\Shipping\Rate();
                         $rate->setBaseRate($row['totalCharges']);
                         $rate->setMethod($method);
                         $extraData = null;
                         if (!empty($row['deliveryTime'])) {
                             $extraData = new \XLite\Core\CommonCell();
                             $extraData->deliveryDays = $row['deliveryTime'];
                             $rate->setExtraData($extraData);
                         }
                         if ($data['cod_enabled'] && $this->isCODAllowed('all', $data['srcAddress']['country'], $data['dstAddress']['country'])) {
                             $extraData = $extraData ?: new \XLite\Core\CommonCell();
                             $extraData->cod_supported = true;
                             $extraData->cod_rate = $rate->getBaseRate();
                             $rate->setExtraData($extraData);
                         }
                         $rates[] = $rate;
                     }
                 }
             } elseif (!isset($this->errorMsg)) {
                 $this->errorMsg = isset($response['err_msg']) ? $response['err_msg'] : 'Unknown error';
             }
         } catch (\Exception $e) {
             $this->errorMsg = 'Exception: ' . $e->getMessage();
         }
     }
     return $rates;
 }
Beispiel #9
0
 /**
  * Performs request to FedEx server and returns array of rates
  *
  * @param array   $data        Array of request parameters
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return array
  */
 protected function doRequest($data, $ignoreCache)
 {
     $rates = array();
     $availableMethods = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->findMethodsByProcessor($this->getProcessorId());
     if ($availableMethods) {
         $xmlData = $this->getXMLData($data);
         $postURL = $this->getApiURL();
         try {
             if (!$ignoreCache) {
                 $cachedRate = $this->getDataFromCache($xmlData);
             }
             if (isset($cachedRate)) {
                 $result = $cachedRate;
             } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
                 // Ignore rates calculation
                 return array();
             } else {
                 $bouncer = new \XLite\Core\HTTP\Request($postURL);
                 $bouncer->body = $xmlData;
                 $bouncer->verb = 'POST';
                 $bouncer->requestTimeout = 5;
                 $response = $bouncer->sendRequest();
                 if (200 == $response->code || !empty($response->body)) {
                     $result = $response->body;
                     if (200 == $response->code) {
                         $this->saveDataInCache($xmlData, $result);
                     }
                     if (\XLite\Core\Config::getInstance()->CDev->FedEx->debug_enabled) {
                         \XLite\Logger::logCustom('FEDEX', var_export(array('Request URL' => $postURL, 'Request XML' => $xmlData, 'Response' => \XLite\Core\XML::getInstance()->getFormattedXML($result)), true));
                     }
                 } else {
                     $this->errorMsg = sprintf('Error while connecting to the FedEx host (%s)', $this->getApiURL());
                 }
             }
             if (!isset($this->errorMsg)) {
                 $response = $this->parseResponse($result);
             } else {
                 $response = array();
             }
             //save communication log for test request only (ignoreCache is set for test requests only)
             if ($ignoreCache === true) {
                 $xmlDataLog = preg_replace('|<v13:AccountNumber>.+</v13:AccountNumber>|i', '<v13:AccountNumber>xxx</v13:AccountNumber>', $xmlData);
                 $xmlDataLog = preg_replace('|<v13:MeterNumber>.+</v13:MeterNumber>|i', '<v13:MeterNumber>xxx</v13:MeterNumber>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<v13:Key>.+</v13:Key>|i', '<v13:Key>xxx</v13:Key>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<v13:Password>.+</v13:Password>|i', '<v13:Password>xxx</v13:Password>', $xmlDataLog);
                 $this->apiCommunicationLog[] = array('request' => $postURL, 'xml' => htmlentities($xmlDataLog), 'response' => htmlentities(\XLite\Core\XML::getInstance()->getFormattedXML($result)));
             }
             if (!isset($this->errorMsg) && !isset($response['err_msg'])) {
                 foreach ($response as $code => $_rate) {
                     $rate = new \XLite\Model\Shipping\Rate();
                     $method = $this->getShippingMethod($code, $availableMethods);
                     if ($method && $method->getEnabled()) {
                         // Method is registered and enabled
                         $rate->setMethod($method);
                         $rate->setBaseRate($_rate['amount']);
                         if (!empty($data['cod_enabled'])) {
                             $extraData = new \XLite\Core\CommonCell();
                             $extraData->cod_supported = true;
                             $rate->setExtraData($extraData);
                         }
                         $rates[] = $rate;
                     }
                 }
             } elseif (!isset($this->errorMsg)) {
                 $this->errorMsg = isset($response['err_msg']) ? $response['err_msg'] : 'Unknown error';
             }
         } catch (\Exception $e) {
             $this->errorMsg = 'Exception: ' . $e->getMessage();
         }
     }
     return $rates;
 }
Beispiel #10
0
 /**
  * doQuery
  *
  * @param mixed   $data        Can be either \XLite\Model\Order instance or an array
  * @param boolean $ignoreCache Flag: if true then do not get rates from cache
  *
  * @return array
  */
 protected function doQuery($data, $ignoreCache)
 {
     $rates = array();
     $config = $this->getConfiguration();
     if ($this->getMethods()) {
         // Do rates calculation if there are enabled shipping methods or calculation test is running
         $xmlData = $this->getXMLData($data);
         $postURL = $this->getApiURL();
         try {
             if (!$ignoreCache) {
                 $cachedRate = $this->getDataFromCache($xmlData);
             }
             if (isset($cachedRate)) {
                 $result = $cachedRate;
             } elseif (\XLite\Model\Shipping::isIgnoreLongCalculations()) {
                 // Ignore rates calculation
                 return array();
             } else {
                 // Prepare request XML for logging
                 $xmlDataLog = preg_replace('|<AccessLicenseNumber>.+</AccessLicenseNumber>|i', '<AccessLicenseNumber>xxx</AccessLicenseNumber>', $xmlData);
                 $xmlDataLog = preg_replace('|<UserId>.+</UserId>|i', '<UserId>xxx</UserId>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<Password>.+</Password>|i', '<Password>xxx</Password>', $xmlDataLog);
                 $xmlDataLog = preg_replace('|<ShipperNumber>.+</ShipperNumber>|i', '<ShipperNumber>xxx</ShipperNumber>', $xmlDataLog);
                 // Do request
                 $bouncer = new \XLite\Core\HTTP\Request($postURL . '/Rate');
                 $bouncer->body = $xmlData;
                 $bouncer->verb = 'POST';
                 $bouncer->requestTimeout = 5;
                 $response = $bouncer->sendRequest();
                 if (200 == $response->code || !empty($response->body)) {
                     $result = $response->body;
                     if (200 == $response->code) {
                         $this->saveDataInCache($xmlData, $result);
                     }
                     if ($config->debug_enabled) {
                         $this->log(array('request_url' => $postURL, 'request_data' => $this->filterRequestData($xmlDataLog), 'response' => \XLite\Core\XML::getInstance()->getFormattedXML($result)));
                     }
                 } else {
                     $this->setError(sprintf('Error while connecting to the UPS server (%s)', $this->getApiURL()));
                 }
             }
             $response = array();
             if (!$this->hasError()) {
                 $response = $this->parseResponse($result);
             }
             // Save communication log for test request only (ignoreCache is set for test requests only)
             if ($ignoreCache === true) {
                 $this->addApiCommunicationMessage(array('request_url' => $postURL, 'request_data' => $xmlDataLog, 'response' => $result));
             }
             if (!$this->hasError() && !isset($response['err_msg'])) {
                 foreach ($response as $row) {
                     $method = $this->getMethodByServiceCodeAndCountry($row['serviceCode'], $data['srcAddress']['country']);
                     if ($method) {
                         $rate = new \XLite\Model\Shipping\Rate();
                         $rate->setBaseRate($row['totalCharges']);
                         $rate->setMethod($method);
                         $extraData = null;
                         if (!empty($row['deliveryTime'])) {
                             $extraData = new \XLite\Core\CommonCell();
                             $extraData->deliveryDays = $row['deliveryTime'];
                             $rate->setExtraData($extraData);
                         }
                         if ($data['cod_enabled'] && $this->isCODAllowed('all', $data['srcAddress']['country'], $data['dstAddress']['country'])) {
                             $extraData = $extraData ?: new \XLite\Core\CommonCell();
                             $extraData->cod_supported = true;
                             $extraData->cod_rate = $rate->getBaseRate();
                             $rate->setExtraData($extraData);
                         }
                         $rates[] = $rate;
                     }
                 }
             } elseif (!$this->hasError()) {
                 $this->setError(isset($response['err_msg']) ? $response['err_msg'] : 'Unknown error');
             }
         } catch (\Exception $e) {
             $this->setError('Exception: ' . $e->getMessage());
         }
     }
     return $rates;
 }