/** * Request probe script * * @return void */ protected function requestProbe() { $url = \XLite::getInstance()->getShopURL(\XLite\Core\Converter::buildURL('', '', array('key' => \XLite\Core\Config::getInstance()->Internal->probe_key), 'probe.php')); set_time_limit(0); $request = new \XLite\Core\HTTP\Request($url); $response = $request->sendRequest(); if (200 != $response->code) { \XLite\Core\TopMessage::addError('Measuring productivity in manual mode failed.'); } }
/** * Returns access token based on authorization code * * @param string $code Authorization code * * @return string */ protected function getAccessToken($code) { $request = new \XLite\Core\HTTP\Request($this->getTokenRequestUrl($code)); $response = $request->sendRequest(); $accessToken = null; if (200 == $response->code) { parse_str($response->body, $data); $accessToken = $data['access_token']; } return $accessToken; }
/** * Returns access token based on authorization code * * @param string $code Authorization code * * @return string */ protected function getAccessToken($code) { $request = new \XLite\Core\HTTP\Request(static::TOKEN_REQUEST_URL); $request->body = array('code' => $code, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->getRedirectUrl(), 'grant_type' => 'authorization_code'); $response = $request->sendRequest(); $accessToken = null; if (200 == $response->code) { $data = json_decode($response->body, true); $accessToken = $data['access_token']; } return $accessToken; }
/** * Get URL content * * @param string $url URL * * @return string|void */ public static function getURLContent($url) { $result = null; if (ini_get('allow_url_fopen')) { $result = file_get_contents($url); } else { $bouncer = new \XLite\Core\HTTP\Request($url); $response = $bouncer->sendRequest(); if (200 == $response->code) { $result = $response->body; } } return $result; }
/** * Get publisher id * * @param string $email Email * * @return string */ public function getPublisherId($email) { $publisherId = null; $sellerName = \XLite\Core\Config::getInstance()->Company->company_name; $data = array('sellerName' => $sellerName, 'emailAddress' => $email, 'bnCode' => static::BN_CODE); $request = new \XLite\Core\HTTP\Request(static::END_POINT); if (function_exists('curl_version')) { $request->setAdditionalOption(\CURLOPT_SSLVERSION, 1); $curlVersion = curl_version(); if ($curlVersion && $curlVersion['ssl_version'] && 0 !== strpos($curlVersion['ssl_version'], 'NSS')) { $request->setAdditionalOption(\CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); } } $request->body = json_encode($data); $request->verb = 'POST'; $timeStamp = LC_START_TIME . '000'; $authorization = 'FPA ' . static::CLIENT_KEY; $authorization .= ':' . sha1(static::SHARED_SECRET . $timeStamp); $authorization .= ':' . $timeStamp; $request->setHeader('Authorization', $authorization); $request->setHeader('Accept', 'application/json'); $request->setHeader('Content-Type', 'application/json'); $response = $request->sendRequest(); \XLite\Module\CDev\Paypal\Main::addLog('getPublisherId', $response->body); if (201 == $response->code) { $responseData = json_decode($response->body, true); if ($responseData && isset($responseData['publisherId'])) { $publisherId = $responseData['publisherId']; } } return $publisherId; }
/** * Place URL into engine's endpoints * * @return void */ protected function doActionLocate() { $engines = \XLite\Core\Request::getInstance()->engines; if ($engines) { foreach ($this->getEngines() as $key => $engine) { if (in_array($key, $engines)) { $url = urlencode(\XLite::getInstance()->getShopURL(\XLite\Core\Converter::buildURL('sitemap', '', array(), \XLite::CART_SELF))); $url = str_replace('%url%', $url, $engine['url']); $request = new \XLite\Core\HTTP\Request($url); $response = $request->sendRequest(); if (200 == $response->code) { \XLite\Core\TopMessage::addInfo('Site map successfully registred on X', array('engine' => $key)); } else { \XLite\Core\TopMessage::addWarning('Site map has not been registred in X', array('engine' => $key)); } } } } }
/** * Place URL into engine's endpoints * * @return void */ protected function doActionLocate() { $engines = \XLite\Core\Request::getInstance()->engines; if ($engines) { foreach ($this->getEngines() as $key => $engine) { if (in_array($key, $engines)) { $url = urlencode(\XLite::getInstance()->getShopURL(\XLite\Core\Converter::buildURL('sitemap', '', array(), \XLite::getCustomerScript()))); $url = str_replace('%url%', $url, $engine['url']); $request = new \XLite\Core\HTTP\Request($url); $response = $request->sendRequest(); if (200 == $response->code) { \XLite\Core\TopMessage::addInfo('Site map successfully registred on X', array('engine' => $key)); } else { \XLite\Core\TopMessage::addWarning('Site map has not been registred in X', array('engine' => $key)); } } } } $postedData = \XLite\Core\Request::getInstance()->getData(); $options = \XLite\Core\Database::getRepo('\\XLite\\Model\\Config')->findBy(array('category' => $this->getOptionsCategory())); $isUpdated = false; foreach ($options as $key => $option) { $name = $option->getName(); $type = $option->getType(); if (isset($postedData[$name]) || 'checkbox' == $type) { if ('checkbox' == $type) { $option->setValue(isset($postedData[$name]) ? 'Y' : 'N'); } else { $option->setValue($postedData[$name]); } $isUpdated = true; \XLite\Core\Database::getEM()->persist($option); } } if ($isUpdated) { \XLite\Core\Database::getEM()->flush(); } }
/** * Send GET/POST data through sockets * * @param string $url * @param string $data * @param integer $timeout * * @return string */ protected function postToHost($url, $data) { $request = new \XLite\Core\HTTP\Request($url); $request->body = $data; $response = $request->sendRequest(); // Log request/response \XLite\Module\XC\IdealPayments\Main::addLog('Post request and response', array('request' => array('url' => $url, 'data' => $data), 'response' => '200' == $response->code ? $response->body : $response)); $result = ''; if ($response->code != '200') { $this->setError('Error while connecting to ' . $url, false, __FILE__, __LINE__); } else { $result = $response->body; } return $result; }
/** * Get IPN verification status * * @return boolean TRUE if verification status is received */ protected function getIPNVerification() { $ipnRequest = new \XLite\Core\HTTP\Request($this->getIPNURL()); $ipnRequest->body = \XLite\Core\Request::getInstance()->getData(); $ipnResult = $ipnRequest->sendRequest(); if ($ipnResult) { $result = 0 < preg_match('/VERIFIED/i', $ipnResult->body) ? self::IPN_VERIFIED : self::IPN_DECLINED; } else { $result = self::IPN_REQUEST_ERROR; $this->setDetail('ipn_http_error', 'IPN HTTP error:'); } return $result; }
/** * Validate secret word * * @return void */ protected function doActionValidateSecretWord() { $secretWord = trim(\XLite\Core\Request::getInstance()->secret_word); $secret = md5(md5($secretWord) . md5(\XLite\Module\CDev\Moneybookers\Model\Payment\Processor\Moneybookers::getPlatformSecretWord())); $platformId = \XLite\Module\CDev\Moneybookers\Model\Payment\Processor\Moneybookers::getPlatformCustomerID(); $request = new \XLite\Core\HTTP\Request('https://www.skrill.com/app/secret_word_check.pl' . '?secret=' . $secret . '&email=' . urlencode(\XLite\Core\Config::getInstance()->CDev->Moneybookers->email) . '&cust_id=' . $platformId); $response = $request->sendRequest(); if (200 == $response->code && 'OK' == $response->body) { \XLite\Core\Database::getRepo('\\XLite\\Model\\Config')->createOption(array('category' => 'CDev\\Moneybookers', 'name' => 'secret_word', 'value' => $secretWord)); \XLite\Core\TopMessage::getInstance()->add('Secret word is valid'); } elseif ('VELOCITY_CHECK_EXCEEDED' == $response->body) { \XLite\Core\TopMessage::getInstance()->add('Maximum number of checks for a particular user has been reached' . ' (currently set to 3 per user per hour)', array(), null, \XLite\Core\TopMessage::ERROR); } elseif ('REQUESTER_NOT_AUTHORISED' == $response->body) { \XLite\Core\TopMessage::getInstance()->add('Requestor\'s account not authorised to run the secret word check', array(), null, \XLite\Core\TopMessage::ERROR); } else { \XLite\Core\TopMessage::getInstance()->add('Secret word is not valid', array(), null, \XLite\Core\TopMessage::ERROR); } }
/** * Return prepared request object * * @param string $action Action name * @param array $data Request data OPTIONAL * * @return \XLite\Core\HTTP\Request */ protected function getRequest($action, array $data = array()) { $url = $this->getMarketplaceActionURL($action); $data += $this->getRequestCommonData(); $request = new \XLite\Core\HTTP\Request($url); $request->body = $data; if (function_exists('curl_version')) { $request->setAdditionalOption(\CURLOPT_SSLVERSION, 1); $curlVersion = curl_version(); if ($curlVersion && $curlVersion['ssl_version'] && 0 !== strpos($curlVersion['ssl_version'], 'NSS')) { $request->setAdditionalOption(\CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); } } if (in_array($action, static::getLongActions())) { $request->requestTimeout = static::REQUEST_LONG_TTL; } else { $request->requestTimeout = static::REQUEST_TTL; } $this->logInfo($action, 'The "{{url}}" URL requested', array('url' => $url), $data); return $request; }
/** * Get Moneybookers session id * * @return string */ protected function getSessionId() { $data = array('pay_to_email' => \XLite\Core\Config::getInstance()->CDev->Moneybookers->email, 'language' => $this->getLanguageCode(), 'recipient_description' => substr(\XLite\Core\Config::getInstance()->Company->company_name, 0, 30), 'transaction_id' => \XLite\Core\Config::getInstance()->CDev->Moneybookers->prefix . $this->transaction->getTransactionId(), 'pay_from_email' => $this->getProfile()->getLogin(), 'firstname' => $this->getProfile()->getBillingAddress()->getFirstname(), 'lastname' => $this->getProfile()->getBillingAddress()->getLastname(), 'address' => $this->getProfile()->getBillingAddress()->getStreet(), 'postal_code' => $this->getProfile()->getBillingAddress()->getZipcode(), 'city' => $this->getProfile()->getBillingAddress()->getCity(), 'country' => $this->getCountryCode(), 'amount' => $this->getOrder()->getCurrency()->roundValue($this->transaction->getValue()), 'currency' => $this->getCurrencyCode(), 'status_url' => $this->getCallbackURL(null, true), 'return_url' => $this->getReturnURL(null, true), 'cancel_url' => $this->getReturnURL(null, true, true), 'hide_login' => 1, 'prepare_only' => 1, 'payment_methods' => $this->convertServiceNameToType($this->transaction->getPaymentMethod()->getServiceName()), 'merchant_fields' => 'platform', 'platform' => '21889079'); if (\XLite\Core\Config::getInstance()->CDev->Moneybookers->logo_url) { $data['logo_url'] = \XLite\Core\Config::getInstance()->CDev->Moneybookers->logo_url; } $this->transaction->setPublicId($data['transaction_id']); $request = new \XLite\Core\HTTP\Request($this->getPostURL()); $request->body = $data; $response = $request->sendRequest(); $id = null; if (200 == $response->code && preg_match('/SESSION_ID=([a-z0-9]+)/iSs', $response->headers->SetCookie, $match) && $response->body == $match[1]) { $id = $match[1]; } elseif (200 != $response->code) { $this->setDetail('moneybookers_session_error', 'Moneybookers payment processor did not receive session ID successfull' . ' (HTTP error: ' . $response->code . ').', 'Session initialization error'); } elseif (preg_match('/SESSION_ID=([a-z0-9]+)/iSs', $response->headers->SetCookie, $match)) { $this->setDetail('moneybookers_session_error', 'Moneybookers payment processor did not receive session ID successfull (page body has not session ID).', 'Session initialization error'); } else { $this->setDetail('moneybookers_session_error', 'Moneybookers payment processor did not receive session ID successfull.', 'Session initialization error'); } if (!$id && preg_match('/<h1[^>]*>(.+)<\\/h1>/USs', $response->body, $m1) && preg_match('/<div class="gateway_content">(.+)<\\/div>/USs', $response->body, $m2)) { $m1 = trim($m1[1]); $m2 = trim(strip_tags($m2[1])); $this->setDetail('moneybookers_session_error', $m1 . ': ' . $m2, 'Session initialization error'); } return $id; }
/** * 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; }
/** * Verify value as file * * @param mixed @value Value * * @return boolean */ protected function verifyValueAsFile($value) { // Do not verify files in verification mode and if 'ignoreFileChecking' option is true if (!$this->isVerification() || !$this->importer->getOptions()->ignoreFileChecking) { if (1 < count(parse_url($value))) { $request = new \XLite\Core\HTTP\Request($value); $response = $request->sendRequest(); $result = $response && 200 == $response->code; } else { $dir = \Includes\Utils\FileManager::getRealPath(LC_DIR_VAR . $this->importer->getOptions()->dir); $result = \Includes\Utils\FileManager::isReadable($dir . LC_DS . $value); } } else { $result = true; } return $result; }
/** * Get IPN verification status * * @return boolean TRUE if verification status is received */ protected function getIPNVerification() { $ipnRequest = new \XLite\Core\HTTP\Request($this->getIPNURL()); if (function_exists('curl_version')) { $ipnRequest->setAdditionalOption(\CURLOPT_SSLVERSION, 1); $curlVersion = curl_version(); if ($curlVersion && $curlVersion['ssl_version'] && 0 !== strpos($curlVersion['ssl_version'], 'NSS')) { $ipnRequest->setAdditionalOption(\CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); } } $ipnRequest->body = \XLite\Core\Request::getInstance()->getData(); $ipnResult = $ipnRequest->sendRequest(); if ($ipnResult) { \XLite\Module\CDev\Paypal\Main::addLog('getIPNVerification()', $ipnResult->body); $result = 0 < preg_match('/VERIFIED/i', $ipnResult->body) ? self::IPN_VERIFIED : self::IPN_DECLINED; } else { $result = self::IPN_REQUEST_ERROR; } return $result; }
/** * 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 * * 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; }
/** * Returns new request object * * @param string $type Request type * @param array $params Request params * * @return \XLite\Core\HTTP\Request */ protected function createRequest($type, $params) { $this->response = null; $request = new \XLite\Core\HTTP\Request($this->createUrl($type, $params)); if (function_exists('curl_version')) { $request->setAdditionalOption(\CURLOPT_SSLVERSION, 1); $curlVersion = curl_version(); if ($curlVersion && $curlVersion['ssl_version'] && 0 !== strpos($curlVersion['ssl_version'], 'NSS')) { $request->setAdditionalOption(\CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); } } $request->body = $this->prepareParams($type, $params); $request->verb = 'POST'; $request = $this->prepareRequest($request, $type, $params); return $request; }
public static function func_amazon_pa_request($action, $data) { if (\XLite\Core\Config::getInstance()->Amazon->PayWithAmazon->amazon_pa_currency == 'USD') { $urlHost = 'mws.amazonservices.com'; } else { $urlHost = 'mws-eu.amazonservices.com'; } if (\XLite\Core\Config::getInstance()->Amazon->PayWithAmazon->amazon_pa_mode == 'test') { $urlUri = '/OffAmazonPayments_Sandbox/2013-01-01'; } else { $urlUri = '/OffAmazonPayments/2013-01-01'; } $params = array('AWSAccessKeyId=' . \XLite\Core\Config::getInstance()->Amazon->PayWithAmazon->amazon_pa_access_key, 'Action=' . $action, 'SellerId=' . \XLite\Core\Config::getInstance()->Amazon->PayWithAmazon->amazon_pa_sid, 'SignatureMethod=HmacSHA256', 'SignatureVersion=2', 'Timestamp=' . urlencode(date('c'))); foreach ($data as $k => $v) { $params[] = "{$k}={$v}"; } sort($params); // sign request $concatParams = implode('&', $params); $str2sign = "POST\n{$urlHost}\n{$urlUri}\n" . $concatParams; $signature = self::func_amazon_pa_sign($str2sign); $concatParams .= '&Signature=' . urlencode($signature); // send request self::func_amazon_pa_debug("send request={$urlHost}{$urlUri}?{$concatParams}"); $request = new \XLite\Core\HTTP\Request("https://{$urlHost}{$urlUri}"); $request->body = $concatParams; $request->verb = 'POST'; $response = $request->sendRequest(); if (200 == $response->code && !empty($response->body)) { $reply = $response->body; } else { self::func_amazon_pa_error("Empty or wrong response received. Reply code=" . $response->code . " response body=" . $response->body); return false; } self::func_amazon_pa_debug($reply, true); $parse_error = array(); $res = self::func_xml_parse($reply, $parse_error); if (!$res) { self::func_amazon_pa_error("Can not parse XML reply: " . print_r($parse_error, true)); } return $res; }
/** * 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; }
/** * Defines if the clean urls can be enabled on the current server environment * * @return boolean */ public function canEnableCleanURL() { $urlToCheck = \XLite::getInstance()->getShopURL() . \XLite::CLEAN_URL_CHECK_QUERY; $request = new \XLite\Core\HTTP\Request($urlToCheck); $request->setAdditionalOption(\CURLOPT_SSL_VERIFYPEER, false); $request->setAdditionalOption(\CURLOPT_SSL_VERIFYHOST, false); $this->curlResponse = $request->sendRequest(); return !$this->isCleanURLEnabled() && $this->curlResponse && in_array($this->curlResponse->code, array(200, 301, 302)); }
/** * Get IPN verification status * * @return boolean TRUE if verification status is received */ protected function getIPNVerification() { $ipnRequest = new \XLite\Core\HTTP\Request($this->getIPNURL()); $ipnRequest->body = \XLite\Core\Request::getInstance()->getData(); $ipnResult = $ipnRequest->sendRequest(); if ($ipnResult) { \XLite\Module\CDev\Paypal\Main::addLog('getIPNVerification()', $ipnResult->body); $result = 0 < preg_match('/VERIFIED/i', $ipnResult->body) ? self::IPN_VERIFIED : self::IPN_DECLINED; } else { $result = self::IPN_REQUEST_ERROR; } return $result; }
/** * Check if file exists * * @param string $path Path to check OPTIONAL * @param boolean $forceFile Flag OPTIONAL * * @return boolean */ public function isFileExists($path = null, $forceFile = false) { if ($this->isURL($path) && !$forceFile) { $request = new \XLite\Core\HTTP\Request($path ?: $this->getPath()); $response = $request->sendRequest(); $exists = 200 == $response->code && !empty($response->headers->ContentLength); } else { $exists = \Includes\Utils\FileManager::isFileReadable($path ?: $this->getStoragePath()); } return $exists; }
/** * Does an Ecwid API call * * @param string $apiMethod API method name to call * @param string $params Parameters to pass along OPTIONAL * * @return array * @throws Exception */ public function callApi($apiMethod, $params = array()) { $time = microtime(true); $lastTime = \XLite\Core\Database::getRepo('XLite\\Model\\TmpVar')->getVar(static::TMP_VAR_NAME); if ($lastTime && $lastTime + static::RATE_LIMIT > $time) { $delay = $lastTime + static::RATE_LIMIT - $time; usleep(round($delay * 1000000)); } $url = 'http://app.ecwid.com/api/v1/' . $this->getStoreId() . '/' . $apiMethod . ($params ? '?' . http_build_query($params) : ''); $bouncer = new \XLite\Core\HTTP\Request($url); $bouncer->requestTimeout = 60; $response = $bouncer->sendRequest(); $result = null; \XLite\Core\Database::getRepo('XLite\\Model\\TmpVar')->setVar(static::TMP_VAR_NAME, microtime(true)); if (200 == $response->code) { $result = json_decode($response->body, true); } else { throw new \Exception('Call to \'' . $url . '\' failed with \'' . $response->code . '\' code'); } return $result; }
/** * Call "Get Service" request * * Reason to Call: * To find out details for a given postal service such as the dimension and weight limits and the available options. * * @param string $endpoint Service endpoint (URL) * @param string $acceptHeader Accept header value * * @return \XLite\Core\CommonCell */ protected function callGetService($endpoint, $acceptHeader) { $result = new \XLite\Core\CommonCell(); try { $request = new \XLite\Core\HTTP\Request($endpoint); $request->requestTimeout = $this->requestTimeout; $request->verb = 'GET'; $request->setHeader('Authorization', 'Basic ' . base64_encode(static::getCanadaPostConfig()->user . ':' . static::getCanadaPostConfig()->password)); $request->setHeader('Accept', $acceptHeader); $request->setHeader('Accept-language', $this->getAcceptLanguage()); if (static::isOnBehalfOfAMerchant()) { $request->setHeader('Platform-id', $this->getPlatformId()); } $response = $request->sendRequest(); if (isset($response->body) && !empty($response->body)) { // Parse XML response to object $result = $this->parseResponseGetService($response->body); } else { // Register request error $result->errors = array($this->createErrorMessage('INTERNAL', sprintf('Error while connecting to the Canada Post host (%s) during "Get Service" request', $endpoint))); } if (static::getCanadaPostConfig()->debug_enabled) { // Save debug log static::logApiCall($endpoint, 'Get Service', '', $response->body); } } catch (\Exception $e) { // Register exception error $errorMessage = $this->createErrorMessage($this->getCode(), $this->getMessage()); $result->errors = array_merge((array) $result->errors, array($errorMessage)); } return $result; }
/** * 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; }
/** * Call "Get Manifest" request * * Reason to Call: * To retrieve the set of information links for a particular manifest that was previously created as part of Transmit Shipments. * * More info at: * https://www.canadapost.ca/cpo/mc/business/productsservices/developers/services/shippingmanifest/manifest.jsf * * @param \XLite\Module\XC\CanadaPost\Model\Order\Parcel\Manifest $manifest Manifest object * * @return \XLite\Core\CommonCell */ public function callGetManifestRequest(\XLite\Module\XC\CanadaPost\Model\Order\Parcel\Manifest $manifest) { $apiHost = $manifest->getHref(); $result = new \XLite\Core\CommonCell(); try { $request = new \XLite\Core\HTTP\Request($apiHost); $request->requestTimeout = $this->requestTimeout; $request->verb = 'GET'; $request->setHeader('Authorization', 'Basic ' . base64_encode(static::getCanadaPostConfig()->user . ':' . static::getCanadaPostConfig()->password)); $request->setHeader('Accept', 'application/vnd.cpc.manifest-v5+xml'); $request->setHeader('Accept-language', static::ACCEPT_LANGUAGE_EN); if (static::isOnBehalfOfAMerchant()) { $request->setHeader('Platform-id', $this->getPlatformId()); } $response = $request->sendRequest(); if (isset($response->body) && !empty($response->body)) { // Parse response to object $result = $this->parseResponse($response->body); } else { $result->errors = array('INTERNAL' => sprintf('Error while connecting to the Canada Post host (%s) during Get Manifest request', $apiHost)); } if (static::getCanadaPostConfig()->debug_enabled) { // Save debug log static::logApiCall($apiHost, 'Get Manifest', '', $response->body); } } catch (\Exception $e) { if (!isset($result->errors)) { $result->errors = array(); } $result->errors += array($e->getCode(), $e->getMessage()); } return $result; }
/** * 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; }
/** * 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; }
/** * Process authorization grant and return array with profile data * * @return array Client information containing at least id and e-mail */ public function processAuth() { $profile = array(); $code = \XLite\Core\Request::getInstance()->code; if (!empty($code)) { $accessToken = $this->getAccessToken($code); if ($accessToken) { $request = new \XLite\Core\HTTP\Request($this->getProfileRequestUrl($accessToken)); $response = $request->sendRequest(); if (200 == $response->code) { $profile = json_decode($response->body, true); } } } return $profile; }