public function getToken(Request $request) { if (isset($this->session->token)) { return true; } elseif (strlen($this->session->state) > 0 and $this->session->state == $request->getQuery('state') and strlen($request->getQuery('code')) > 5) { $client = $this->getHttpClient(); $client->setUri($this->options->getTokenUri()); $client->setMethod(Request::METHOD_POST); $client->setParameterPost(array('code' => $request->getQuery('code'), 'client_id' => $this->options->getClientId(), 'client_secret' => $this->options->getClientSecret(), 'redirect_uri' => $this->options->getRedirectUri(), 'grant_type' => 'authorization_code')); $retVal = $client->send()->getContent(); try { $token = \Zend\Json\Decoder::decode($retVal); if (isset($token->access_token) and $token->expires_in > 0) { $this->session->token = $token; return true; } else { $this->error = array('internal-error' => 'Google settings error.', 'error' => $token->error, 'token' => $token); return false; } } catch (\Zend\Json\Exception\RuntimeException $e) { $this->error['internal-error'] = 'Unknown error.'; $this->error['token'] = $retVal; return false; } } else { $this->error = array('internal-error' => 'State error, request variables do not match the session variables.', 'session-state' => $this->session->state, 'request-state' => $request->getQuery('state'), 'code' => $request->getQuery('code')); return false; } }
/** * Make a remote call to freegeoip.net to detect country of current customer session and store it into session * * @return $this */ public function saveVisitorData($observer) { $clientIP = $this->_request->getClientIp(); $httpClient = new Client(); $clientIP = $this->getRandomeIp($clientIP); $uri = self::URL_GEO_IP_SITE . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = JsonDecoder::decode($httpClient->send()->getBody()); $this->_customerSession->setVisitorData($response); //save to database $currenttime = date('Y-m-d H:i:s'); $model = $this->_objectManager->create('Bluecom\\Freegeoip\\Model\\Visitor'); $model->setData('visitor_ip', $response->ip); $model->setData('country_code', $response->country_code); $model->setData('country_name', $response->country_name); $model->setData('region_code', $response->region_code); $model->setData('region_name', $response->region_name); $model->setData('city', $response->city); $model->setData('zip_code', $response->zip_code); $model->setData('latitude', $response->latitude); $model->setData('longitude', $response->longitude); $model->setData('metro_code', $response->metro_code); $model->setData('browser', $_SERVER['HTTP_USER_AGENT']); $model->setData('os', php_uname()); $model->setData('created', $currenttime); $model->save(); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
public function getToken(Request $request) { if (isset($this->session->token)) { return true; } elseif (strlen($this->session->state) > 0 and $this->session->state == $request->getQuery('state') and strlen($request->getQuery('code')) > 5) { $client = $this->getHttpClient(); $client->setUri($this->options->getTokenUri()); $client->setMethod(Request::METHOD_POST); $client->setParameterPost(array('code' => $request->getQuery('code'), 'client_id' => $this->options->getClientId(), 'client_secret' => $this->options->getClientSecret(), 'redirect_uri' => $this->options->getRedirectUri(), 'grant_type' => 'authorization_code')); $resBody = $client->send()->getBody(); try { $response = JsonDecoder::decode($resBody, Json::TYPE_ARRAY); if (is_array($response) and isset($response['access_token']) and !isset($response['expires']) || $response['expires'] > 0) { $this->session->token = (object) $response; return true; } else { $this->error = array('internal-error' => 'Instagram settings error.', 'message' => $response->error_message, 'type' => $response->error_type, 'code' => $response->code); return false; } } catch (\Zend\Json\Exception\RuntimeException $e) { $this->error = array('internal-error' => 'Parse error.', 'message' => $e->getMessage(), 'code' => $e->getCode()); return false; } } else { $this->error = array('internal-error' => 'State error, request variables do not match the session variables.', 'session-state' => $this->session->state, 'request-state' => $request->getQuery('state'), 'code' => $request->getQuery('code')); return false; } }
/** * Get Country User * * @param EventObserver $observer */ public function execute(EventObserver $observer) { if (!$this->_customerSession->getLocated()) { //$clientIP = $this->_request->getClientIp(); /* * Set static Ip to test * * DE : 194.55.30.46 * VN : 123.30.215.27 * PL : 212.77.98.9 * SG : 202.157.143.72 * **/ $clientIP = '123.30.215.27'; $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient = new \Zend\Http\Client(); $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } } }
public function getToken(Request $request) { if (isset($this->session->token)) { return true; } elseif (strlen($this->session->state) > 0 and $this->session->state == $request->getQuery('state') and strlen($request->getQuery('code')) > 5) { $client = $this->getHttpClient(); $client->setUri($this->options->getTokenUri()); $client->setMethod(Request::METHOD_POST); $client->setParameterPost(array('code' => $request->getQuery('code'), 'client_id' => $this->options->getClientId(), 'client_secret' => $this->options->getClientSecret(), 'redirect_uri' => $this->options->getRedirectUri())); $retVal = $client->send()->getContent(); parse_str($retVal, $token); if (is_array($token) and isset($token['access_token']) and $token['expires'] > 0) { $this->session->token = (object) $token; return true; } else { try { $error = \Zend\Json\Decoder::decode($retVal); $this->error = array('internal-error' => 'Facebook settings error.', 'message' => $error->error->message, 'type' => $error->error->type, 'code' => $error->error->code); } catch (\Zend\Json\Exception\RuntimeException $e) { $this->error = $token; $this->error['internal-error'] = 'Unknown error.'; } return false; } } else { $this->error = array('internal-error' => 'State error, request variables do not match the session variables.', 'session-state' => $this->session->state, 'request-state' => $request->getQuery('state'), 'code' => $request->getQuery('code')); return false; } }
/** * Decodes the given $encodedValue string from JSON. * * Uses json_decode() from ext/json if available. * * @param string $encodedValue Encoded in JSON format * @param int $objectDecodeType Optional; flag indicating how to decode * objects. See {@link Decoder::decode()} for details. * @return mixed * @throws RuntimeException */ public static function decode($encodedValue, $objectDecodeType = self::TYPE_OBJECT) { $encodedValue = (string) $encodedValue; if (function_exists('json_decode') && static::$useBuiltinEncoderDecoder !== true) { return self::decodeViaPhpBuiltIn($encodedValue, $objectDecodeType); } return Decoder::decode($encodedValue, $objectDecodeType); }
protected function _parseResponse(\Zend\Http\Response $response) { $body = \Zend\Json\Decoder::decode($response->getBody()); if (array_key_exists(self::PARSE_ERROR, $body)) { throw new \Exception($body[self::PARSE_REASON]); } return $body; }
public function find($collectionName, $query, array $fields = array()) { $this->_connect(); $request = $this->_buildRequest($collectionName, $query, $fields); $response = $this->_connection->restPost('/mapred', \Zend\Json\Encoder::encode($request)); if ($response->isError()) { return null; } return new DbDocument\Cursor\Riak($this->getCollection($collectionName), \Zend\Json\Decoder::decode($response->getBody())); }
public function getGeocodedLatitudeAndLongitude($address) { $client = new Client(); $client->setUri($this->_url); $client->setParameterGet(array('address' => urlencode($address), 'sensor' => 'false')); $client->setMethod('GET'); $result = $client->send(); $response = Decoder::decode($result->getBody(), Json::TYPE_OBJECT); return $response; }
/** * Parses data returned from the Facebook Graph Api * @throws \Spabby\Facebook\Exception\AccessException * @param string $body The JSON encoded body returned from the http request * @return stdClass */ protected function parseFromGraph($body) { $data = \Zend\Json\Decoder::decode($body); if (!\is_object($data)) { throw new AccessException("Invalid Facebook Response"); } if (\property_exists($data, 'error')) { throw new AccessException("{$data->error->type}: \n {$data->error->message}"); } return $data; }
public function __invoke(FormModel $model, $route) { $form = new ZendForm(); foreach ($model->getElements() as $element) { $type = $element->getType(); $name = $element->getName(); $options = (array) Json::decode($element->getOptions()); $form->addElement($type, $name, $options); } $form->addElement('hidden', IndexController::ID, array('value' => $model->getId())); $url = $this->getView()->url(array(), array('name' => $route . '/send')); $form->setView($this->getView())->setAction($url); return $form; }
/** * @param Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $clientIP = "115.78.167.37"; // $clientIP = $this->_request->getClientIp(); $httpClient = new \Zend\Http\Client(); $uri = 'http://freegeoip.net/json/' . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = \Zend\Json\Decoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
public function retornarProducteAction() { $res = []; $res[0] = new RespostaTO(); try { $request = $this->getRequest(); $content = $request->getContent(); $post = Decoder::decode($content); $this->producte = $this->cataleg->consultarProducte(new Integer($post->id), UsuariConnectat::getUsuari()->getDepenDe()); $this->producte->retornar(UsuariConnectat::getUsuari()->getDepenDe()); $res[0]->resultat = "OK"; } catch (\Exception $e) { $res[0]->resultat = "KO"; $res[0]->missatge = $e->getMessage(); } finally { return new JsonModel($res); } }
/** * Get country from IP * * @return $this */ public function getCountry() { // $clientIP = $this->_request->getClientIp(); $clientIP = file_get_contents(self::URL_IP_SITE); $httpClient = new Client(); $uri = self::URL_GEO_IP_SITE . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = JsonDecoder::decode($httpClient->send()->getBody()); if (is_object($response) && $response->country_name) { return $response->country_name; } return false; } catch (\Exception $e) { return false; } }
public function getInfo() { if (is_object($this->session->info)) { return $this->session->info; } elseif (isset($this->session->token->access_token)) { $urlProfile = $this->options->getInfoUri() . '?access_token=' . $this->session->token->access_token; $client = $this->getHttpclient()->resetParameters(true)->setHeaders(array('Accept-encoding' => 'utf-8'))->setMethod(Request::METHOD_GET)->setUri($urlProfile); $retVal = $client->send()->getContent(); if (strlen(trim($retVal)) > 0) { $this->session->info = \Zend\Json\Decoder::decode($retVal); return $this->session->info; } else { $this->error = array('internal-error' => 'Get info return value is empty.'); return false; } } else { $this->error = array('internal-error' => 'Session access token not found.'); return false; } }
/** * Make a remote call to freegeoip.net to detect country of current customer session and store it into session * * @return $this */ public function getCountryFromIp() { /* Already call located data */ // if ($this->_customerSession->getLocated()) { // return $this; // } $clientIP = $this->_request->getClientIp(); $httpClient = new Client(); $uri = self::URL_GEO_IP_SITE . $clientIP; $httpClient->setUri($uri); $httpClient->setOptions(array('timeout' => 30)); try { $response = JsonDecoder::decode($httpClient->send()->getBody()); $this->_customerSession->setLocationData($response); $this->_customerSession->setLocated(true); } catch (\Exception $e) { $this->_logger->critical($e); } return $this; }
/** * Decodes the given $encodedValue string which is * encoded in the JSON format * * Uses ext/json's json_decode if available. * * @param string $encodedValue Encoded in JSON format * @param int $objectDecodeType Optional; flag indicating how to decode * objects. See {@link Zend\Json\Decoder::decode()} for details. * @return mixed * @throws RuntimeException */ public static function decode($encodedValue, $objectDecodeType = self::TYPE_OBJECT) { $encodedValue = (string) $encodedValue; if (function_exists('json_decode') && static::$useBuiltinEncoderDecoder !== true) { $decode = json_decode($encodedValue, $objectDecodeType); switch (json_last_error()) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: throw new RuntimeException('Decoding failed: Maximum stack depth exceeded'); case JSON_ERROR_CTRL_CHAR: throw new RuntimeException('Decoding failed: Unexpected control character found'); case JSON_ERROR_SYNTAX: throw new RuntimeException('Decoding failed: Syntax error'); default: throw new RuntimeException('Decoding failed'); } return $decode; } return Decoder::decode($encodedValue, $objectDecodeType); }
public function getInfo() { if (is_object($this->session->info)) { return $this->session->info; } if (isset($this->session->token->access_token)) { $urlProfile = $this->options->getInfoUri(); $client = $this->getHttpclient()->resetParameters(true)->setMethod(Request::METHOD_GET)->setParameterGet(array('format' => 'json', 'oauth2_access_token' => $this->session->token->access_token))->setUri($urlProfile); $retVal = $client->send()->getBody(); if (strlen(trim($retVal)) > 0) { $this->session->info = \Zend\Json\Decoder::decode($retVal); return $this->session->info; } else { $this->error = array('internal-error' => 'Get info return value is empty.'); return false; } } else { $this->error = array('internal-error' => 'Session access token not found.'); return false; } }
public function renewToken($refreshToken) { $client = $this->getHttpClient(); $client->setUri($this->options->getTokenUri()); $client->setMethod(\Zend\Http\PhpEnvironment\Request::METHOD_POST); $client->setParameterPost(array('refresh_token' => $refreshToken, 'client_id' => $this->options->getClientId(), 'client_secret' => $this->options->getClientSecret(), 'grant_type' => 'refresh_token')); $retVal = $client->send()->getContent(); try { $token = \Zend\Json\Decoder::decode($retVal); if (isset($token->access_token) and $token->expires_in > 0) { $this->session->token = $token; return true; } else { $this->error = array('internal-error' => 'Google settings error.', 'error' => $token->error, 'token' => $token); return false; } } catch (\Zend\Json\Exception\RuntimeException $e) { $this->error['internal-error'] = 'Unknown error.'; $this->error['token'] = $retVal; return false; } }
public function getUserProfileInfo() { // generate access token using the authorization code grant $accessToken = $this->generateAccessToken($this->authorizationCode, $this->providerState); // get URi for user's profile information using access token $userProfileInfoUri = $this->getUserProfileInfoUri($accessToken); // send request // $response = $this->httpClient->resetParameters(true) // ->setMethod(\Zend\Http\PhpEnvironment\Request::METHOD_GET) // ->setUri($userProfileInfoUri) // ->send(); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $userProfileInfoUri); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); curl_close($curl); $userProfileInfoObject = \Zend\Json\Decoder::decode($response); // return $this->mapUserProfileInfoObject2Array($userProfileInfoObject); $userProfileInfo['email'] = $userProfileInfoObject->emailAddress; $userProfileInfo['fullName'] = $userProfileInfoObject->firstName . " " . $userProfileInfoObject->lastName; $userProfileInfo['providerId'] = $userProfileInfoObject->id; return $userProfileInfo; }
public function lockstateAction() { $request = $this->getRequest(); $headers = $request->getHeaders(); $message = Decoder::decode($request->getContent(), Json::TYPE_ARRAY); $snsMessageType = $headers->get('x-amz-sns-message-type'); if (!$snsMessageType || !$message) { return $this->redirect()->toRoute('home'); } else { if ($snsMessageType->getFieldValue() == 'SubscriptionConfirmation') { //ToDo Confirm the subscription -> save signature, save arn $topicArn = $message['TopicArn']; $subscribeUrl = $message['SubscribeURL']; $client = new Client($subscribeUrl, ['adapter' => 'Zend\\Http\\Client\\Adapter\\Curl']); $response = $client->send(); } else { //ToDo Check signature, check arn } } $this->gr2info('Notification from Lockstate via Amazon SNS', $message); echo 'Notification received.'; exit; }
public function editarSupermercatAction() { $res = []; $res[0] = new RespostaTO(); try { $request = $this->getRequest(); $content = $request->getContent(); $post = Decoder::decode($content); $dd = UsuariConnectat::getUsuari()->getDepenDe(); $this->supermercat = $this->supers->consultarSupermercatNom(new String($post->nom), $dd); if ($this->supermercat->getNom() != null && $this->supermercat->getNom()->getString() != null && $this->supermercat->getId() != null && $this->supermercat->getId()->getInteger() != null && $this->supermercat->getId()->getInteger() != $post->id) { $res[0]->resultat = "ES"; } else { $id = $this->supermercat->guardar(new Integer($post->id), new String($post->nom), $dd); $res[0]->resultat = "OK"; $res[0]->id = $id; } } catch (\Exception $e) { $res[0]->resultat = "KO"; $res[0]->missatge = $e->getMessage(); } finally { return new JsonModel($res); } }
/** * @group ZF-4054 */ public function testDecodeUnicodeStringSolarRegression() { $expected = 'héllö wørÅ‚d'; $value = 'h\\u00c3\\u00a9ll\\u00c3\\u00b6 w\\u00c3\\u00b8r\\u00c5\\u201ad'; $this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value)); $expected = "ä"; $value = '\\u00e4'; $this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value)); $value = '\\u10a0'; $expected = "Ⴀ"; $this->assertEquals($expected, Json\Decoder::decodeUnicodeString($value)); }
/** * Perform a request to the API * * @param string $url * @param array $postData * @param Client $client * @return Zend\Http\Response * @author Christopher */ protected static function doRequest($url, array $postData = null, $method = Request::METHOD_GET) { $client = self::getClientInstance(); $client->setUri($url); $client->setMethod($method); if ($postData !== null) { $client->setParameterPost($postData); } $response = $client->send(); if ($response->isSuccess()) { return JsonDecoder::decode($response->getBody(), Json::TYPE_ARRAY); } else { $logger = new Logger(); $logger->addWriter(new Stream('data/logs/apiclient.log')); $logger->debug($response->getBody()); return FALSE; } }
/** * The default json decode type should be TYPE_OBJECT * * @group ZF-8618 */ public function testDefaultTypeObject() { $this->assertInstanceOf('stdClass', Json\Decoder::decode('{"var":"value"}')); }
/** * Handles all GET requests to a web service * * @param string $path Path * @param array $parms Array of GET parameters * @param string $type Type of a request ("xml"|"json") * @return mixed decoded response from web service * @throws Zend_Service_Delicious_Exception */ public function makeRequest($path, array $params = array(), $type = 'xml') { // if previous request was made less then 1 sec ago // wait until we can make a new request $timeDiff = microtime(true) - self::$lastRequestTime; if ($timeDiff < 1) { usleep((1 - $timeDiff) * 1000000); } $this->httpClient->setAuth($this->authUname, $this->authPass); $this->httpClient->setOptions(array('ssltransport' => 'ssl')); $request = new HttpRequest(); $request->setMethod(HttpRequest::METHOD_GET); switch ($type) { case 'xml': $request->setUri(self::API_URI); break; case 'json': $params['raw'] = true; $request->setUri(self::JSON_URI); break; default: throw new Exception('Unknown request type'); } self::$lastRequestTime = microtime(true); $request->getQuery()->fromArray($params); $response = $this->httpClient->send($request); if (!$response->isSuccess()) { throw new Exception("Http client reported an error: '{$response->getReasonPhrase()}'"); } $responseBody = $response->getBody(); switch ($type) { case 'xml': $dom = new \DOMDocument(); if (!@$dom->loadXML($responseBody)) { throw new Exception('XML Error'); } return $dom; case 'json': return \Zend\Json\Decoder::decode($responseBody); } }
/** * Handles all GET requests to a web service * * @param string $path Path * @param array $parms Array of GET parameters * @param string $type Type of a request ("xml"|"json") * @return mixed decoded response from web service * @throws Zend_Service_Delicious_Exception */ public function makeRequest($path, array $parms = array(), $type = 'xml') { // if previous request was made less then 1 sec ago // wait until we can make a new request $timeDiff = microtime(true) - self::$_lastRequestTime; if ($timeDiff < 1) { usleep((1 - $timeDiff) * 1000000); } $this->_rest->getHttpClient()->setAuth($this->_authUname, $this->_authPass); switch ($type) { case 'xml': $this->_rest->setUri(self::API_URI); break; case 'json': $parms['raw'] = true; $this->_rest->setUri(self::JSON_URI); break; default: throw new Exception('Unknown request type'); } self::$_lastRequestTime = microtime(true); $response = $this->_rest->restGet($path, $parms); if (!$response->isSuccessful()) { throw new Exception("Http client reported an error: '{$response->getMessage()}'"); } $responseBody = $response->getBody(); switch ($type) { case 'xml': $dom = new \DOMDocument(); if (!@$dom->loadXML($responseBody)) { throw new Exception('XML Error'); } return $dom; case 'json': return \Zend\Json\Decoder::decode($responseBody); } }
/** * Perform a request to the API * * @param string $url * @param array $postData * @param Client $client * @return Zend\Http\Response * @author Christopher */ protected static function doRequest($url, array $postData = null, $method = Request::METHOD_POST) { $client = self::getClientInstance(); $client->setUri($url); $client->setMethod($method); if ($postData !== null) { $client->setParameterPost($postData); } $response = $client->send(); if ($response->isSuccess()) { return JsonDecoder::decode($response->getBody(), Json::TYPE_ARRAY); } else { return FALSE; } }
/** * Gibt die Daten der Accountclientmessage zurück * @return array */ public function getData() { return \Zend\Json\Decoder::decode($this->data, \Zend\Json\Json::TYPE_ARRAY); }
/** * Send Http request to retrieve datas * @access protected * @param string $service Service to call * @param string $type Resource type to retrieve (for search service) * @param array $parameters Parameters used for request * @throws \Zend\Http\Exception\RuntimeException * @return \stdClass */ protected function send($service, $type, $parameters) { // reset old parameters $this->getHttpClient()->resetParameters(); // setup Http headers $headers = array(ContentTypeHeader::fromString('Content-Type: ' . HttpClient::ENC_URLENCODED)); // setup HttpClient $this->getHttpClient()->setMethod(HttpRequest::METHOD_GET); $this->getHttpClient()->setParameterGet($parameters); $this->getHttpClient()->setHeaders($headers); // generate URI and set to HttpClient $this->getHttpClient()->setUri($this->generateURI($service, $type)); // get HttpResponse $this->response = $this->getHttpClient()->send(); // is HttpRequest ok ? if (!$this->response->isOk()) { // throw RuntimeException throw new ZendRuntimeException(sprintf('Invalid status code: %d', $this->response->getStatusCode())); } // return decode object return \Zend\Json\Decoder::decode($this->response->getBody()); }