Ejemplo n.º 1
0
 /**
  * license the app
  * 
  */
 public static function license($activationKey, $productToken)
 {
     $url = 'https://ls.amazonaws.com/';
     $client = new Varien_Http_Client($url);
     $client->setMethod(Zend_Http_Client::GET);
     $client->setParameterGet("Action", "ActivateDesktopProduct");
     $client->setParameterGet("ActivationKey", $activationKey);
     $client->setParameterGet("ProductToken", $productToken);
     $response = $client->request();
     if ($response->isSuccessful()) {
         $body = $response->getRawBody();
         $xml = new SimpleXMLElement($body);
         $result = array();
         $result["access"] = $xml->ActivateDesktopProductResult->AWSAccessKeyId;
         $result["secret"] = $xml->ActivateDesktopProductResult->SecretAccessKey;
         $result["usertoken"] = $xml->ActivateDesktopProductResult->UserToken;
         // uncomment to debug raw submission response
         //Mage::log("result=" . print_r($result,true));
         return $result;
     } else {
         Mage::log("Activation failed to URL: " . $url . ", HTTP response code was not 200");
         Mage::log("Raw response: " . print_r($response, true));
         return false;
     }
 }
Ejemplo n.º 2
0
 /**
  * run synchronize customer to Magestore
  */
 public function indexAction()
 {
     // Turn Off
     die('x');
     $session = Mage::getSingleton('core/session');
     $limit = $this->getRequest()->getParam('limit', 10);
     $start = (int) $session->getLastAccountId();
     // Customer info
     $customers = Mage::getResourceModel('customer/customer_collection');
     $customers->addFieldToFilter('entity_id', array('gt' => $start))->addAttributeToSelect('email')->addAttributeToSelect('firstname')->addAttributeToSelect('lastname')->addAttributeToSelect('password_hash')->getSelect()->limit($limit)->order('entity_id ASC');
     if (!$customers->count()) {
         echo '0';
         return;
     }
     $customerData = array();
     foreach ($customers as $customer) {
         $customerData[] = array('email' => $customer->getEmail(), 'firstname' => $customer->getFirstname(), 'lastname' => $customer->getLastname(), 'password_hash' => $customer->getPasswordHash());
         $start = $customer->getId();
     }
     // Run query
     $url = Mage::getStoreConfig('subsystem/general/account') . 'add';
     $client = new Varien_Http_Client($url);
     $client->setParameterPost('pk', Magestore_Subsystem_Model_Observer::PK);
     $client->setParameterPost('data', Zend_Json::encode($customerData));
     $response = $client->request(Varien_Http_Client::POST);
     // Update start to session
     $session->setLastAccountId($start);
     echo $start;
     echo '<br>' . $response->getBody();
 }
Ejemplo n.º 3
0
 function queryMaxMind($params)
 {
     $servers = array("http://minfraud1.maxmind.com", "http://minfraud2.maxmind.com");
     $return = array();
     $error = false;
     foreach ($servers as $server) {
         $http = new Varien_Http_Client($server . "/app/ccv2r");
         $http->setParameterPost($params);
         try {
             $response = $http->request('POST');
         } catch (Exception $e) {
             continue;
         }
         if ($response->getStatus() != '200') {
             continue;
         }
         foreach (explode(";", $response->getBody()) as $keyval) {
             $bits = explode("=", $keyval);
             if (count($bits) > 1) {
                 list($key, $value) = $bits;
                 $return[$key] = $value;
             }
         }
         if (!empty($return)) {
             break;
         }
     }
     if (empty($return)) {
         $return['errmsg'] = "Could not contact MaxMind servers.";
         $return['err'] = "FATAL_ERROR";
     }
     return $return;
 }
 /**
  * Create an api request and inject the app token.
  *
  * @param string Path to the rest method being called
  * @param string Request method: GET, POST, PUT or DELETE
  * @param mixed An array of parameters or raw post data.  Raw data isn't accepted for GET.
  * @return null
  * @throws Exception Invalid or failed requests throw exceptions.
  */
 protected function apiCall($path, $requestMethod, $params = array())
 {
     $requestMethod = strtoupper($requestMethod);
     switch ($requestMethod) {
         case 'GET':
             $setParamMethod = 'setParameterGet';
             if (!is_array($params)) {
                 throw new Exception('GET parameters can\'t be provided as raw data.');
             }
             break;
         case 'POST':
         case 'PUT':
         case 'DELETE':
             $setParamMethod = 'setParameterPost';
             break;
         default:
             throw new Exception('Invalid request method');
     }
     $client = new Varien_Http_Client($this->serverLocation . $path);
     $client->setMethod($requestMethod);
     if (is_array($params)) {
         foreach ($params as $paramKey => $paramValue) {
             call_user_func(array($client, $setParamMethod), $paramKey, $paramValue);
         }
     } else {
         $client->setRawData($params);
     }
     $response = $client->request();
     if ($response->isSuccessful()) {
         return json_decode($response->getBody());
     } else {
         throw new Exception('Request failed');
     }
 }
 /**
  * Only executed if sendOrderStatus validates true for orderStatuses, order data and API data is fetched
  * URL is then formed and sent as a GET request, response is then decoded with boolean values. Exception 
  * thrown if the request cannot be successfully made. Warning thrown if connection is successfully but
  * credentials are not correct
  *
  * @param $order
  * @param $orderStatus
  * @throws throwException
  */
 public function executeApiCall($order, $orderStatus)
 {
     $apiUrl = Mage::helper('orderstatus')->getApiUrl();
     $apiServiceName = Mage::helper('orderstatus')->getApiServiceName();
     $apiUsername = Mage::helper('orderstatus')->getApiUsername();
     $apiPassword = Mage::helper('orderstatus')->getApiPassword();
     $apiMethod = Mage::helper('orderstatus')->getApiMethod();
     $apiDebuggingEnabled = Mage::helper('orderstatus')->isDebuggingEnabled();
     $orderNumber = $order->getIncrementId();
     $orderDateStatusChanged = $order->getUpdatedAt();
     $orderStatus = $orderStatus;
     $apiRequest = $apiUrl . $apiMethod . "?service=" . $apiServiceName . "&username="******"&password="******"&orderno=" . $orderNumber . "&date=" . str_replace(" ", "_", $orderDateStatusChanged) . "&status=" . $orderStatus;
     try {
         $client = new Varien_Http_Client($apiRequest);
         $client->setMethod(Varien_Http_Client::GET);
         $response = $client->request();
         if ($apiDebuggingEnabled) {
             Mage::getSingleton('adminhtml/session')->addWarning("API Request : " . $apiRequest);
             Mage::getSingleton('adminhtml/session')->addWarning("API Response : " . $response->getBody());
         }
         if ($response->isSuccessful()) {
             Mage::getSingleton('adminhtml/session')->addSuccess('Touch Retail API connection was successful.');
             $responseJson = json_decode($response->getBody());
             if ($responseJson->serviceresult->success == 1) {
                 Mage::getSingleton('adminhtml/session')->addSuccess('Order status was successfully sent to Touch Retail.');
             } else {
                 Mage::getSingleton('adminhtml/session')->addWarning('Unable to send order status to Touch Retail, please check your API method System > Configuration menu.');
             }
         } else {
             Mage::getSingleton('adminhtml/session')->addWarning('Unable to connect to Touch Retail, please check your API credentials in System > Configuration menu.');
         }
     } catch (Exception $e) {
         Mage::throwException('Unable to send your API request, this maybe due to a malformed URL.');
     }
 }
