public function facebook(Request $request)
 {
     $accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
     $graphApiUrl = 'https://graph.facebook.com/v2.5/me';
     $params = ['code' => $request->input('code'), 'client_id' => $request->input('clientId'), 'redirect_uri' => $request->input('redirectUri'), 'client_secret' => '76cd1014c10586c33f3e13f03929a221'];
     $client = new \GuzzleHttp\Client();
     // Step 1. Exchange authorization code for access token.
     $accessToken = json_decode($client->get($accessTokenUrl, ['query' => $params])->getBody(), true);
     // Step 2. Retrieve profile information about the current user.
     $profile = json_decode($client->get($graphApiUrl, ['query' => $accessToken])->getBody(), true);
     // Step 3a. If user is already signed in then link accounts.
     if ($request->header('Authorization')) {
         $user = User::where('facebook', '=', $profile['id']);
         if ($user->first()) {
             return response()->json(['message' => 'There is already a Facebook account that belongs to you'], 409);
         }
         $token = explode(' ', $request->header('Authorization'))[1];
         $payload = (array) JWT::decode($token, Config::get('jwt.secret'), array('HS256'));
         $user = User::find($payload['sub']);
         $user->facebook = $profile['id'];
         $user->displayName = $user->displayName ?: $profile['name'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     } else {
         $user = User::where('facebook', '=', $profile['id']);
         if ($user->first()) {
             return response()->json(['token' => $this->createToken($user->first())]);
         }
         $user = new User();
         $user->facebook = $profile['id'];
         $user->displayName = $profile['name'];
         $user->save();
         return response()->json(['token' => $this->createToken($user)]);
     }
 }
Пример #2
1
 /**
  * @param ParametersInterface|null $params
  * @return CountriesResponse
  */
 public function execute(ParametersInterface $params = null)
 {
     $client = new \GuzzleHttp\Client();
     $res = $client->request('GET', sprintf('http://peakclimber.com/api/countries/%s.json', $params->getParameter('id')));
     $resArr = json_decode($res->getBody(), true);
     return new CountriesResponse($resArr);
 }
Пример #3
0
 public function getGeoInfo($ip)
 {
     $cache = Cache::getInstance();
     $return = $cache->get('geo:' . $ip);
     if ($cache->wasResultFound()) {
         if (DEBUG_BAR) {
             Bootstrap::getInstance()->debugbar['messages']->addMessage("Cached GeoInfo: {$ip}");
         }
         return $return;
     }
     $client = new \GuzzleHttp\Client();
     //'https://geoip.maxmind.com/geoip/v2.1/city/me
     $res = $client->get($this->url . $ip, array('auth' => array($this->user, $this->password)));
     $body = $res->getBody(true);
     $json = json_decode($body);
     $return = array('countryCode' => $json->country->iso_code, 'countryName' => $json->country->names->en, 'state' => $json->subdivisions[0]->names->en, 'city' => $json->city->names->en);
     if (empty($return['city'])) {
         $return['city'] = 'Unknown';
     }
     if (empty($return['state'])) {
         $return['state'] = 'Unknown';
     }
     $cache->set('geo:' . $ip, $return, 3600);
     return $return;
 }
Пример #4
0
 private function getMoney($idTask)
 {
     $client = new GuzzleHttp\Client();
     $post = ['ajax' => 1, 'id' => $idTask, 'page' => 'check', 'rand' => rand(1, 99999999999.0)];
     $money = $client->post($this->config->item('url') . 'index.php?act=ajax', ['headers' => ['user-agent' => $this->config->item('agent'), 'cookie' => 'hash=' . $this->config->item('cookie')['hash'] . '; id=' . $this->config->item('cookie')['id'] . '; r=1; g=1466098105', 'X-Requested-With' => 'XMLHttpRequest'], 'form_params' => $post]);
     return $money->getBody();
 }
Пример #5
0
 /**
  * Lookup entitete direktno preko GuzzleHttp
  * 
  * @param string $entity ime entitete - kratka oblika 
  * @param string $ident ident po katerem povprašujemo
  * @param boolean $returnIdOnly a vrnemo samo id ali pa celi lookup objekt
  * @param string $route dodatek k default lookup url-ju
  * @return typeSkoči po ID entitete 
  */
 public function lookupEntity($entity, $ident, $returnIdOnly = true, $route = '')
 {
     $br = $this->getModule('PhpBrowser');
     $client = new \GuzzleHttp\Client();
     /* @var $a \Codeception\Module\Asserts */
     $a = $this->getModule('Asserts');
     if ($route && substr($route, 0, 1) !== '/') {
         $route = '/' . $route;
     }
     $url = $br->_getUrl() . "/lookup/{$entity}{$route}?";
     if (preg_match(self::ID_RE, $ident)) {
         $url .= "ids={$ident}&page=1&per_page=30";
     } else {
         $url .= "ident=" . urlencode($ident) . "&page=1&per_page=30";
     }
     $res = $client->get($url, ['auth' => [\IfiTest\AuthPage::$admin, \IfiTest\AuthPage::$adminPass]]);
     //        codecept_debug($res->getHeader('content-type')[0]);
     $a->assertEquals('application/json; charset=utf-8', $res->getHeader('content-type')[0], "Lookup {$entity} z identom {$ident} ni vrnil pravega content type");
     $json = $res->getBody();
     $decoded = json_decode($json, true);
     $a->assertEquals(JSON_ERROR_NONE, json_last_error(), "Lookup {$entity} z identom {$ident} ni vrnil pravilnega json-a");
     $a->assertEquals("200", $res->getStatusCode(), "Lookup {$entity} z identom {$ident} ni vrnil pravega statusa ");
     $a->assertTrue(count($decoded['data']) > 0, "Lookup {$entity} z identom {$ident} ni našel entitete.");
     if ($returnIdOnly) {
         return $decoded['data'][0]['id'];
     } else {
         return $decoded['data'][0];
     }
 }
Пример #6
0
 /**
  * Получение токена по рефреш токену
  *
  * @param string $refToken
  *
  * @return array|null $tokenData
  */
 public function getAccessTokenByRefreshToken($refToken)
 {
     $params = ['grant_type' => 'refresh_token', 'client_secret' => $this->secretKey, 'client_id' => $this->appId, 'refresh_token' => $refToken];
     $client = new \GuzzleHttp\Client();
     $res = $client->request('POST', $this->tokenUrl, ['form_params' => $params]);
     return json_decode($res->getBody()->getContents(), true);
 }
Пример #7
0
 public function searchDescription($description)
 {
     $URL = "http://sap.prefeitura.unicamp.br/sap/pesquisa_achados_perdidos.jsf?javax.faces.ViewState={$this->viewState}&javax.faces.partial.ajax=true&javax.faces.partial.execute=%40all&javax.faces.partial.render=mainForm%3AmainOutputPanel&javax.faces.source=mainForm%3Aj_idt44&mainForm=mainForm&mainForm%3AfilterDataFinal_input=&mainForm%3AfilterDataInicio_input=&mainForm%3AfilterIdentificacao={$description}&mainForm%3AfilterLocalEncontrado=&mainForm%3Aj_idt34_focus=&mainForm%3Aj_idt34_input=&mainForm%3Aj_idt44=mainForm%3Aj_idt44";
     $client = new \GuzzleHttp\Client(['cookies' => True, 'headers' => ['Cookie' => $this->cookie]]);
     $response = $client->post($URL);
     return $response->getBody()->getContents();
 }
Пример #8
0
 /**
  * Init api key and secret key with mail and password
  * @param $mail
  * @param $password
  * @return AccessToken[]
  * @throws InvalidRequestError
  * @throws ResourceNotFoundException
  * @throws ServiceException
  * @throws UnauthorizedException
  */
 public static function Authenticate($mail, $password)
 {
     $body = ["mail" => $mail, "password" => $password];
     $client = new GuzzleHttp\Client();
     $res = $client->request('POST', Itwapp::$apiBase . '/api/v1/auth/', ['json' => $body, 'exceptions' => false]);
     if ($res->getStatusCode() == 200) {
         $json = json_decode($res->getBody(), true);
         $all = array();
         foreach ($json as $auth) {
             $all[] = new AccessToken($auth["apiKey"], $auth["secretKey"], $auth["company"]);
         }
         return $all;
     } else {
         switch ($res->getStatusCode()) {
             case 401:
                 throw new UnauthorizedException();
                 break;
             case 400:
                 throw new InvalidRequestError();
                 break;
             case 404:
                 throw new ResourceNotFoundException();
                 break;
             case 503:
             case 500:
             default:
                 throw new ServiceException();
         }
     }
 }
Пример #9
0
 protected function getFeed($count = 5)
 {
     try {
         $countKey = $this->cacheKey . $count;
         if (null !== $this->cacheProvider && $this->cacheProvider->contains($countKey)) {
             return $this->cacheProvider->fetch($countKey);
         }
         $client = new \GuzzleHttp\Client();
         $params = ['query' => ['access_token' => $this->accessToken, 'limit' => $count, 'fields' => implode(',', $this->fields)]];
         /*
          * Filter by date range
          */
         if (null !== $this->since && $this->since instanceof \Datetime) {
             $params['query']['since'] = $this->since->getTimestamp();
         }
         if (null !== $this->until && $this->until instanceof \Datetime) {
             $params['query']['until'] = $this->until->getTimestamp();
         }
         $response = $client->get('https://graph.facebook.com/' . $this->pageId . '/posts', $params);
         $body = json_decode($response->getBody());
         if (null !== $this->cacheProvider) {
             $this->cacheProvider->save($countKey, $body->data, $this->ttl);
         }
         return $body->data;
     } catch (ClientException $e) {
         return ['error' => $e->getMessage()];
     }
 }
Пример #10
0
 /**
  * Performs the test.
  *
  * @return \Jyxo\Beholder\Result
  */
 public function run() : \Jyxo\Beholder\Result
 {
     // The \GuzzleHttp library is required
     if (!class_exists(\GuzzleHttp\Client::class)) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Guzzle library missing');
     }
     try {
         $httpClient = new \GuzzleHttp\Client();
         $httpRequest = new \GuzzleHttp\Psr7\Request('GET', $this->url, ['User-Agent' => 'JyxoBeholder']);
         $httpResponse = $httpClient->send($httpRequest, [\GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5, \GuzzleHttp\RequestOptions::TIMEOUT => 10]);
         if (200 !== $httpResponse->getStatusCode()) {
             throw new \Exception(sprintf('Http error: %s', $httpResponse->getReasonPhrase()));
         }
         if (isset($this->tests['body'])) {
             $body = (string) $httpResponse->getBody();
             if (strpos($body, $this->tests['body']) === false) {
                 $body = trim(strip_tags($body));
                 throw new \Exception(sprintf('Invalid body: %s', \Jyxo\StringUtil::cut($body, 128)));
             }
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS, $this->url);
     } catch (\Exception $e) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $e->getMessage());
     }
 }
