/** * testCreate * * @return void * @access public * @see ____func_see____ * @since 1.0.0 */ public function testCreate() { // Prepare data for rate $method = $this->getMethodByName('Courier'); $methodName = $method->getName(); $markups = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Markup')->findAll(); $this->assertTrue(0 < count($markups), 'markups list length checking'); $markup = array_shift($markups); $markupId = $markup->getMarkupId(); unset($markups); $extraData = new \XLite\Core\CommonCell(); $extraData->testparam1 = 'test value 1'; $extraData->testparam2 = 'test value 2'; $newRate = new \XLite\Model\Shipping\Rate(); $newRate->setMethod($method); $newRate->setBaseRate(100); $newRate->setMarkup($markup); $newRate->setMarkupRate(200); $newRate->setExtraData($extraData); // Check all parameters $this->assertEquals($markupId, $newRate->getMarkup()->getMarkupId(), 'Markup wrong'); $this->assertEquals(100, $newRate->getBaseRate(), 'Base rate wrong'); $this->assertEquals(200, $newRate->getMarkupRate(), 'Markup rate wrong'); $this->assertEquals(300, $newRate->getTotalRate(), 'Total rate wrong'); $this->assertEquals('test value 1', $newRate->getExtraData()->testparam1, 'Extra data #1 wrong'); $this->assertEquals('test value 2', $newRate->getExtraData()->testparam2, 'Extra data #2 wrong'); $this->assertEquals($methodName, $newRate->getMethodName(), 'getMethodName() returned wrong value'); }
public function testGetTotalRate() { $tax = \XLite\Core\Database::getRepo('XLite\\Module\\CDev\\VAT\\Model\\Tax')->getTax(); foreach ($tax->getRates() as $rate) { \XLite\Core\Database::getEM()->remove($rate); } $tax->getRates()->clear(); $tax->setEnabled(true); $rate = new \XLite\Module\CDev\VAT\Model\Tax\Rate(); $rate->setValue(10); $rate->setPosition(1); \XLite\Core\Database::getEM()->persist($rate); $tax->addRates($rate); $rate->setTax($tax); $rate = new \XLite\Module\CDev\VAT\Model\Tax\Rate(); $rate->setValue(20); $rate->setPosition(0); \XLite\Core\Database::getEM()->persist($rate); $tax->addRates($rate); $rate->setTax($tax); $memberships = \XLite\Core\Database::getRepo('XLite\\Model\\Membership')->findAll(); $membership = array_shift($memberships); $rate->setMembership($membership); $tax->setVATMembership($membership); \XLite\Core\Database::getEM()->flush(); $method = new \XLite\Model\Shipping\Method(); $method->setEnabled(true); $rate = new \XLite\Model\Shipping\Rate(); $rate->setBaseRate(10); $rate->setMarkupRate(10); $rate->setMethod($method); $this->assertEquals(16.67, \XLite::getInstance()->getCurrency()->formatValue($rate->getTotalRate()), 'check cost'); }
/** * Returns offline shipping rates * * @param \XLite\Logic\Order\Modifier\Shipping $modifier Shipping order modifier * @param boolean $ignoreCache Flag: if true then do not get rates from cache (not used in offline processor) OPTIONAL * * @return array */ public function getRates($modifier, $ignoreCache = false) { $rates = array(); if ($modifier instanceof \XLite\Logic\Order\Modifier\Shipping) { // Find markups for all enabled offline shipping methods $markups = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Markup')->findMarkupsByProcessor($this->getProcessorId(), $modifier); if (!empty($markups)) { // Create shipping rates list foreach ($markups as $markup) { $rate = new \XLite\Model\Shipping\Rate(); $rate->setMethod($markup->getShippingMethod()); $rate->setBaseRate(self::PROCESSOR_DEFAULT_BASE_RATE); $rate->setMarkup($markup); $rate->setMarkupRate($markup->getMarkupValue()); $rates[] = $rate; } } } // Return shipping rates list return $rates; }
/** * 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(); $availableMethods = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->findMethodsByProcessor($this->getProcessorId()); $currencyRate = doubleval(\XLite\Core\Config::getInstance()->CDev->AustraliaPost->currency_rate); $currencyRate = 0 < $currencyRate ?: 1; foreach ($availableMethods as $method) { $rate = null; $postFields = array('Service_Type' => $method->getCode(), 'Pickup_Postcode' => $data['srcAddress']['zipcode'], 'Destination_Postcode' => $data['dstAddress']['zipcode'], 'Country' => $data['dstAddress']['country'], 'Weight' => $data['weight'], 'Length' => \XLite\Core\Config::getInstance()->CDev->AustraliaPost->length, 'Width' => \XLite\Core\Config::getInstance()->CDev->AustraliaPost->width, 'Height' => \XLite\Core\Config::getInstance()->CDev->AustraliaPost->height, 'Quantity' => 1); $postData = array(); foreach ($postFields as $key => $value) { $postData[] = sprintf('%s=%s', $key, $value); } $postURL = $this->apiURL . '?' . implode('&', $postData); try { if (!$ignoreCache) { $cachedRate = $this->getDataFromCache($postURL); } if (isset($cachedRate)) { $result = $cachedRate; } else { $bouncer = new \XLite\Core\HTTP\Request($postURL); $bouncer->requestTimeout = 5; $response = $bouncer->sendRequest(); if (200 == $response->code) { $result = $response->body; $this->saveDataInCache($postURL, $result); } else { $this->errorMsg = sprintf('Error while connecting to the USPS host (%s)', $this->apiURL); break; } } $response = $this->parseResponse($result); $this->apiCommunicationLog[] = array('request' => $postURL, 'response' => isset($response['charge']) ? $response : $result); if ('OK' == $response['err_msg']) { $rate = new \XLite\Model\Shipping\Rate(); $rate->setMethod($method); $rate->setBaseRate($response['charge'] * $currencyRate); $extraData = new \XLite\Core\CommonCell(); $extraData->deliveryDays = $response['days']; $rate->setExtraData($extraData); } else { $this->errorMsg = $response['err_msg']; } } catch (\Exception $e) { $this->errorMsg = $e->getMessage(); break; } if (isset($rate)) { $rates[] = $rate; } } return $rates; }
/** * Returns rates array parsed from response * * @param array $response * * @return array */ protected function parseResponse($response) { $rates = array(); if (isset($response['ShipRate'])) { foreach ($response['ShipRate'] as $responseRate) { // UPS Next Day Air Early AM is a commercial only service. // Rather than ask you to implement differential code based // on the module Residential setting, lets just eliminate // this service method for the XS trial. // The two “Saturday” services have special handling in AuctionInc. // It would be best just to eliminate these two service methods as well for the XS trial $code = $responseRate['CarrierCode'] . '_' . $responseRate['ServiceCode']; if (!\XLite\Module\XC\AuctionInc\Main::isSSAvailable() && in_array($code, array('UPS_UPSNDE', 'FEDEX_FDXPOS', 'UPS_UPSNDAS'))) { continue; } $rate = new \XLite\Model\Shipping\Rate(); $rate->setBaseRate($responseRate['Rate']); $extraData = new \XLite\Core\CommonCell(array('auctionIncPackage' => $responseRate['PackageDetail'])); $rate->setExtraData($extraData); $method = $this->findMethod($responseRate['CarrierCode'], $responseRate['ServiceCode'], $responseRate['ServiceName']); if ($method && (\XLite\Module\XC\AuctionInc\Main::isSSAvailable() || $method->getEnabled())) { $rate->setMethod($method); $rates[] = $rate; } } } return $rates; }
/** * Restore rates * * @return \XLite\Model\Shipping\Rate[] */ protected function restoreRates() { $rates = array(); if ($this->order->getShippingId()) { /** @var \XLite\Model\Shipping\Method $method */ $method = \XLite\Core\Database::getRepo('XLite\\Model\\Shipping\\Method')->find($this->order->getShippingId()); if ($method) { $rate = new \XLite\Model\Shipping\Rate(); $rate->setMethod($method); $rate->setBaseRate(0); $rate->setMarkupRate($this->order->getSurchargeSumByType($this->type)); $rates[] = $rate; } } return $rates; }
/** * Map single quote * * @param mixed $quote Single quote line * * @return \XLite\Model\Shipping\Rate */ protected function mapSingleQuote($quote) { $rate = null; if (isset($quote->total->value)) { $rate = new \XLite\Model\Shipping\Rate(); $rate->setBaseRate($this->getBaseRate($quote)); $method = Processor\PitneyBowes::getMethod($this->getMethodCode($quote)); $rate->setMethod($method); $rate->setMarkupRate($this->getMarkupRate($quote)); if (isset($quote->totalTransportation->minDays) || isset($quote->totalTransportation->maxDays)) { $extraData = new \XLite\Core\CommonCell(); $extraData->deliveryMinDays = $quote->totalTransportation->minDays + intval($this->config->min_delivery_adjustment); $extraData->deliveryMaxDays = $quote->totalTransportation->maxDays + intval($this->config->max_delivery_adjustment); $rate->setExtraData($extraData); } } if (isset($quote->errors)) { foreach ($quote->errors as $error) { \XLite\Logger::logCustom("PitneyBowes", $error->error, false); } } return $rate; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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) { $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($xmlData); try { if (!$ignoreCache) { $cachedRate = $this->getDataFromCache($postURL); } if (isset($cachedRate)) { $result = $cachedRate; } else { $bouncer = new \XLite\Core\HTTP\Request($postURL); $bouncer->requestTimeout = 5; $response = $bouncer->sendRequest(); if (200 == $response->code) { $result = $response->body; $this->saveDataInCache($postURL, $result); } else { $this->errorMsg = sprintf('Error while connecting to the USPS host (%s)', $this->getApiURL()); } } if (!isset($this->errorMsg)) { $response = $this->parseResponse($result); } else { $response = array(); } $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 $this->addShippingMethod($postage); } elseif ($method->getEnabled()) { // Method is registered and enabled $rate->setMethod($method); $rate->setBaseRate($postage['Rate'] * $currencyRate); $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; }
/** * 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; }