Ejemplo n.º 6
0
 /**
  * @param array $data Array of each installed Fontis extensions version
  * @return string
  * @throws Exception
  */
 public function request($data)
 {
     $client = new Varien_Http_Client(Mage::helper('fontis_info')->getInfoUrl(), array('keepalive' => true));
     $client->setParameterPost('data', $data);
     // If we accept gzip encoding and the response isn't actually chunked, Zend_Http_Response will throw
     // an exception. Unfortunately, this means we can't use gzip encoded responses at this time.
     $client->setHeaders('Accept-encoding', 'identity');
     $response = $client->request(Varien_Http_Client::POST);
     if ($response->isError()) {
         // if the request fails, throw an exception
         throw new Exception('Error getting info data: ' . $response->getStatus() . ' ' . $response->getMessage());
     }
     return $response->getBody();
 }
Ejemplo n.º 7
0
 /**
  * Retrieve js scripts by parsing remote Google Optimizer page
  */
 public function codesAction()
 {
     if ($this->getRequest()->getQuery('url')) {
         $client = new Varien_Http_Client($this->getRequest()->getQuery('url'));
         $response = $client->request(Varien_Http_Client::GET);
         $result = array();
         if (preg_match_all('/<textarea[^>]*id="([_a-zA-Z0-9]+)"[^>]*>([^<]+)<\\/textarea>/', $response->getRawBody(), $matches)) {
             $c = count($matches[1]);
             for ($i = 0; $i < $c; $i++) {
                 $id = $matches[1][$i];
                 $code = $matches[2][$i];
                 $result[$id] = $code;
             }
         }
         $this->getResponse()->setBody(Zend_Json::encode($result));
     }
 }
Ejemplo n.º 8
0
 /**
  * Verify installation id in Worldpay registration system to reduce configuration failures (experimental)
  *
  * @return Phoenix_Worldpay_Model_Config_Backend_Instid
  */
 protected function _beforeSave()
 {
     try {
         if ($this->getValue()) {
             $client = new Varien_Http_Client();
             $client->setUri((string) Mage::getConfig()->getNode('phoenix/worldpay/verify_url'))->setConfig(array('timeout' => 10))->setHeaders('accept-encoding', '')->setParameterPost('inst_id', $this->getValue())->setMethod(Zend_Http_Client::POST);
             $response = $client->request();
             //                $responseBody = $response->getBody();
             //                if (empty($responseBody) || $responseBody != 'VERIFIED') {
             // verification failed. throw error message (not implemented yet).
             //                }
             // okay, inst_id verified. continue saving.
         }
     } catch (Exception $e) {
         // verification system unavailable. no further action.
     }
     return parent::_beforeSave();
 }
Ejemplo n.º 9
0
 public function SendRequest($topic, $orderId, $customerId, $productId = 0, $categoryId = 0, $quoteId = 0)
 {
     $affiliate = 0;
     $client = new Varien_Http_Client();
     $company_app_name = $this->getStoreConfig('revenueconduit_app_name');
     $store_name = $this->getStoreConfig('revenueconduit_store_name');
     $storeId = Mage::app()->getStore()->getStoreId();
     $url = Mage::getStoreConfig('web/unsecure/base_link_url', $storeId);
     $host = "https://app.revenueconduit.com/magento_incoming_requests/receive";
     $parameter = array("company_app_name" => $company_app_name, "store_name" => $store_name, 'domain' => $url);
     if (!empty($_COOKIE) && array_key_exists('affiliate', $_COOKIE)) {
         $affiliate = $_COOKIE['affiliate'];
     }
     $postParameters = array("topic" => $topic, "order_id" => $orderId, "customer_id" => $customerId, "product_id" => $productId, 'category_id' => $categoryId, 'referral_code_id' => $affiliate ? $affiliate : 0, 'quote_id' => $quoteId);
     $client->setUri($host)->setConfig(array('timeout' => 30))->setParameterGet($parameter)->setParameterPost($postParameters)->setUrlEncodeBody(false)->setMethod(Zend_Http_Client::POST);
     try {
         $response = $client->request();
         return $response->getBody();
     } catch (Exception $e) {
         Mage::log("Could not send the {$topic} request to RevenueConduit. Error Message: " . $e->getMessage(), null);
     }
     return null;
 }
 /**
  * Return some checking result
  *
  * @return void
  */
 public function checkAction()
 {
     $apiUrl = Mage::helper('orderstatus')->getApiUrl();
     $apiServiceName = Mage::helper('orderstatus')->getApiServiceName();
     $apiUsername = Mage::helper('orderstatus')->getApiUsername();
     $apiPassword = Mage::helper('orderstatus')->getApiPassword();
     $apiMethod = Mage::helper('orderstatus')->getApiMethod();
     $apiDebuggingEnabled = Mage::helper('orderstatus')->isDebuggingEnabled();
     $apiRequest = $apiUrl . $apiMethod . "?service=" . $apiServiceName . "&username="******"&password="******"API Request : " . $apiRequest);
             Mage::getSingleton('adminhtml/session')->addWarning("API Response : " . $response->getBody());
         }
         if ($response->isSuccessful()) {
             Mage::getSingleton('adminhtml/session')->addSuccess('Touch Retail API connection was successful.');
             $responseJson = json_decode($response->getBody());
             if ($responseJson->serviceresult && $responseJson->serviceresult->success == 1) {
                 Mage::getSingleton('adminhtml/session')->addSuccess('Touch Retail API credentials are valid.');
                 Mage::app()->getResponse()->setBody($responseJson->serviceresult->success);
             } else {
                 Mage::getSingleton('adminhtml/session')->addwarning('Touch Retail API credentials are invalid.');
                 Mage::app()->getResponse()->setBody($responseJson->serviceresult->errormessage);
             }
         } else {
             Mage::getSingleton('adminhtml/session')->addWarning('Unable to connect to Touch Retail, please check your API credentials .');
             Mage::app()->getResponse()->setBody($responseJson->serviceresult->errormessage);
         }
     } catch (Exception $e) {
         Mage::throwException('Unable to send your API request, this maybe due to a malformed URL.');
     }
 }