Пример #11
0
 /**
  * Fetch data.
  *
  * @param string $path
  * @param array $params
  * @param string $tag
  * @param int $cacheLifetime
  * @param bool $forceFetch
  * @return array|mixed
  */
 public function fetchData($path, $params = [], $tag = '', $cacheLifetime = 0, $forceFetch = false)
 {
     // Set default values.
     $this->code = 200;
     $this->message = '';
     $fetch = true;
     $data = Cache::load($this->prefix, $path, $params, $cacheLifetime);
     if (!$forceFetch && count($data) > 0) {
         $fetch = false;
     }
     if ($fetch) {
         // Build and request data.
         $this->url = $this->buildUrl($path, $params);
         try {
             $client = new \GuzzleHttp\Client();
             $result = $client->get($this->url);
             if ($result->getStatusCode() == 200) {
                 $data = json_decode($result->getBody(), true);
             }
         } catch (\Exception $e) {
             $this->code = $e->getCode();
             $this->message = $e->getMessage();
         }
         // Save cache.
         if ($cacheLifetime > 0) {
             Cache::save($this->prefix, $path, $params, $data);
         }
     }
     // Extract on tag.
     if ($tag != '' && isset($data[$tag])) {
         $data = $data[$tag];
     }
     return $data;
 }
Пример #12
0
 public function parse($cms, $cms_options)
 {
     $url = $cms_options['version_page'];
     if (empty($url)) {
         throw new EmptyUrlException("URL must be set for '{$cms}'. We can not parse empty url.");
     }
     // fetch url and get the version id
     $client = new \GuzzleHttp\Client();
     try {
         $res = $client->get($url, array('verify' => false));
     } catch (RequestException $e) {
         $status_code = $e->getCode();
         throw new EmptyUrlException("URL '{$url}'' returned status code: {$status_code}. Was expecting 200.");
     }
     $status_code = $res->getStatusCode();
     if ($res->getStatusCode() != 200) {
         throw new EmptyUrlException("URL '{$url}'' returned status code: {$status_code}. Was expecting 200.");
     }
     $body = $res->getBody();
     // loop through all parsers and try to get the cms value.
     // each CMS should have only one parser so once one parser has committed to do the job don't try the other
     // parsers, they should not match
     $version_found = false;
     foreach ($this->parsers as $parser) {
         // can the parser do anything with this content?
         if ($parser->isParser($cms_options['parser'])) {
             $version_found = $parser->parse($body, $cms_options);
             break;
         }
     }
     return $version_found;
 }
