/** * Sets the response data. * @param Psr\Http\Message\ResponseInterface $response the response object. */ public function __construct(\Psr\Http\Message\ResponseInterface $response) { $this->response = $response; $body = (string) $response->getBody(); $this->body = \GuzzleHttp\json_decode($body, true); $this->statusCode = $response->getStatusCode(); }
private function setForecast() { $getFromApi = true; $recordFile = \Yii::getAlias('@frontend') . '/runtime/cache/forecast.json'; if (file_exists($recordFile)) { if (time() - filemtime($recordFile) < 3600) { $getFromApi = false; } } if ($getFromApi) { $url = "http://api.openweathermap.org/data/2.5/forecast?id=" . \Yii::$app->params['openweathermap']['city_id'] . "&APPID=" . \Yii::$app->params['openweathermap']['api_key'] . "&units=" . \Yii::$app->params['openweathermap']['units'] . "&cnt=24"; $contentFromApi = file_get_contents($url) ?: ''; $testForecast = \GuzzleHttp\json_decode($contentFromApi, true); if ($testForecast['cod'] == '404') { $url = "http://api.openweathermap.org/data/2.5/forecast?q=" . \Yii::$app->params['openweathermap']['city_name'] . ',' . \Yii::$app->params['openweathermap']['country_code'] . "&APPID=" . \Yii::$app->params['openweathermap']['api_key'] . "&units=" . \Yii::$app->params['openweathermap']['units'] . "&cnt=24"; $contentFromApi = file_get_contents($url) ?: ''; } $handle = fopen($recordFile, "wb"); if (fwrite($handle, $contentFromApi) === false) { throw new Exception(\Yii::t('front', 'Forecast file not writable!')); } fclose($handle); clearstatcache(); } if (file_exists($recordFile)) { $handle = fopen($recordFile, "rb"); $jsonContent = fread($handle, filesize($recordFile)); $this->_forecast = json_decode($jsonContent, true); fclose($handle); } else { throw new Exception(\Yii::t('front', 'Forecast file not exists')); } }
/** * Call the API w/ Guzzle. * parameter is a parameter in the url. Ex: neoapi.com/{parameter} * queryOpt are optional querry parameters. In most case, it has to be ['id' => id] or ['ids' => id,id,id] * Ex : neoapi.com?id=123 (where queryOpt = ['id' => 123] * * @param string|null $parameter * @param array $queryOpt * * @return array|\stdClass * @throws \Exception * @throws Gw2Exception */ public function callApi(string $parameter = null, array $queryOpt = []) { if (!empty($this->getApiKey())) { $queryOpt = array_merge($queryOpt, ['access_token' => $this->getApiKey()]); } $options = ['query' => $queryOpt]; // For not messing with query param when no parameters are sets $parameter = !empty($parameter) ? '/' . $parameter : null; $this->checkParameters($parameter); // Add some extra informations to the request if ($this->isDebug()) { $options = array_merge($options, ['debug' => true]); } if ($this->log) { $this->logger->log(Logger::INFO, 'Call to ' . $this->apiBase . $this->getVersion() . $this->endpoint . $parameter); $this->logger->log(Logger::INFO, json_encode($options)); } $response = $this->client->get($this->getVersion() . $this->endpoint . $parameter, $options); $result = $response->getBody()->getContents(); if (!in_array($response->getStatusCode(), ['200', '201', '202', '203', '204', '205', '206', '207', '208', '226'])) { $textError = !empty(json_decode($response->getBody())) ? json_decode($response->getBody())->text : ''; $result = json_encode(['status' => $response->getStatusCode(), 'error' => $textError]); if ($this->log) { $this->logger->log(Logger::ALERT, 'An error occured : status ' . $response->getStatusCode() . '. message : ' . $textError); } } return \GuzzleHttp\json_decode($result); }
protected function initKeywordsData() { if (!empty($this->decodedRaw)) { return; } $contents = $this->response->getBody()->getContents(); if (empty($contents)) { return; } $this->decodedRaw = \GuzzleHttp\json_decode($contents); if ($this->decodedRaw->results) { foreach ($this->decodedRaw->results as $k => $res) { if ($k == '_empty_') { $this->keywords[] = ['kw' => $res[0]->string, 'vol' => intval($res[0]->volume)]; continue; } foreach ($res as $keyword) { $volume = 0; if (!empty($keyword->volume)) { $volume = intval($keyword->volume) > 0 ? intval($keyword->volume) : 0; } $this->keywords[] = ['kw' => $keyword->string, 'vol' => $volume]; } } } }
public function json(array $config = []) { try { return \GuzzleHttp\json_decode((string) $this->getBody(), isset($config['object']) ? !$config['object'] : true, 512, isset($config['big_int_strings']) ? JSON_BIGINT_AS_STRING : 0); } catch (\InvalidArgumentException $e) { throw new ParseException($e->getMessage(), $this); } }
private function prepareResponse(ResponseInterface $response) { $json = \GuzzleHttp\json_decode($response->getBody()->getContents(), true); if (array_get($json, 'ok') === false) { throw new TelegramCoreException(array_get($json, 'description', 'error') . array_get($json, 'error_code'), array_get($json, 'error_code')); } return $json; }
public function generateApplicationForAccess($username, $password, $applicationName) { $client = new GuzzleClient(['cookies' => true, 'allow_redirects' => true]); // Login into the portal. $client->post('https://cloud.estimote.com/v1/login', ['headers' => ['Content-Type' => ' application/json'], 'json' => array('username' => $username, 'password' => $password)]); $response = $client->post('https://cloud.estimote.com/v1/applications', ['json' => ['name' => $applicationName, 'description' => $applicationName, 'template' => 'your-own-app']]); $json = \GuzzleHttp\json_decode($response->getBody(), true); return new ApplicationAuthorization($json['name'], $json['token']); }
protected function authenticate($username, $password, $integrator_key, $env, $version) { $auth_header = ['Username' => $username, 'Password' => $password, 'IntegratorKey' => $integrator_key]; $this->auth_header = \GuzzleHttp\json_encode($auth_header); $client = new Client(); $response = $client->request('GET', 'https://' . $env . '.docusign.net/restapi/' . $version . '/login_information', ['headers' => ['X-DocuSign-Authentication' => $this->auth_header]]); $content = \GuzzleHttp\json_decode((string) $response->getBody()); $this->accounts = $content->loginAccounts; }
/** * Retrieve the job feed associated with the configured company ID * * @param array $filters Optional filters with keys found in self::JOB_FEED_FILTERS * @return string * @throws Exception\JobviteException */ public function getJobFeed(array $filters = []) { $response = $this->client->request('GET', '/v1/jobFeed', ['base_uri' => $this->baseUri, 'query' => $this->buildQuery($filters, self::JOB_FEED_FILTERS)]); try { return \GuzzleHttp\json_decode((string) $response->getBody()); } catch (\InvalidArgumentException $invalidArgumentException) { throw new Exception\JobviteException('Unable to decode response as JSON.', 0, $invalidArgumentException); } }
/** * @param UriInterface $httpUri * @param string $method * @param array $data [OPTIONAL] * * @return array */ protected function proceed(UriInterface $httpUri, $method, array $data = []) { if (!empty($data)) { $response = $this->httpClient->request($method, $httpUri, ['headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'body' => 'JSONString=' . \GuzzleHttp\json_encode($data)]); } else { $response = $this->httpClient->request($method, $httpUri); } return \GuzzleHttp\json_decode($response->getBody()->getContents()); }
/** * Authentication */ public function auth() { $this->handlerStack->remove('reAuth'); $res = $this->client->post($this->config->get('authUri'), ['form_params' => ['client_id' => $this->config->get('clientId'), 'client_secret' => $this->config->get('clientSecret'), 'grant_type' => 'client_credentials', 'scope' => 'https://graph.microsoft.com/.default']]); $json = \GuzzleHttp\json_decode($res->getBody(), true); $now = new \DateTime('now', new \DateTimeZone('UTC')); $json['expires_in'] = $now->getTimestamp() + $json['expires_in']; $this->tokenStorage->write($json); }
function uploadImg($photosPost) { $dotenv = new \Dotenv\Dotenv(__DIR__ . '/../'); $dotenv->load(); $token = $_ENV['VK_ACCESS_TOKEN']; $user_uid = $_ENV['USER_UID']; $vk = \getjump\Vk\Core::getInstance()->apiVersion('5.5')->setToken($token); $url = 'https://api.vk.com/method/photos.getWallUploadServer?group_id=101646894&v=5.5&access_token=' . $token; $request = get_curl($url); $data = json_decode($request); $link = $data->response->upload_url; $photo = explode('/||/', $photosPost); $group_id = '101646894'; $postParams = array(); $index = 0; for ($i = 1; $i < count($photo); $i++) { $extention = explode(".", basename($photo[$i])); if ($extention[1] == 'gif') { echo 'You can\'t upload GIF'; die; } $index++; $path = __DIR__ . "/../images/" . basename($photo[$i]); file_put_contents($path, file_get_contents($photo[$i])); $postParams["file" . $index] = "@" . $path; } if ($index < 7) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $link); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); @curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams); $response = curl_exec($ch); $photoParams = json_decode($response); $photo = $photoParams->photo; $server = $photoParams->server; $url = 'https://api.vk.com/method/photos.saveWallPhoto?group_id=' . $group_id . '&v=5.5&photo=' . $photo . '&server=' . $server . '&hash=' . $photoParams->hash . '&access_token=' . $token; $an = get_curl($url); $save = json_decode($an)->response; $attachments = ""; for ($i = 0; $i < count($save); $i++) { $attachments = $attachments . "photo" . $user_uid . "_" . $save[$i]->id . ','; } $url = 'https://api.vk.com/method/wall.post?owner_id=-' . $group_id . '&from_group=1&attachments=' . $attachments . '&access_token=' . $token; $an = get_curl($url); if (!isset(\GuzzleHttp\json_decode($an)->response)) { echo "Unknown error"; return false; } else { echo "Images is successfully uploaded"; return true; } } else { echo "ERROR! You upload more than 6 images OR all your pics are GIFs !"; return false; } }
public function HTTPRequest($method, $url, $params) { $client = new Client(['base_uri' => $this->domain]); if ($method == self::METHOD_GET) { $res = $client->request($method, $url, ['query' => $params]); } else { $res = $client->request($method, $url, ['form_params' => $params]); } return \GuzzleHttp\json_decode($res->getBody()->getContents(), true); }
/** * Update one beacon. * * @param string $beaconMac The beacon MAC address. * @param BeaconUpdate $data The data to send. * @return boolean */ public function updateBeacon($beaconMac, BeaconUpdate $data) { try { $response = $this->client->post('beacons/' . $beaconMac . '/pending_settings', ['headers' => ['Content-Type' => 'application/json'], 'body' => $this->serializer->serialize($data, 'json')]); $json = \GuzzleHttp\json_decode($response->getBody(), true); return isset($json['status']) ? $json['status'] === 'ok' : false; } catch (ClientException $e) { throw $this->createApiException($e); } }
/** * Load the contents of the client session into the data array */ protected function load() { $cookieJar = isset($_SESSION[$this->sessionKey]) ? $_SESSION[$this->sessionKey] : null; $data = \GuzzleHttp\json_decode($cookieJar, true); if (is_array($data)) { foreach ($data as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie data"); } }
/** * */ public function login() { $body = ['grant_type' => 'password', 'client_id' => $this->config['client_id'], 'client_secret' => $this->config['client_secret'], 'username' => $this->config['username'], 'password' => $this->config['password']]; $response = $this->client->post('https://login.salesforce.com/services/oauth2/token', ['form_params' => $body])->getBody()->getContents(); $responseObject = \GuzzleHttp\json_decode($response); $this->id = $responseObject->id; $this->issuedAt = $responseObject->issued_at; $this->signature = $responseObject->signature; $this->accessToken = $responseObject->access_token; $this->instanceUrl = $responseObject->instance_url; $this->url = $responseObject->instance_url . $this->version['url']; }
/** * @param string $vhost * @param string $name * @param int $interval * * @return array */ public function getQueue($vhost, $name, $interval = 30) { $queueName = sprintf('%s/%s', urlencode($vhost), urlencode($name)); $url = sprintf('http://%s:%d/api/queues/%s?%s', $this->hostname, $this->port, $queueName, http_build_query(['lengths_age' => $interval, 'lengths_incr' => $interval, 'msg_rates_age' => $interval, 'msg_rates_incr' => $interval, 'data_rates_age' => $interval, 'data_rates_incr' => $interval])); $options = ['auth' => [$this->user, $this->password]]; if (version_compare(ClientInterface::VERSION, '6.0') >= 0) { $response = $this->httpClient->request('get', $url, $options); } else { $response = $this->httpClient->get($url, $options); } return \GuzzleHttp\json_decode($response->getBody()->getContents(), true); }
/** * Update devices. * * @param string|array $uniqueId The unique IDs to update. * @param string $deviceType The device type. One of the DEVICE_TYPE_* Device model constants. * @param DeviceModel $values The values for the device(s). * @return boolean * @throws \Speicher210\KontaktIO\Exception\ApiException */ public function update($uniqueId, $deviceType, DeviceModel $values) { $jsonSerialized = $this->serializer->serialize($values, 'json'); $values = \GuzzleHttp\json_decode($jsonSerialized, true); $values['uniqueId'] = implode(',', (array) $uniqueId); $values['deviceType'] = $deviceType; try { $response = $this->client->post('/device/update', ['form_params' => $values, 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded']]); return $response->getStatusCode() === 200; } catch (ClientException $e) { throw $this->createApiException($e); } }
/** * Response constructor. * @param ResponseInterface $responseInterface * @param string $type */ public function __construct(ResponseInterface $responseInterface, $type) { $this->setRaw($responseInterface); $this->setStatus($this->getRaw()->getStatusCode()); $contents = $this->getRaw()->getBody()->getContents(); $contents = \GuzzleHttp\json_decode($contents, true); if (array_key_exists('suggestions', $contents) && is_array($contents['suggestions'])) { foreach ($contents['suggestions'] as $suggestion) { $suggestion = new Suggestion($type, $suggestion); $this->suggestions[] = $suggestion; } } }
/** * Load cookies from a JSON formatted file. * * Old cookies are kept unless overwritten by newly loaded ones. * * @param string $filename Cookie file to load. * @throws \RuntimeException if the file cannot be loaded. */ public function load($filename) { $json = file_get_contents($filename); if (false === $json) { throw new \RuntimeException("Unable to load file {$filename}"); } elseif ($json === '') { return; } $data = \GuzzleHttp\json_decode($json, true); if (is_array($data)) { foreach (json_decode($json, true) as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie file: {$filename}"); } }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function dispatch(ServerRequestInterface $request, ResponseInterface $response) { $callStack = \GuzzleHttp\json_decode($request->getBody()->getContents()); if (!is_array($callStack)) { $callStack = [$callStack]; } $results = []; foreach ($callStack as $call) { $className = $this->classMap[$call->action]; $method = $call->method; $parameters = $call->data; $instance = GeneralUtility::makeInstance($className); $results[] = $this->buildResultFromResponse(call_user_func_array([$instance, $method], $parameters), $call); } $response->getBody()->write(json_encode($results)); return $response; }
/** * @param ClientException $clientException * * @return ApiException | SearchLimitException */ public static function createThrowable(ClientException $clientException) { $data = \GuzzleHttp\json_decode($clientException->getResponse()->getBody()->getContents()); $code = 0; $message = ''; if (!empty($data->error)) { $error = $data->error; if (!empty($error->code)) { $code = $error->code; } if (!empty($error->message)) { $message = $error->message; } } if ($code == SearchLimitException::EXCEPTION_CODE) { return new SearchLimitException($message); } return new ApiException($message, $code); }
public function queryOrder($receipt, $sandbox = false) { $url = $sandbox ? $this->sandboxRequestUrl : $this->requestUrl; try { $client = new Client(); $response = $client->request('POST', $url, [RequestOptions::JSON => ['receipt-data' => $receipt], RequestOptions::TIMEOUT => $this->timeout]); $contents = $response->getBody()->getContents(); $results = \GuzzleHttp\json_decode($contents, true); /** * 如果是在正式环境, 可能使用的是沙盒环境的receipt请求的 */ if (!$sandbox && isset($results['status']) && 21007 == $results['status']) { return call_user_func(__METHOD__, $receipt, true); } return isset($results['status']) && 0 == $results['status'] ? $results : false; } catch (GuzzleException $e) { return false; } }
public function messageAdmin(Request $request) { $this->validate($request, ['g-recaptcha-response' => 'required']); $client = new Client(); $captcha_response = $client->post('https://www.google.com/recaptcha/api/siteverify', ['query' => ['secret' => '6Ld39AkUAAAAAMboW5zfWXIZ2N1bBZ4VJCPCO2Yx', 'response' => $request->input('g-recaptcha-response')]]); $body = \GuzzleHttp\json_decode($captcha_response->getBody()->getContents()); if (!$body->success) { return redirect(url('/help'))->with("captcha_error", "Invalid Captcha"); } $investor = Auth::user()->investor; $admin = User::is('admin')->active()->orderBy('created_at', 'desc')->first(); $emails = ['admin' => $admin->email, 'investor' => $investor->email]; Mail::send('emails.helpInvestor', ['question' => $request->input('message'), 'investor' => $investor], function ($m) use($emails) { $m->from('*****@*****.**', 'Cars2Let Investor Support'); $m->cc($emails['investor']); $m->to($emails['admin'])->subject('An Investor needs help'); }); return redirect('/investor'); }
public function postModuleData(ModulesRequest $request) { if (!isset($_SESSION)) { session_start(); } $domain = $_SESSION['domain']; $token = \Crypt::decrypt($_SESSION['userToken']); $courseId = $_SESSION['courseID']; $scope = "module"; $urlPieces = array(); $urlArgs = array(); $urlPieces[] = "https://{$domain}/api/v1/courses/{$courseId}"; if ($request->getModuleId()) { // "we're creating a moduleItem"; $urlPieces[] = "modules/{$request->getModuleId()}/items"; $urlArgs = $this->buildAddModuleItemArgs($request); } else { //we're creating a module obj $urlPieces[] = "modules"; $urlArgs = $this->buildAddModuleArgs($request); } //Attach token $urlArgs[] = "access_token={$token}"; $url = GuzzleHelper::constructUrl($urlPieces, $urlArgs); // echo "The URL is".$url."--"; //return; $response = GuzzleHelper::makeRequest($request, $url, true); //update DB if request was successful if ($response->getStatusCode() === "200") { $newlyCreated = \GuzzleHttp\json_decode($response->getBody()); $newFromDb; if (isset($newlyCreated->module_id)) { //it's a module item $this->processSingleModuleItem($courseId, $newlyCreated); $newFromDb = ModuleItem::with('content')->where(array('module_id' => $newlyCreated->module_id, 'module_item_id' => $newlyCreated->id))->first(); // echo json_encode($modItem); if ($request->getModuleItem()->getTags()) { //add the tags! $tags = $request->getModuleItem()->getTags(); $dbHelper = new DbHelper(); $dbHelper->addTagsToContent($modItem['content_id'], $tags, $courseId); } } else { //it's a module $this->processSingleModule($newlyCreated, $courseId); $newFromDb = Module::firstOrNew(array('module_id' => $newlyCreated->id)); } return $newFromDb; } else { return 0; } }
/** * Send request to SalesManago API. * * @param string $method HTTP Method * @param string $apiMethod API Method * @param array $data Request data * @return array */ protected function doRequest($method, $apiMethod, array $data = []) { $url = $this->config['endpoint'] . $apiMethod; $data = $this->mergeData($this->createAuthData(), $data); $response = $this->getGuzzleClient()->request($method, $url, ['json' => $data]); $responseContent = \GuzzleHttp\json_decode($response->getBody()); if (!property_exists($responseContent, 'success') || !$responseContent->success) { throw new InvalidRequestException($method, $url, $data, $response); } return $responseContent; }
/** * @param string $path * @param array $data * @return mixed * @throws OsticketPhpClientException */ public function request($path, $data) { try { $res = $this->client->request('POST', $this->url . '/' . $path, ['json' => $data, 'headers' => ['User-Agent' => 'OsticketPhpClient/1.0', 'Accept' => 'application/json', 'Expect' => '', 'X-API-Key' => $this->apiKey]]); } catch (\Exception $e) { throw new OsticketPhpClientException("Request error: " . $e->getMessage(), 0, $e); } if ($res->getStatusCode() != 201) { throw new OsticketPhpClientException("Server error: " . $res->getStatusCode()); } try { return \GuzzleHttp\json_decode($res->getBody(), true); } catch (\Exception $e) { throw new OsticketPhpClientException("Error during parsing response", 0, $e); } }
/** * Grab data through webservice */ private function setData() { try { $client = new Client(['base_uri' => $this->apiRecolnatBaseUri]); $response = $client->request('GET', $this->apiRecolnatUserPath . urlencode($this->getUsername())); $this->data = \GuzzleHttp\json_decode($response->getBody()->getContents()); } catch (ClientException $e) { echo \GuzzleHttp\Psr7\str($e->getRequest()); echo \GuzzleHttp\Psr7\str($e->getResponse()); } }
private function getContent($chatId) { $file = $this->getFileName($chatId); return file_exists($file) ? \GuzzleHttp\json_decode(file_get_contents($file)) : []; }
private function _getContent($from, $topicId, $lastUpdate) { $queryParams = ['id' => $topicId, 'since' => time() - 60 * 60 * $lastUpdate]; if ($from == 'curablePosts') { $queryParams['curable'] = 150; $queryParams['curablePage'] = $this->_pager; } elseif ($from == 'curatedPosts') { $queryParams['curated'] = 150; } $raw = $this->get('api/1/topic', ['query' => $queryParams]); $out = \GuzzleHttp\json_decode($raw->getBody()->getContents())->topic; return $out->{$from}; }