Ejemplo n.º 11
0
 /**
  * Veritfy the gateway response
  *
  * @param string $apiKey
  * @param string $token
  * @param string $timestamp
  * @param string $signature
  * @return boolean
  */
 public function _verifyResponse($purchase_id)
 {
     $client_id = Mage::helper('sign2pay')->getSign2payClientId();
     $client_secret = Mage::helper('sign2pay')->getSign2payClientSecret();
     $client = new Varien_Http_Client('https://app.sign2pay.com/api/v2/payment/status/' . $purchase_id);
     $client->setMethod(Varien_Http_Client::GET);
     $client->setAuth($client_id, $client_secret);
     try {
         $response = $client->request();
         $body = json_decode($response->getBody());
         if (array_key_exists('status', $body) || $body['status'] == 'processing') {
             return true;
         } else {
             return false;
         }
     } catch (Zend_Http_Client_Exception $e) {
         Mage::logException($e);
         return false;
     }
 }
Ejemplo n.º 12
0
 protected function _postRequest(Varien_Object $request)
 {
     $debugData = array('request' => $request->getData());
     $result = Mage::getModel('paygate/authorizenet_result');
     $client = new Varien_Http_Client();
     $uri = $this->getConfigData('cgi_url');
     $client->setUri($uri ? $uri : self::CGI_URL);
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->setParameterPost($request->getData());
     $client->setMethod(Zend_Http_Client::POST);
     try {
         $response = $client->request();
     } catch (Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         $debugData['result'] = $result->getData();
         $this->_debug($debugData);
         Mage::throwException($this->_wrapGatewayError($e->getMessage()));
     }
     $responseBody = $response->getBody();
     $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
     if ($r) {
         $result->setResponseCode((int) str_replace('"', '', $r[0]))->setResponseSubcode((int) str_replace('"', '', $r[1]))->setResponseReasonCode((int) str_replace('"', '', $r[2]))->setResponseReasonText($r[3])->setApprovalCode($r[4])->setAvsResultCode($r[5])->setTransactionId($r[6])->setInvoiceNumber($r[7])->setDescription($r[8])->setAmount($r[9])->setMethod($r[10])->setTransactionType($r[11])->setCustomerId($r[12])->setMd5Hash($r[37])->setCardCodeResponseCode($r[38])->setCAVVResponseCode(isset($r[39]) ? $r[39] : null);
     } else {
         Mage::throwException(Mage::helper('paygate')->__('Error in payment gateway.'));
     }
     $debugData['result'] = $result->getData();
     $this->_debug($debugData);
     return $result;
 }
Ejemplo n.º 13
0
 /**
  *  Send request to gateway
  *
  *  @param    Mage_Chronopay_Model_Gateway_Request
  *  @return	  mixed
  */
 protected function _postRequest(Mage_Chronopay_Model_Gateway_Request $request)
 {
     $result = Mage::getModel('chronopay/gateway_result');
     $client = new Varien_Http_Client();
     $url = $this->getConfigData('cgi_url');
     $client->setUri($url ? $url : self::CGI_URL);
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->setParameterPost($request->getData());
     $client->setMethod(Zend_Http_Client::POST);
     $debugData = array('request' => $request->getData());
     try {
         $response = $client->request();
         $body = $response->getRawBody();
         if (preg_match('/(T\\|(.+)\\|[\\r\\n]{0,}){0,1}(Y\\|(.+)?|\\|)|(N\\|(.+[\\r\\n]{0,}.+){0,})/', $body, $matches)) {
             $transactionId = $matches[2];
             $message = isset($matches[4]) ? trim($matches[4], '|') : '';
             if (isset($matches[5], $matches[6])) {
                 $result->setError($matches[6]);
                 Mage::throwException($matches[6]);
             }
             if ($message == 'Completed') {
                 $result->setTransaction($request->getTransaction());
             }
             if (strlen($transactionId)) {
                 $result->setTransaction($transactionId);
             }
             if (!$result->getTransaction()) {
                 Mage::throwException(Mage::helper('chronopay')->__('The transaction ID is invalid.'));
             }
         } else {
             Mage::throwException(Mage::helper('chronopay')->__('Invalid response format.'));
         }
     } catch (Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         $exceptionMsg = Mage::helper('chronopay')->__('Gateway request error: %s', $e->getMessage());
         $debugData['result'] = $result->getData();
         $this->_debug($debugData);
         Mage::throwException($exceptionMsg);
     }
     $debugData['result'] = $result->getData();
     $this->_debug($debugData);
     return $result;
 }