Пример #13
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $config = $this->setConfiguraton($input);
     $client = new \GuzzleHttp\Client(['defaults' => ['allow_redirects' => false, 'timeout' => 5, 'connect_timeout' => 5]]);
     /** @var Instance $instance */
     foreach ($config->getInstances() as $instance) {
         $requests[] = $client->createRequest('HEAD', $instance->getUrl());
     }
     $options = [];
     Pool::send($client, $requests, ['complete' => function (CompleteEvent $event) {
     }, 'error' => function (ErrorEvent $event) use($config) {
         $instance = $config->findInstanceByUrl($event->getRequest()->getUrl());
         if ($instance == null) {
             throw new \RuntimeException('Instance not found');
         }
         if (!$event->getException()->hasResponse()) {
             $raven = new \Raven_Client($instance->getSentryDsn());
             $event_id = $raven->getIdent($raven->captureMessage(sprintf('The website %s with url -> %s is down or has a problem', $instance->getName(), $event->getRequest()->getUrl()), [], \Raven_Client::FATAL));
             if ($raven->getLastError() !== null) {
                 printf('There was an error sending the event to Sentry: %s', $raven->getLastError());
             }
             $error_handler = new \Raven_ErrorHandler($raven);
             $error_handler->registerExceptionHandler();
             $error_handler->registerErrorHandler();
             $error_handler->registerShutdownFunction();
         }
     }]);
 }
