/** * 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'); } }
/** * Client GET call * * @param $string, $string * @return Varien_Http_Client $response */ private function getClient($apiKey, $url) { $client = new Varien_Http_Client($url); $client->setMethod(Varien_Http_Client::GET); $client->setHeaders('Authorization', 'Token token="' . $apiKey . '"'); return $client; }
/** * 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.'); } }
/** * 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; } }
/** * 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.'); } }
/** * 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; } }
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; }
/** * 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; }
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; }
/** * 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; }
/** * Post the transaction request * * @param Shift4_Shift4Payment_Model_ApiRequest $request * @return Shift4_Shift4Payment_Model_ApiResponse */ protected function _postRequest(Shift4_Shift4Payment_Model_ApiRequest $request) { $client = new Varien_Http_Client(); $client->setUri($request->getData('url')); $client->setConfig(array('maxredirects' => 0, 'timeout' => 30)); $params = array_merge(array('STX' => 'YES'), $request->getData(), array('ETX' => 'YES')); $client->setParameterPost($params); $client->setMethod(Zend_Http_Client::POST); try { $response = $client->request(); } catch (Exception $e) { $response = Mage::getModel('shift4payment/ApiResponse'); $response->setResponseCode(self::RESPONSE_ERROR); $response->setResponseMessage('There was a problem communicating with the payment gateway. Please try again.'); } $request->setParams($params); return $this->_processResponse($request, $response->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();
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); } }
protected function _postRequest($request) { $client = new Varien_Http_Client(); $client->setUri($this->getUrl()); $client->setConfig(array('maxredirects' => 2, 'timeout' => 60)); $client->setParameterGet($request); $client->setMethod(Zend_Http_Client::GET); try { $response = $client->request(); } catch (Exception $e) { Mage::throwException(Mage::helper('pnsofortueberweisung')->__('Gateway request error: %s', $e->getMessage())); } $responseBody = $response->getBody(); return $responseBody; }
public function checkAwesomeCheckoutVersion() { $request_url = 'http://api.anattadesign.com/awesomecheckout/1alpha/status/latestVersion'; // 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 === 'success' ? true : false; } } catch (Exception $e) { $json_success = false; } if ($json_success) { // Don't do anything if we are on latest, this prevents duplicate notifications if (version_compare($json_response->latestVersion, Mage::getStoreConfig('anattadesign_awesomecheckout_latest_checked_version'), 'eq')) { return; } $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']; if (version_compare($json_response->latestVersion, $version, '>')) { Mage::getModel('adminnotification/inbox')->setSeverity(Mage_AdminNotification_Model_Inbox::SEVERITY_NOTICE)->setTitle(Mage::helper('anattadesign_awesomecheckout')->__("Awesome Checkout %s is now available", $json_response->latestVersion))->setDateAdded(gmdate('Y-m-d H:i:s'))->setUrl('http://www.awesomecheckout.com/update')->setDescription(Mage::helper('anattadesign_awesomecheckout')->__('Your version of Awesome Checkout is currently not up-to-date. Please <a href="http://www.awesomecheckout.com/update">click here</a> to get the latest version.'))->save(); Mage::getModel('core/config')->saveConfig('anattadesign_awesomecheckout_latest_checked_version', $json_response->latestVersion); } } }
/** * 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; }
/** * 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)); }
/** * 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; }
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.")); } }
/** * 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 array An array of parameters * @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'; 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); call_user_func(array($client, $setParamMethod), 'pio_appkey', $this->apiKey); foreach ($params as $paramKey => $paramValue) { call_user_func(array($client, $setParamMethod), $paramKey, $paramValue); } $response = $client->request(); if ($response->isSuccessful()) { return json_decode($response->getBody()); } else { // [todo] decide on a better way to handle this without throwing an exception throw new Exception('Request failed'); } }