Ejemplo n.º 14
0
 protected function processAdminRequest($params, $requestTimeout = 60)
 {
     try {
         $client = new Varien_Http_Client();
         $client->setUri($this->getAdminUrl())->setConfig(array('timeout' => $requestTimeout))->setParameterPost($params)->setMethod(Zend_Http_Client::POST);
         $response = $client->request();
         $responseBody = $response->getBody();
         if (empty($responseBody)) {
             Mage::throwException($this->_getHelper()->__('vacc API failure. The request has not been processed.'));
         }
         // create array out of response
     } catch (Exception $e) {
         Mage::log($e->getMessage());
         Mage::throwException($this->_getHelper()->__('vacc API connection error. The request has not been processed.'));
     }
     return $responseBody;
 }
Ejemplo n.º 15
0
 protected function _postRequest(Varien_Object $request)
 {
     $result = AO::getModel('paygate/authorizenet_result');
     $client = new Varien_Http_Client();
     $uri = $this->getConfigData('cgi_url');
     $client->setUri($uri ? $uri : self::CGI_URL);
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->setParameterPost($request->getData());
     $client->setMethod(Zend_Http_Client::POST);
     if ($this->getConfigData('debug')) {
         foreach ($request->getData() as $key => $value) {
             $requestData[] = strtoupper($key) . '=' . $value;
         }
         $requestData = join('&', $requestData);
         $debug = AO::getModel('paygate/authorizenet_debug')->setRequestBody($requestData)->setRequestSerialized(serialize($request->getData()))->setRequestDump(print_r($request->getData(), 1))->save();
     }
     try {
         $response = $client->request();
     } catch (Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         if (!empty($debug)) {
             $debug->setResultSerialized(serialize($result->getData()))->setResultDump(print_r($result->getData(), 1))->save();
         }
         AO::throwException(AO::helper('paygate')->__('Gateway request error: %s', $e->getMessage()));
     }
     $responseBody = $response->getBody();
     $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
     if ($r) {
         $result->setResponseCode((int) str_replace('"', '', $r[0]))->setResponseSubcode((int) str_replace('"', '', $r[1]))->setResponseReasonCode((int) str_replace('"', '', $r[2]))->setResponseReasonText($r[3])->setApprovalCode($r[4])->setAvsResultCode($r[5])->setTransactionId($r[6])->setInvoiceNumber($r[7])->setDescription($r[8])->setAmount($r[9])->setMethod($r[10])->setTransactionType($r[11])->setCustomerId($r[12])->setMd5Hash($r[37])->setCardCodeResponseCode($r[39]);
     } else {
         AO::throwException(AO::helper('paygate')->__('Error in payment gateway'));
     }
     if (!empty($debug)) {
         $debug->setResponseBody($responseBody)->setResultSerialized(serialize($result->getData()))->setResultDump(print_r($result->getData(), 1))->save();
     }
     return $result;
 }