Пример #14
0
 protected function _checkLatestVersion()
 {
     $client = new \GuzzleHttp\Client();
     $response = $client->get(VeerApp::VEERCOREURL . "/releases", ['verify' => false]);
     $res = json_decode($response->getBody());
     return head($res)->tag_name;
 }
Пример #15
0
 public static function getOnlineStreams()
 {
     $streams = [];
     $client = new \GuzzleHttp\Client(['headers' => ['Client-ID' => 'ModpackIndex', 'Accept' => 'application/vnd.twitchtv.v3+json']]);
     $response = $client->get('https://api.twitch.tv/kraken/streams?game=Minecraft&limit=100');
     if ($response->getStatusCode() != 200) {
         return false;
     }
     $raw_body = $response->getBody();
     $decoded_body = json_decode($raw_body);
     $channel_total = $decoded_body->_total;
     foreach ($decoded_body->streams as $stream) {
         $stream_id = $stream->channel->_id;
         $streams[$stream_id] = $stream;
     }
     if ($channel_total > 100) {
         $i = 100;
         while ($i <= $channel_total) {
             $response = $client->get('https://api.twitch.tv/kraken/streams?game=Minecraft&limit=100&offset=' . $i);
             $raw_body = $response->getBody();
             $decoded_body = json_decode($raw_body);
             foreach ($decoded_body->streams as $stream) {
                 $stream_id = $stream->channel->_id;
                 $streams[$stream_id] = $stream;
             }
             $i = $i + 100;
         }
     }
     if (!$decoded_body) {
         return false;
     } else {
         return $streams;
     }
 }