Ejemplo n.º 16
0
 public function postData($json, $endpoint)
 {
     $apiURL = Mage::getStoreConfig('settings/endpoint_url') . '/' . $endpoint;
     $appID = Mage::getStoreConfig('reachly_handleevent_options/section_one/field_app_id');
     $secretKey = Mage::getStoreConfig('reachly_handleevent_options/section_one/field_secret_key');
     $auth = $appID . ":" . base64_encode(hash_hmac('sha256', $json, $secretKey));
     $client = new Varien_Http_Client();
     $client->setUri($apiURL)->setMethod('POST')->setConfig(array('maxredirects' => 0, 'timeout' => 15));
     $client->setHeaders(array('Content-Length: ' . strlen($json), 'Authorization: ' . $auth));
     $client->setRawData($json, "application/json;charset=UTF-8");
     $reqCounter = 0;
     do {
         $success = true;
         try {
             $response = $client->request();
         } catch (Zend_Http_Client_Exception $e) {
             $success = false;
             $reqCounter++;
         }
     } while (!$success && $reqCounter < 3);
 }
 /**
  * Get country, city and state from postcode
  */
 public function postcodeAddressAction()
 {
     $result = new stdClass();
     $result->error = false;
     $postcode = $this->getRequest()->getParam('postcode');
     $postcode = urlencode(trim($postcode));
     $specificCountry = trim($this->getRequest()->getParam('country'));
     $allowed_countries = $this->_getCountryOptions();
     $request_url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $postcode . '&sensor=true';
     // make call
     $client = new Varien_Http_Client($request_url);
     $client->setMethod(Varien_Http_Client::GET);
     try {
         $response = $client->request();
         if ($response->isSuccessful()) {
             $json_response = json_decode($response->getBody());
             $json_success = $json_response->status === 'OK' ? true : false;
         }
     } catch (Exception $e) {
         $json_success = false;
     }
     if ($json_success) {
         if (1 == count($json_response->results)) {
             // if we only have one result let's return that & stop right here
             $result = $this->_extractAddress($json_response->results[0]->address_components);
         } else {
             if (!empty($specificCountry)) {
                 // if we have multiple results & a country already specified, then prefer the specified country first
                 $flag = true;
                 $firstRecordFlag = true;
                 foreach ($json_response->results as $resultInstance) {
                     foreach ($resultInstance->address_components as $address_component) {
                         if ($address_component->types[0] == 'country' && $flag) {
                             if ($address_component->long_name === $specificCountry) {
                                 // found a record where country matches the already specified country, let's try to use this address
                                 $result = $this->_extractAddress($resultInstance->address_components);
                                 if (!$result->error) {
                                     // the address matched & we have the needed information, no need to continue. Hooray!
                                     $flag = false;
                                 }
                             } else {
                                 if ($firstRecordFlag) {
                                     // stored first record as result if countries in all records doesn't match the already specified country
                                     $firstResult = $this->_extractAddress($resultInstance->address_components);
                                     if (!$result->error) {
                                         // the first record stored no need to store it again.
                                         $firstRecordFlag = false;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // if result is emtpy then use first record (if first record exists)
         if (!isset($result->data) && isset($firstResult->data)) {
             $result = $firstResult;
         }
         // if the country is not allowed in admin settings, just return no results
         if (isset($result->data) && isset($result->data->country_id) || isset($result->data) && isset($result->data->country)) {
             $flag = true;
             foreach ($allowed_countries as $allowed_country) {
                 if ($allowed_country['value'] === $result->data->country_id || $allowed_country['label'] === $result->data->country) {
                     $flag = false;
                     break;
                 }
             }
             if ($flag) {
                 unset($result->data);
             }
         }
     } else {
         $result->error = true;
     }
     $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
 }
Ejemplo n.º 18
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $url
  * @param Varien_Object $data
  * @param string $method
  * @return Varien_Object
  */
 public function request($url, Varien_Object $data, $method = 'GET')
 {
     $client = new Varien_Http_Client($url, array('timeout' => 30));
     $client->setMethod($method);
     if ($method == Zend_Http_Client::POST) {
         $client->setParameterPost($this->_parseArray($data));
     } else {
         $client->setParameterGet($this->_parseArray($data));
     }
     $response = $client->request();
     $body = json_decode($response->getBody(), true);
     $result = $this->_parseObject($body);
     return $result;
 }
Ejemplo n.º 19
0
 public function ping()
 {
     // Get current version of the extension
     $connection = Mage::getSingleton('core/resource')->getConnection('core_read');
     $table = Mage::getSingleton('core/resource')->getTableName('core_resource');
     $stmt = $connection->query("SELECT version FROM {$table} WHERE code='anattadesign_awesomecheckout_setup';");
     $data = $stmt->fetch();
     $version = $data['version'];
     $ping = array('version' => $version, 'site_name' => Mage::getStoreConfig('general/store_information/name'), 'url' => 'http://' . str_replace(array('http://', 'https://', '/index.php/', '/index.php'), '', Mage::getUrl()));
     $ping['url'] = $this->trailingslashit($ping['url']);
     // make call
     $client = new Varien_Http_Client('http://api.anattadesign.com/awesomecheckout/1alpha/collect/ping');
     $client->setMethod(Varien_Http_Client::POST);
     $client->setParameterPost('ping', $ping);
     try {
         $response = $client->request();
         if ($response->isSuccessful()) {
             $json_response = json_decode($response->getBody(), true);
             $ping_success = $json_response['status'] == 'success' ? true : false;
         }
     } catch (Exception $e) {
         $ping_success = false;
     }
     if ($ping_success) {
         // make sure ping is not rescheduled anymore
         Mage::getModel('core/config')->deleteConfig('anattadesign_awesomecheckout_ping_rescheduled');
     } else {
         // reschedule ping, increment counts if its already scheduled, so that we can see how many times it has failed
         // $ping_rescheduled = Mage::getStoreConfig( 'anattadesign_awesomecheckout_ping_rescheduled' );
         // Fetch directly from database to bypass Magento config cache.
         // Its better to bypass cache and make a sql query in favor of performance, sql query is not gonna run up on frontend side, except when all the cache is refreshed & extension is upgraded
         $table = Mage::getSingleton('core/resource')->getTableName('core_config_data');
         $stmt = $connection->query("SELECT value FROM {$table} WHERE path='anattadesign_awesomecheckout_ping_rescheduled' AND scope = 'default' AND scope_id = 0 LIMIT 1;");
         $data = $stmt->fetch();
         if ($data === false) {
             $ping_rescheduled = 1;
         } else {
             $ping_rescheduled = intval($data['value']) + 1;
         }
         Mage::getModel('core/config')->saveConfig('anattadesign_awesomecheckout_ping_rescheduled', $ping_rescheduled);
     }
 }
Ejemplo n.º 20
0
 private function rpxCall($url, $method = 'GET', $postParams = null)
 {
     $result = "rpxCallUrl: no result yet";
     try {
         $http = new Varien_Http_Client($url);
         $http->setHeaders(array("Accept-encoding" => "identity"));
         if ($method == 'POST') {
             $http->setParameterPost($postParams);
         }
         $response = $http->request($method);
         $body = $response->getBody();
         try {
             $result = json_decode($body);
         } catch (Exception $e) {
             throw Mage::exception('Mage_Core', $e);
         }
         if ($result) {
             return $result;
         } else {
             throw Mage::exception('Mage_Core', "something went wrong");
         }
     } catch (Exception $e) {
         throw Mage::exception('Mage_Core', $e);
     }
 }
Ejemplo n.º 21
0
 public function request($url, $params, $object = null, $timeout = null)
 {
     if (!$timeout) {
         $timeout = 0;
     }
     try {
         $client = new Varien_Http_Client();
         $client->setUri($url)->setConfig(array('timeout' => $timeout))->setHeaders('accept-encoding', '')->setParameterPost($params)->setMethod(Zend_Http_Client::POST);
         if ($object instanceof Mageplace_Backup_Model_Backup && $object->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_ENABLE) && $object->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_USER)) {
             $client->setAuth($object->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_USER), $object->getProfileData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_PASSWORD));
         } elseif ($object instanceof Mageplace_Backup_Model_Profile && $object->getData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_ENABLE) && $object->getData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_USER)) {
             $client->setAuth($object->getData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_USER), $object->getData(Mageplace_Backup_Model_Profile::COLUMN_AUTH_PASSWORD));
         }
         $response = $client->request();
         return $response->getRawBody();
     } catch (Zend_Http_Client_Exception $zhce) {
         if ($zhce->getMessage() != 'Unable to read response, or response is empty') {
             Mage::logException($zhce);
             throw $zhce;
         }
     } catch (Exception $e) {
         Mage::logException($e);
         throw $e;
     }
     return '';
 }
Ejemplo n.º 22
0
 public function process_images($observer)
 {
     $product = $observer->getEvent()->getProduct();
     if (!$product->hasWebtoprintTemplate()) {
         return;
     }
     $template_guid = $product->getWebtoprintTemplate();
     $template_guid_orig = $product->getOrigData('webtoprint_template');
     if ($template_guid == $template_guid_orig && !Mage::registry('webtoprint-template-changed')) {
         return;
     }
     $media_gallery = $product->getMediaGallery();
     if (is_array($media_gallery)) {
         foreach ($media_gallery as &$item) {
             if (!is_array($item) && strlen($item) > 0) {
                 $item = Zend_Json::decode($item);
             }
         }
     } else {
         $media_gallery = array('images' => array());
     }
     if ($template_guid) {
         $template = Mage::getModel('webtoprint/template')->load($template_guid);
         if (!$template->getId()) {
             return;
         }
         $xml = new SimpleXMLElement($template->getXml());
         unset($template);
     }
     //Trying to remove images which no longer exist in template
     foreach ($media_gallery['images'] as &$image) {
         if (!(isset($image['file']) && strpos(basename($image['file']), 'zetaprints_') === 0)) {
             continue;
         }
         if (!$template_guid) {
             $image['removed'] = 1;
             if ($product->getSmallImage() == $image['file']) {
                 $product->setSmallImage('no_selection');
             }
             if ($product->getThumbnail() == $image['file']) {
                 $product->setThumbnail('no_selection');
             }
             continue;
         }
         foreach ($xml->Pages[0]->Page as $page) {
             $image_id = basename((string) $page['PreviewImage']);
             if (strpos(basename($image['file']), "zetaprints_{$image_id}")) {
                 break;
             }
             $image['removed'] = 1;
             if ($product->getSmallImage() == $image['file']) {
                 $product->setSmallImage('no_selection');
             }
             if ($product->getThumbnail() == $image['file']) {
                 $product->setThumbnail('no_selection');
             }
         }
     }
     $product->setMediaGallery($media_gallery);
     if (!$template_guid) {
         return;
     }
     $first_image = true;
     foreach ($media_gallery['images'] as $image) {
         if (!isset($image['removed']) && $image['disabled'] === 1) {
             $first_image = false;
             break;
         }
     }
     $attributes = $product->getTypeInstance(true)->getSetAttributes($product);
     $gallery_backend = $attributes['media_gallery']->getBackend();
     unset($attributes);
     foreach ($xml->Pages[0]->Page as $page) {
         $image_id = basename((string) $page['PreviewImage']);
         $image_exists = false;
         if (is_array($media_gallery)) {
             foreach ($media_gallery['images'] as &$image) {
                 if (!isset($image['removed']) && isset($image['file']) && strpos(basename($image['file']), "zetaprints_{$image_id}") === 0) {
                     $image_exists = true;
                 }
             }
         }
         if ($image_exists) {
             break;
         }
         $client = new Varien_Http_Client(Mage::getStoreConfig('webtoprint/settings/url') . '/' . (string) $page['PreviewImage']);
         $filename = Mage::getBaseDir('var') . "/tmp/zetaprints_{$image_id}";
         file_put_contents($filename, $client->request()->getBody());
         unset($client);
         $file = $gallery_backend->addImage($product, $filename, null, true);
         $data = array('label' => (string) $page['Name']);
         if ($first_image) {
             if (!$product->getSmallImage() || $product->getSmallImage() == 'no_selection') {
                 $product->setSmallImage($file);
             }
             if (!$product->getThumbnail() || $product->getThumbnail() == 'no_selection') {
                 $product->setThumbnail($file);
             }
             $first_image = false;
         } else {
             $data['exclude'] = 0;
         }
         $gallery_backend->updateImage($product, $file, $data);
         unset($data);
     }
     unset($gallery_backend);
     unset($xml);
 }
Ejemplo n.º 23
0
 protected function _checkUrl($url, $secure = false)
 {
     $prefix = $secure ? 'install/wizard/checkSecureHost/' : 'install/wizard/checkHost/';
     try {
         $client = new Varien_Http_Client($url . 'index.php/' . $prefix);
         $response = $client->request('GET');
         /* @var $responce Zend_Http_Response */
         $body = $response->getBody();
     } catch (Exception $e) {
         $this->_getInstaller()->getDataModel()->addError(Mage::helper('install')->__('The URL "%s" is not accessible.', $url));
         throw $e;
     }
     if ($body != Mage_Install_Model_Installer::INSTALLER_HOST_RESPONSE) {
         $this->_getInstaller()->getDataModel()->addError(Mage::helper('install')->__('The URL "%s" is invalid.', $url));
         Mage::throwException(Mage::helper('install')->__('Response from server isn\'t valid.'));
     }
     return $this;
 }
Ejemplo n.º 24
0
 /**
  * Send request for tracking
  *
  * @param array $trackings
  * @return void
  */
 protected function _getXMLTracking($trackings)
 {
     $xmlStr = '<?xml version="1.0" encoding="UTF-8"?>' . '<req:KnownTrackingRequest' . ' xmlns:req="http://www.dhl.com"' . ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . ' xsi:schemaLocation="http://www.dhl.com TrackingRequestKnown.xsd" />';
     $xml = new SimpleXMLElement($xmlStr);
     $requestNode = $xml->addChild('Request', '', '');
     $serviceHeaderNode = $requestNode->addChild('ServiceHeader', '', '');
     $serviceHeaderNode->addChild('SiteID', (string) $this->getConfigData('id'));
     $serviceHeaderNode->addChild('Password', (string) $this->getConfigData('password'));
     $xml->addChild('LanguageCode', 'EN', '');
     foreach ($trackings as $tracking) {
         $xml->addChild('AWBNumber', $tracking, '');
     }
     /*
      * Checkpoint details selection flag
      * LAST_CHECK_POINT_ONLY
      * ALL_CHECK_POINTS
      */
     $xml->addChild('LevelOfDetails', 'ALL_CHECK_POINTS', '');
     /*
      * Value that indicates for getting the tracking details with the additional
      * piece details and its respective Piece Details, Piece checkpoints along with
      * Shipment Details if queried.
      *
      * S-Only Shipment Details
      * B-Both Shipment & Piece Details
      * P-Only Piece Details
      * Default is ‘S’
      */
     //$xml->addChild('PiecesEnabled', 'ALL_CHECK_POINTS');
     $request = $xml->asXML();
     $request = utf8_encode($request);
     $responseBody = $this->_getCachedQuotes($request);
     if ($responseBody === null) {
         $debugData = array('request' => $request);
         try {
             $client = new Varien_Http_Client();
             $client->setUri((string) $this->getConfigData('gateway_url'));
             $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
             $client->setRawData($request);
             $responseBody = $client->request(Varien_Http_Client::POST)->getBody();
             $debugData['result'] = $responseBody;
             $this->_setCachedQuotes($request, $responseBody);
         } catch (Exception $e) {
             $this->_errors[$e->getCode()] = $e->getMessage();
             $responseBody = '';
         }
         $this->_debug($debugData);
     }
     $this->_parseXmlTrackingResponse($trackings, $responseBody);
 }
Ejemplo n.º 25
0
 /**
  * This function returns full transaction details for a specified transaction ID.
  *
  * @link http://www.authorize.net/support/ReportingGuide_XML.pdf
  * @link http://developer.authorize.net/api/transaction_details/
  * @param string $transactionId
  * @return Varien_Object
  */
 protected function _getTransactionDetails($transactionId)
 {
     $requestBody = sprintf('<?xml version="1.0" encoding="utf-8"?>' . '<getTransactionDetailsRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">' . '<merchantAuthentication><name>%s</name><transactionKey>%s</transactionKey></merchantAuthentication>' . '<transId>%s</transId>' . '</getTransactionDetailsRequest>', $this->getConfigData('login'), $this->getConfigData('trans_key'), $transactionId);
     $client = new Varien_Http_Client();
     $uri = $this->getConfigData('cgi_url_td');
     $client->setUri($uri ? $uri : self::CGI_URL_TD);
     $client->setConfig(array('timeout' => 45));
     $client->setHeaders(array('Content-Type: text/xml'));
     $client->setMethod(Zend_Http_Client::POST);
     $client->setRawData($requestBody);
     $debugData = array('request' => $requestBody);
     try {
         $responseBody = $client->request()->getBody();
         $debugData['result'] = $responseBody;
         $this->_debug($debugData);
         libxml_use_internal_errors(true);
         $responseXmlDocument = new Varien_Simplexml_Element($responseBody);
         libxml_use_internal_errors(false);
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('paygate')->__('Payment updating error.'));
     }
     $response = new Varien_Object();
     $response->setResponseCode((string) $responseXmlDocument->transaction->responseCode)->setResponseReasonCode((string) $responseXmlDocument->transaction->responseReasonCode);
     return $response;
 }