Пример #16
0
 public static function FormSubmit($form)
 {
     if (WEBHOOKS_URL != '') {
         $client = new GuzzleHttp\Client();
         $client->post(WEBHOOKS_URL, ['headers' => ['X-Action' => 'Form.Submit'], 'json' => $form]);
     }
 }
Пример #17
0
 public function getRecentPosts()
 {
     $client = new \GuzzleHttp\Client(['base_uri' => $this->baseUri]);
     $response = $client->request('GET', 'posts/recent', $this->options());
     $body = $response->getBody();
     return $body->getContents();
 }
Пример #18
0
 /**
  * @param $action String the action to call
  * @throws InvalidRequestError
  * @throws ResourceNotFoundException
  * @throws ServiceException
  * @throws UnauthorizedException
  * @return mixed
  */
 public static function delete($action)
 {
     $signedRequest = ApiRequest::sign_request("DELETE", $action);
     $client = new GuzzleHttp\Client();
     $res = $client->request('DELETE', Itwapp::$apiBase . $signedRequest, ['exceptions' => false]);
     return ApiRequest::parse_result($res);
 }
Пример #19
0
 /**
  * file_get_content request with additional params
  * @param $purpose
  * @param $additional_params
  *
  * @return xml?
  */
 private function gRequest($purpose, $additional_params = [])
 {
     $client = new \GuzzleHttp\Client();
     $url = $this->BuildURL($this->BuildQuery($purpose, $additional_params));
     $response = $client->get($url);
     dd($response);
 }
Пример #20
0
 public function request($method, $request_body)
 {
     $client = new GuzzleHttp\Client();
     $response = $client->post($this->url, array('verify' => false, 'headers' => array('X-EBAY-API-COMPATIBILITY-LEVEL' => $this->compatability_level, 'X-EBAY-API-DEV-NAME' => $this->dev_id, 'X-EBAY-API-APP-NAME' => $this->app_id, 'X-EBAY-API-CERT-NAME' => $this->cert_id, 'X-EBAY-API-SITEID' => $this->site_id, 'X-EBAY-API-CALL-NAME' => $method), 'body' => $request_body));
     $body = $response->xml();
     return $body;
 }
Пример #21
0
 /**
  * Execute the job.
  *
  */
 public function handle()
 {
     $client = new \GuzzleHttp\Client();
     $res = $client->get("https://www.tulsapolice.org/live-calls-/police-calls-near-you.aspx");
     $data = (string) $res->getBody();
     if ($res->getStatusCode() != 200) {
         throw new \Exception('Couldn\'t retrieve crime data');
     }
     $classes = ['accident' => ['/coll/', '/collision/', '/crash/', '/non inj/'], 'serious' => ['/burglary/', '/robbery/', '/homicide/', '/shooting/', '/shots/', '/theft/', '/missing/', '/intrusion/', '/doa/', '/suicide/', '/holdup/', '/stabbing/', '/assault/', '/weapon/'], 'drunk_driver' => ['/drunk/']];
     preg_match_all('/<td .+>(.+)<\\/td><td>(.+)<\\/td>/sU', $data, $matches);
     $scraped_crimes = [];
     foreach ($matches[1] as $key => $val) {
         foreach ($classes as $class => $patterns) {
             foreach ($patterns as $pattern) {
                 if (preg_match($pattern, strtolower($val))) {
                     $class_val = $class;
                 }
             }
         }
         $crime = ['description' => $val, 'address' => ucwords(strtolower($matches[2][$key])), 'class' => isset($class_val) ? $class_val : 'other'];
         $crimeModel = \App\Crime::firstOrCreate($crime);
         $crimeModel->active = true;
         $crimeModel->save();
         $scraped_crimes[] = $crimeModel->toArray();
         unset($class_val);
     }
     $expired = \App\Crime::where('updated_at', '<', \Carbon\Carbon::now()->subMinutes(6)->toDateTimeString())->update(['active' => false]);
     return ['expired' => $expired, 'scraped' => count($scraped_crimes)];
 }