Ejemplo n.º 26
0
 /**
  * Reading a page via HTTPS and returning its content.
  */
 protected function _getHttpsPage($host, $parameter)
 {
     $client = new Varien_Http_Client();
     $client->setUri($host)->setConfig(array('timeout' => 30))->setHeaders('accept-encoding', '')->setParameterGet($parameter)->setMethod(Zend_Http_Client::GET);
     $request = $client->request();
     // Workaround for pseudo chunked messages which are yet too short, so
     // only an exception is is thrown instead of returning raw body
     if (!preg_match("/^([\\da-fA-F]+)[^\r\n]*\r\n/sm", $request->getRawBody(), $m)) {
         return $request->getRawBody();
     }
     return $request->getBody();
 }
/**
 * Listrak Remarketing Magento Extension Ver. 1.1.9
 *
 * PHP version 5
 *
 * @category  Listrak
 * @package   Listrak_Remarketing
 * @author    Listrak Magento Team <*****@*****.**>
 * @copyright 2014 Listrak Inc
 * @license   http://s1.listrakbi.com/licenses/magento.txt License For Customer Use of Listrak Software
 * @link      http://www.listrak.com
 */
$installer = $this;
$installer->startSetup();
$installer->run("\nALTER TABLE {$this->getTable('listrak/session')}\n  ADD COLUMN `converted` boolean NOT NULL DEFAULT 0;\n");
try {
    Mage::getModel("listrak/log")->addMessage("1.1.8-1.1.9 upgrade");
} catch (Exception $e) {
}
try {
    $client = new Varien_Http_Client("http://magento.listrakbi.com/Install.ashx");
    $client->setMethod(Varien_Http_Client::POST);
    $client->setParameterPost("Listrak Extension Version", "1.1.9");
    $client->setParameterPost("Magento Version", Mage::getVersion());
    $client->setParameterPost("Install URL", "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
    $client->setParameterPost("IP Address", "{$_SERVER['SERVER_ADDR']}");
    $client->request();
} catch (Exception $e) {
}
$installer->endSetup();
Ejemplo n.º 28
0
 public function getApiCall($url)
 {
     $JsonResponse = "";
     if ($this->getApiOption() == 'curl') {
         $curl_handle = curl_init();
         curl_setopt($curl_handle, CURLOPT_URL, $url);
         curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5);
         curl_setopt($curl_handle, CURLOPT_TIMEOUT, 5);
         curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
         if (ini_get('open_basedir') == '' && (ini_get('safe_mode') == 'Off' or !ini_get('safe_mode'))) {
             curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
             curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
         } else {
             curl_setopt($curl_handle, CURLOPT_HEADER, 1);
             $url = curl_getinfo($curl_handle, CURLINFO_EFFECTIVE_URL);
             curl_close($curl_handle);
             $curl_handle = curl_init();
             $url = str_replace('?', '/?', $url);
             curl_setopt($curl_handle, CURLOPT_URL, $url);
             curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
         }
         $JsonResponse = curl_exec($curl_handle);
         $httpCode = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
         if (in_array($httpCode, array(400, 401, 403, 404, 500, 503)) && $httpCode != 200) {
             return "service connection timeout";
         } else {
             if (curl_errno($curl_handle) == 28) {
                 return "timeout";
             }
         }
         curl_close($curl_handle);
     } elseif ($this->getApiOption() == 'fopen') {
         $JsonResponse = @file_get_contents($url);
         if (strpos(@$http_response_header[0], "400") !== false || strpos(@$http_response_header[0], "401") !== false || strpos(@$http_response_header[0], "403") !== false || strpos(@$http_response_header[0], "404") !== false || strpos(@$http_response_header[0], "500") !== false || strpos(@$http_response_header[0], "503") !== false) {
             return "service connection timeout";
         }
     } else {
         $method = 'GET';
         try {
             $client = new Varien_Http_Client($url);
             $response = $client->request($method);
             $JsonResponse = $response->getBody();
         } catch (Exception $e) {
         }
     }
     if ($JsonResponse) {
         return json_decode($JsonResponse);
     } else {
         return "something went wrong, Can not get api response.";
     }
 }