Пример #22
0
 /**
  * @param string $endpoint
  * @param int $since_time_stamp
  * @return array
  * @throws Exception
  */
 public function getSamplesDataFromEndpointSinceTimestamp($endpoint, $since_time_stamp)
 {
     $client = new GuzzleHttp\Client();
     $response = $client->get($endpoint);
     if ($response->getStatusCode() !== 200) {
         throw new Exception('invalid status code!');
     }
     $content_type = $response->getHeader('content-type');
     if (empty($content_type)) {
         throw new Exception('invalid content type!');
     }
     if ($content_type !== 'application/json') {
         throw new Exception('invalid content type!');
     }
     $json = $response->getBody()->getContents();
     $response = json_decode($json, true);
     if (!isset($response['datapoints'])) {
         throw new Exception('missing response datapoints!');
     }
     $datapoints = array();
     foreach ($response['datapoints'] as $datapoint) {
         if (count($datapoint) != 2) {
             continue;
         }
         $time_stamp = $datapoint[1];
         if ($time_stamp <= $since_time_stamp) {
             continue;
         }
         $datapoints[] = $datapoint;
     }
     return $datapoints;
 }
Пример #23
0
 public function kepco_bid_detail($job)
 {
     echo $job->workload(), PHP_EOL;
     $workload = Json::decode($job->workload());
     try {
         $httpClient = new \GuzzleHttp\Client(['base_uri' => 'http://203.248.44.161', 'cookies' => true, 'headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Content-Type' => 'application/json', 'X-Requested-With' => 'XMLHttpRequest', 'Accept-Language' => 'ko', 'Accept-Encoding' => 'gzip, deflate', 'DNT' => '1', 'Pragma' => 'no-cache', 'Connection' => 'Keep-Alive', 'Accept' => '*/*', 'Referer' => 'http://203.248.44.161/mdi.do?theme=default', 'X-CSRF-TOKEN' => $this->csrf_token, 'Cookie' => $this->cookie]]);
         $response = $httpClient->request('POST', '/router', ['json' => [['action' => 'smartsuit.ui.etnajs.pro.rfx.sp.BidDetailController', 'method' => 'findBidBasicInfo', 'tid' => 51, 'type' => 'rpc', 'data' => [$workload['id']]], ['action' => 'smartsuit.ui.etnajs.pro.rfx.sp.BidDetailController', 'method' => 'findBidChangeTimeDetailList', 'tid' => 52, 'type' => 'rpc', 'data' => [['bidFileType' => 'Bid', 'bidId' => $workload['id'], 'fileGroupId' => 'ProductBidFileGroup', 'limit' => 100, 'page' => 1, 'start' => 0, 'type' => 'Bid']]], ['action' => 'smartsuit.ui.etnajs.pro.rfx.sp.BidDetailController', 'method' => 'findBidItems', 'tid' => 53, 'type' => 'rpc', 'data' => [['bidFileType' => 'Bid', 'bidId' => $workload['id'], 'fileGroupId' => 'ProductBidFileGroup', 'limit' => 100, 'page' => 1, 'start' => 0, 'type' => 'Bid']]], ['action' => 'smartsuit.ui.etnajs.pro.rfx.sp.BidDetailController', 'method' => 'findProgressStateSPList', 'tid' => 54, 'type' => 'rpc', 'data' => [['bidFileType' => 'Bid', 'bidId' => $workload['id'], 'fileGroupId' => 'ProductBidFileGroup', 'limit' => 100, 'page' => 1, 'start' => 0, 'type' => 'Bid']]], ['action' => 'smartsuit.ui.etnajs.pro.rfx.sp.BidDetailController', 'method' => 'getFileItemList', 'tid' => 55, 'type' => 'rpc', 'data' => [['bidFileType' => 'Bid', 'bidId' => $workload['id'], 'fileGroupId' => 'ProductBidFileGroup', 'limit' => 100, 'page' => 1, 'start' => 0, 'type' => 'Bid']]]]]);
         $body = $response->getBody();
         $json = Json::decode($body);
         file_put_contents(\Yii::getAlias('@vendor') . '/didwjdgks/kepco/temp/' . $workload['id'], \yii\helpers\VarDumper::dumpAsString($json));
         foreach ($json as $row) {
             switch ($row['method']) {
                 case 'findBidBasicInfo':
                     $findBidBasicInfo = $row['result'];
                     break;
                 case 'findBidChangeTimeDetailList':
                     $findBidChangeTimeDetail = $row['result'];
                     break;
                 case 'findBidItems':
                     $findBidItems = $row['result'];
                     break;
                 case 'findProcessStateSPList':
                     $findProcessStateSPList = $row['result'];
                     break;
                 case 'getFileItemList':
                     $getFileItemList = $row['result'];
                     break;
             }
         }
         echo ' > 입찰참가등록마감일시: ' . $findBidBasicInfo['bidAttendRequestCloseDateTime'], PHP_EOL;
     } catch (\Exception $e) {
         echo Console::ansiFormat($e->getMessage(), [Console::FG_RED]), PHP_EOL;
         return;
     }
 }