Ejemplo n.º 29
0
 public function approveOrder(Varien_Event_Observer $observer)
 {
     if (!$this->_helper->isActive()) {
         return;
     }
     if (!$this->_helper->isEligible()) {
         return;
     }
     $this->_helper->log("approveOrder: begin");
     $order = $observer->getEvent()->getOrder();
     $orderId = $order->getId();
     $orderIncrementId = $order->getIncrementId();
     $this->_helper->log("approveOrder: orderid: {$orderId} orderIncrementId: {$orderIncrementId}");
     $url = rtrim($this->_helper->getApiUrl(), '/') . '/approveOrder';
     $client = new Varien_Http_Client($url);
     $client->setMethod(Varien_Http_Client::POST)->setConfig(array('timeout' => 8000, 'maxredirects' => 2));
     $quoteId = $order->getQuoteId();
     $deliverytime = Mage::getModel('milkman_deliveries/deliverytime');
     $deliverytime->load($quoteId, 'quote_id');
     $sessionId = $deliverytime->getSessionId();
     $data = (object) ['privateKey' => $this->_helper->getPrivateKey(), 'sessionId' => $sessionId, 'externalTrackingCode' => $orderIncrementId];
     // $client->setParameterPost($data);
     $json = utf8_encode(json_encode($data, JSON_UNESCAPED_SLASHES));
     $this->_helper->log("approveOrder: json: {$json}");
     $client->setRawData($json);
     $error = true;
     try {
         $response = $client->request();
         $body = $response->getBody();
         if ($response->isSuccessful()) {
             $result = json_decode($body, true);
             $checkJson = JSON_ERROR_NONE == json_last_error();
             $checkSuccess = isset($result['result']['success']) && $result['result']['success'];
             if ($checkJson && $checkSuccess) {
                 $error = false;
                 $this->_helper->log("approveOrder: success");
             } else {
                 if (json_last_error() > 0) {
                     $this->_helper->log("approveOrder: json error code: " . json_last_error());
                 } else {
                     $this->_helper->log("approveOrder: data error");
                 }
             }
         } else {
             $this->_helper->log("approveOrder: rest error");
         }
     } catch (Exception $e) {
         $body = $response->getBody();
         $this->_helper->log("approveOrder: exception error");
     }
     $this->_helper->log("approveOrder: body: " . $body);
     if ($error) {
         $this->_helper->log("approveOrder: error");
         Mage::throwException($this->_helper->__("An error occurred during order confirmation."));
     }
 }
 /**
  * Post request to gateway and return responce
  *
  * @param Mage_Paygate_Model_Authorizenet_Request $request)
  * @return Mage_Paygate_Model_Authorizenet_Result
  */
 protected function _postRequest(Varien_Object $request)
 {
     $debugData = array('request' => $request->getData());
     $debugData['class'] = get_class($request);
     $result = Mage::getModel('paygate/authorizenet_result');
     $client = new Varien_Http_Client();
     $uri = $this->getConfigData('cgi_url');
     $client->setUri($uri ? $uri : self::CGI_URL);
     //Mage::log(' ---------- new post request ', null, 'capture.log');
     //Mage::log(' uri '.$client->getUri(), null, 'capture.log');
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     foreach ($request->getData() as $key => $value) {
         $request->setData($key, str_replace(self::RESPONSE_DELIM_CHAR, '', $value));
     }
     $request->setXDelimChar(self::RESPONSE_DELIM_CHAR);
     $client->setParameterPost($request->getData());
     $client->setMethod(Zend_Http_Client::POST);
     //Mage::log($request->getData(), null, 'capture.log');
     try {
         $response = $client->request();
     } catch (Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         $debugData['result'] = $result->getData();
         $this->_debug($debugData);
         Mage::throwException($this->_wrapGatewayError($e->getMessage()));
     }
     $responseBody = $response->getBody();
     $debugData['responseBody'] = $responseBody;
     $r = explode(self::RESPONSE_DELIM_CHAR, $responseBody);
     $debugData['deliminator'] = self::RESPONSE_DELIM_CHAR;
     $debugData['results_exploded'] = $r;
     if ($r) {
         $result->setResponseCode((int) str_replace('"', '', $r[0]))->setResponseSubcode((int) str_replace('"', '', $r[1]))->setResponseReasonCode((int) str_replace('"', '', $r[2]))->setResponseReasonText($r[3])->setApprovalCode($r[4])->setAvsResultCode($r[5])->setTransactionId($r[6])->setInvoiceNumber($r[7])->setDescription($r[8])->setAmount($r[9])->setMethod($r[10])->setTransactionType($r[11])->setCustomerId($r[12])->setMd5Hash($r[37])->setCardCodeResponseCode($r[38])->setCAVVResponseCode(isset($r[39]) ? $r[39] : null)->setSplitTenderId($r[52])->setAccNumber($r[50])->setCardType($r[51])->setRequestedAmount($r[53])->setBalanceOnCard($r[54]);
     } else {
         Mage::throwException(Mage::helper('revolution')->__('Error in payment gateway.'));
     }
     $debugData['result'] = $result->getData();
     $this->_debug($debugData);
     return $result;
 }