Пример #24
0
 /**
  * @inherit
  */
 public function handle()
 {
     $formatter = new Formatter();
     $data = $formatter->getData($this->getInspector());
     $json = json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
     $data = [];
     $data['event'] = 'exception';
     //$data['event-id'] = Uuid::uuid4();
     $data['datetime'] = date('Y-m-d H:i:s');
     $data['json'] = $json;
     /*
     if ($user) {
         $data['user'] = [
             'name' => $user->getName(),
             'display_name' => $user->getDisplayName(),
             'email' => $user->getEmail(),
             'mobile' => $user->getMobile()
         ];
     }
     */
     $verify = __DIR__ . '/../../cacert.pem';
     if (!file_exists($verify)) {
         throw new RuntimeException($verify . ' not found');
     }
     $headers = ['Content-Type' => 'application/json'];
     $guzzle = new \GuzzleHttp\Client(['headers' => $headers, 'verify' => $verify]);
     $response = $guzzle->request('POST', $this->url, ['json' => $data]);
     return Handler::DONE;
 }
Пример #25
0
 private function fetchResponse($api_url)
 {
     $http_client = new \GuzzleHttp\Client(['base_uri' => $api_url]);
     $response = $http_client->request('GET', '');
     $responseJson = $response->getBody()->getContents();
     return array($responseJson, $response);
 }
Пример #26
0
function post_guzzle($url, $params)
{
    $data = json_encode($params);
    $client = new GuzzleHttp\Client();
    $response = $client->post($url, ['body' => $data]);
    return $response->json();
}
 /**
  * Search for a company
  * @param  string $query Query
  * @return array Results
  */
 static function search($query)
 {
     $client = new \GuzzleHttp\Client(array('cookies' => true));
     $response = $client->request('GET', self::$_BASEURL . 'services/entreprise/rest/recherche/parPhrase', array('query' => array('phrase' => $query, 'typeProduitMisEnAvant' => 'EXTRAIT')));
     $json = $response->getBody();
     $result = json_decode($json);
     $client->request('GET', self::$_BASEURL . 'societes/recherche-entreprise-dirigeants/' . 'resultats-entreprise-dirigeants.html');
     $response = $client->request('GET', 'https://www.infogreffe.fr/services/entreprise/rest/recherche/' . 'derniereRechercheEntreprise');
     $response = json_decode($response->getBody());
     $idsRCS = $idsNoRCS = array();
     foreach ($response->entrepRCSStoreResponse->items as $result) {
         if (isset($result->id)) {
             $idsRCS[] = $result->id;
         }
     }
     foreach ($response->entrepHorsRCSStoreResponse->items as $result) {
         if (isset($result->id)) {
             $idsNoRCS[] = $result->id;
         }
     }
     $items = array();
     if (!empty($idsRCS)) {
         $resultRCS = $client->request('POST', self::$_BASEURL . 'services/entreprise/rest/recherche/' . 'resumeEntreprise?typeRecherche=ENTREP_RCS_ACTIF', array('json' => $idsRCS, 'headers' => array('Content-Type' => 'text/plain')));
         $items = array_merge($items, json_decode($resultRCS->getBody())->items);
     }
     if (!empty($idsNoRCS)) {
         $resultNoRCS = $client->request('POST', self::$_BASEURL . 'services/entreprise/rest/recherche/' . 'resumeEntreprise?typeRecherche=ENTREP_HORS_RCS', array('json' => $idsNoRCS, 'headers' => array('Content-Type' => 'text/plain')));
         $items = array_merge($items, json_decode($resultNoRCS->getBody())->items);
     }
     return self::_getArrayFromJSON($items);
 }
 public function postRing($uuid, Request $req)
 {
     try {
         $bell = Bell::where('uuid', $uuid)->first();
         $user = $bell->user;
         $file = '';
         if ($req->hasFile('image')) {
             $image = $req->file('image');
             if ($image->isValid()) {
                 $file = Uuid::generate(1)->string;
                 $image->move(public_path() . '/img/uploads/', $file);
             }
         }
         $ring = Ring::create(['user_id' => $user->id, 'bell_id' => $bell->id, 'file' => $file]);
         $ring->save();
         $clients = $user->push_clients;
         if (!$clients->isEmpty() && $bell->active == 1) {
             $token = [];
             foreach ($clients as $client) {
                 $token[] = $client->token;
             }
             $http = new \GuzzleHttp\Client();
             $res = $http->request('POST', 'https://android.googleapis.com/gcm/send', ['headers' => ['Authorization' => 'key=' . env('SMARTBELL_GCM')], 'json' => ["registration_ids" => $token, "data" => ["image" => $file, "name" => $bell->name]]]);
         }
         return ['success'];
     } catch (\Exception $e) {
         return ['failure'];
     }
 }
Пример #29
0
 /**
  * Make API request.
  *
  * @throws \Exception
  *
  * @param string     $method     HTTP method [GET / POST / PUT / DELETE].
  * @param string     $endpoint   API endpoint.
  * @param array      $data       The request body.
  * @param Pagination $pagination Set pagination values.
  *
  * @return boolean|array
  */
 public function request($method, $endpoint, array $data = array(), Pagination $pagination = null)
 {
     $headers = array('Content-Type' => 'application/json', 'Accept' => 'application/json');
     if ($pagination instanceof Pagination) {
         $headers['Range'] = 'records=' . $pagination->getStart() . '-' . $pagination->getEnd();
     }
     $client = new \GuzzleHttp\Client();
     $request = $client->createRequest($method, $this->apiUrl . $endpoint, array('body' => !empty($data) ? json_encode($data) : null, 'headers' => $headers));
     try {
         $response = $client->send($request);
         $body = $response->json();
         return $body;
     } catch (RequestException $e) {
         $response = $e->getResponse();
         $body = $response->json();
         switch ((int) $response->getStatusCode()) {
             case 400:
                 throw new Exception\ValidationException($body['results']['error']['message']);
                 break;
             case 401:
                 throw new Exception\AuthenticationException('Failed authentication.');
                 break;
             case 402:
                 throw new Exception\PaymentRequiredException('Payment required.');
                 break;
             case 404:
                 throw new Exception\NotFoundException('Resource not found.');
                 break;
             case 500:
                 throw new Exception\ServerException('Server error.');
                 break;
         }
     }
     return false;
 }
Пример #30
0
 /**
  * Main application logic
  */
 public static function run()
 {
     try {
         $httpClient = new GuzzleHttp\Client();
         $date = date('Y-m-d-h-i-s', time());
         $response = $httpClient->get(self::FORECAST_IMG_URL);
         $sImg = $response->getBody()->getContents();
         $img = imagecreatefromstring($sImg);
         $color = imagecolorat($img, self::MY_CORDS_X, self::MY_CORDS_Y);
         $rgb = imagecolorsforindex($img, $color);
         $red = $rgb['red'];
         $green = $rgb['green'];
         $blue = $rgb['blue'];
         if (!self::checkDefault($red, $green, $blue) && (self::checkRedLine($red) || self::checkAurora($red, $green, $blue))) {
             // Alert! We have a positive aurora forecast
             file_put_contents(sprintf("%s%s.img", self::ALERT_IMG_ARCHIVE, $date), $sImg);
             $ifHttpClient = new GuzzleHttp\Client();
             $ifHttpClient->get(self::IFTTT_TRIGGER_URL);
         }
         exit(0);
     } catch (\Exception $e) {
         var_dump($e);
         exit(1);
     }
 }