/** * 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; }
/** * 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()); } }
/** * */ public function call($verb, $host, $port, $uri, $headers = null, $query = null, $body = null, $statusCode = null) { // Fix headers, query and body $headers = \z\conf($headers); $query = \z\conf($query); if (is_null($body) === true) { $body = ''; } // Body must be a string if (is_string($body) === false) { \z\e(EXCEPTION_HTTP_BODY_NOT_VALID, ['body' => json_encode($body, true), 'type' => gettype($body)]); } // Build the HTTP client $client = new \GuzzleHttp\Client(['base_url' => $host]); // Build the request $request = $client->createRequest($verb, $uri, ['exceptions' => false]); // Setup the request $request->setPort($port); $request->setHeaders($headers); $request->setQuery($query); $request->setBody(\GuzzleHttp\Stream\Stream::factory($body)); // Log \z\logger()->debug($request); // Send the request $response = $client->send($request); // Log \z\logger()->debug($response); // Did it succeed? if (is_null($statusCode) === false && (int) $statusCode !== (int) $response->getStatusCode()) { \z\e(EXCEPTION_HTTP_STATUS_CODE_NOT_VALID, ['expected' => $statusCode, 'actual' => $response->getStatusCode(), 'request' => $request->__toString(), 'response' => $response->__toString()]); } // Build the result $result = $response->getBody(); return $result; }
public function fire() { // get last update $latestLog = DB::table('steam_log')->orderBy('updated', 'DESC')->first(); if (count($latestLog) == 0) { // create new record for player DB::table('steam_log')->insert(['steam_id' => env('STEAM_ID'), 'in_game' => 0, 'updated' => time()]); $currentStatus = 0; } else { $currentStatus = $latestLog->in_game; } $client = new \GuzzleHttp\Client(); $request = $client->createRequest('GET', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . env('STEAM_KEY') . '&steamids=' . env('STEAM_ID')); $response = $client->send($request); $responseData = json_decode($response->getBody()->getContents()); $player = $responseData->response->players[0]; //dd(isset($player->gameid)); if (isset($player->gameid)) { // in game $status = 1; $game_id = $player->gameid; $game_name = $player->gameextrainfo; } else { // out of game $status = 0; $game_id = null; $game_name = null; } // save latest status DB::table('steam_log')->where('steam_id', env('STEAM_ID'))->update(['in_game' => $status, 'game_id' => $game_id, 'game_name' => $game_name, 'updated' => time()]); // check to see if notification needs to be sent if ($currentStatus != $status) { if ($status == 1) { $pushMessage = 'In Game: ' . $game_name; } else { $pushMessage = 'No longer playing game'; } if (env('STEAM_NOTIFY_METHOD') == 'pushover') { // send to Pushover curl_setopt_array($ch = curl_init(), array(CURLOPT_URL => "https://api.pushover.net/1/messages.json", CURLOPT_POSTFIELDS => array("token" => env('PUSHOVER_API_KEY'), "user" => env('PUSHOVER_USER_KEY'), "message" => $pushMessage), CURLOPT_SAFE_UPLOAD => true)); curl_exec($ch); curl_close($ch); } else { // send to Slack $settings = ['username' => env('STEAM_SLACK_USERNAME'), 'channel' => '#' . env('STEAM_SLACK_CHANNEL'), 'link_names' => true, 'icon' => ':ghost:']; // send to slack $client = new \Maknz\Slack\Client(env('STEAM_SLACK_WEBHOOK'), $settings); $client->send($pushMessage); } } $this->info('Complete'); }
/** * @todo A monster method to refactor!!! * * @param SpecRest $restSpec * @param string $useCaseFilter * @return ValidationReport */ public function validate(Spec\Rest $restSpec, $apiFilter, $useCaseFilter = null) { $validationReport = new ValidationReport(); $apiSpecs = $restSpec->getApiSpecs(); foreach ($apiSpecs as $apiSpec) { if ($apiFilter && $apiSpec->getName() !== $apiFilter) { $this->log[] = sprintf("API %s omitted due to filter '%'", $apiSpec->getName(), $apiFilter); continue; } $this->log[] = sprintf("Testing %s API at %s ", $apiSpec->getName(), $apiSpec->getBaseUrl()); $apiValidationReport = new ApiValidationReport($apiSpec); $validationReport->addApiReport($apiValidationReport); $client = new \GuzzleHttp\Client(['base_url' => $apiSpec->getBaseUrl()]); $responseValidator = new Response(); foreach ($apiSpec->getUrlSpecs() as $urlSpec) { $this->log[] = sprintf("\tTesting URL %s", $urlSpec->getUrl()); $urlReport = new UrlValidationReport($urlSpec); $apiValidationReport->addUrlReport($urlReport); $useCases = $urlSpec->getUseCases(); foreach ($useCases as $urlUseCaseSpec) { if ($useCaseFilter && strpos(strtolower($urlUseCaseSpec->getDescription()), strtolower($useCaseFilter)) === false) { continue; } $useCaseValidationReport = new UseCaseValidationReport($urlUseCaseSpec, $urlUseCaseSpec->getExpectedResponseSpec()); $urlReport->addUseCaseReport($useCaseValidationReport); if ($beforeCallback = $urlUseCaseSpec->getBeforeCallback()) { call_user_func($beforeCallback, $urlUseCaseSpec); } $request = $urlUseCaseSpec->getRequest(); $res = $client->send($request); $responseValidator->validate($res, $urlUseCaseSpec->getExpectedResponseSpec(), $useCaseValidationReport); $useCaseValidationReport->setResponse($res); if ($responseValidator->isValid()) { $validationReport->incrementPassedCount(); } else { $validationReport->incrementFailedCount(); } $responseValidator->reset(); if ($doneCallback = $urlUseCaseSpec->getDoneCallback()) { call_user_func($doneCallback, $res); } if ($this->onProgress) { call_user_func($this->onProgress, $validationReport->getTotalUseCases()); } } } } return $validationReport; }
public function getEvents() { $client = new \GuzzleHttp\Client(); $request = $client->createRequest('GET', 'https://www.eventbriteapi.com/v3/users/me/owned_events/'); $request->setHeader('Authorization', 'Bearer ' . $this->oauth); $response = $client->send($request); $body = json_decode($response->getBody()); if (isset($body->events) && is_array($body->events)) { $events = array_map(function ($event) { return new \PhpDorset\Eventbrite\EventDecorator($event); }, $body->events); return $events; } return null; }
/** * @param string $method * @param string $url * @param string|null $query * @return string * @throws EntityValidationException */ private function request($method, $url, $query = null) { try { $client = new \GuzzleHttp\Client(['defaults' => ['timeout' => 60, 'allow_redirects' => false, 'verify' => true]]); $options = ['auth' => [$this->user, $this->password, "Digest"]]; if (!empty($query)) { $options['query'] = $query; } $request = $client->createRequest($method, $url, $options); $response = $client->send($request); if ($response->getStatusCode() == 200) { return $response->getBody()->getContents(); } throw new Exception(); } catch (Exception $ex) { SS_Log::log($ex, SS_Log::ERR); throw new EntityValidationException([['message' => 'server error']]); } }
private function attemptGuzzle($method, $endpoint, $headers, $body) { if ($this->use_guzzle && class_exists('\\GuzzleHttp\\Exception\\BadResponseException') && class_exists('\\GuzzleHttp\\Exception\\ClientException') && class_exists('\\GuzzleHttp\\Exception\\ConnectException') && class_exists('\\GuzzleHttp\\Exception\\RequestException') && class_exists('\\GuzzleHttp\\Exception\\ServerException') && class_exists('\\GuzzleHttp\\Exception\\TooManyRedirectsException') && class_exists('\\GuzzleHttp\\Client') && class_exists('\\GuzzleHttp\\Psr7\\Request')) { $request = new \GuzzleHttp\Psr7\Request(strtoupper($method), $endpoint, $headers, $body); $client = new \GuzzleHttp\Client(); try { $response = $client->send($request); } catch (\Exception $e) { if (($e instanceof \GuzzleHttp\Exception\BadResponseException || $e instanceof \GuzzleHttp\Exception\ClientException || $e instanceof \GuzzleHttp\Exception\ConnectException || $e instanceof \GuzzleHttp\Exception\RequestException || $e instanceof \GuzzleHttp\Exception\ServerException || $e instanceof \GuzzleHttp\Exception\TooManyRedirectsException) && $e->hasResponse()) { $response = $e->getResponse(); } else { throw $e; } } return $response; } else { return false; } }
/** * performing gitlab api request * * @param $uri API uri * @param $body body data * * @return type json response */ public function send($uri, $body, $method = 'POST') { $client = new \GuzzleHttp\Client(['base_uri' => $this->gitHost, 'timeout' => 10.0, 'verify' => false]); $postData['headers'] = ['PRIVATE-TOKEN' => $this->gitToken]; $postData['json'] = $body; if ($this->debug) { $postData['debug'] = fopen(base_path() . '/' . 'debug.txt', 'w'); } $request = new \GuzzleHttp\Psr7\Request($method, $this->gitHost . '/api/v3/' . $uri); try { $response = $client->send($request, $postData); } catch (GuzzleHttp\Exception\ClientException $e) { dump($response); echo $e->getRequest(); if ($e->hasResponse()) { echo $e->getResponse(); } } if ($response->getStatusCode() != 200 && $response->getStatusCode() != 201) { throw new JiraIntegrationException("Http request failed. status code : " . $response->getStatusCode() . " reason:" . $response->getReasonPhrase()); } return json_decode($response->getBody()); }
/** * @dataProvider recordingProvider */ public function testRecording($name, $requests, $responses) { $this->setName($name); $this->assertGreaterThanOrEqual(sizeof($requests), sizeof($responses)); \GuzzleHttp\Tests\Server::enqueue($responses); $cassette = __DIR__ . '/fixtures/temp/' . str_replace([" with data set #", "test", " "], ["-", "", "-"], $this->getName()) . '.json'; $responses = []; $vcr = \Dshafik\GuzzleHttp\VcrHandler::turnOn($cassette); $this->assertInstanceOf(\GuzzleHttp\HandlerStack::class, $vcr); $client = new \GuzzleHttp\Client(['handler' => $vcr]); foreach ($requests as $key => $request) { try { $response = $client->send($request); } catch (\GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse(); } $this->assertEmpty($response->getHeader('X-VCR-Recording')); $responses[$key] = $response; } $vcr = \Dshafik\GuzzleHttp\VcrHandler::turnOn($cassette); $this->assertInstanceOf(\GuzzleHttp\HandlerStack::class, $vcr); $client = new \GuzzleHttp\Client(['handler' => $vcr]); foreach ($requests as $key => $request) { try { $recording = $client->send($request); } catch (\GuzzleHttp\Exception\ClientException $e) { $recording = $e->getResponse(); } $this->assertTrue(ctype_digit($recording->getHeader('X-VCR-Recording')[0])); $this->assertEquals($responses[$key]->getStatusCode(), $recording->getStatusCode()); foreach ($responses[$key]->getHeaders() as $header => $value) { $this->assertEquals($value, $recording->getHeader($header)); } $this->assertEquals((string) $responses[$key]->getBody(), (string) $recording->getBody()); } }
/** * @Then As :user edit the last created comment and set text to :text it should return :statusCode */ public function asEditTheLastCreatedCommentAndSetTextToItShouldReturn($user, $text, $statusCode) { $client = new \GuzzleHttp\Client(); $options = []; $options['auth'] = [$user, '123456']; $options['body'] = '<?xml version="1.0"?> <d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"> <d:set> <d:prop> <oc:message>' . $text . '</oc:message> </d:prop> </d:set> </d:propertyupdate>'; try { $res = $client->send($client->createRequest('PROPPATCH', $this->baseUrl . '/remote.php/dav/comments/files/' . $this->fileId . '/' . $this->commentId, $options)); } catch (\GuzzleHttp\Exception\ClientException $e) { $res = $e->getResponse(); } if ($res->getStatusCode() !== (int) $statusCode) { throw new \Exception("Response status code was not {$statusCode} (" . $res->getStatusCode() . ")"); } }
<?php include 'vendor/autoload.php'; include 'wp-load.php'; $args = array('sort_order' => 'asc', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'child_of' => 0, 'parent' => -1, 'exclude_tree' => '', 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish'); $pages = get_pages($args); // Create a client with a base URI $client = new GuzzleHttp\Client(); foreach ($pages as $page) { $data = []; $data['title'] = $page->post_title; $data['content'] = $page->post_content; $data['urls'][0]['url'] = $page->post_name . '/'; $request = new GuzzleHttp\Psr7\Request('PUT', 'http://127.0.0.1:8000/api/v1/content/' . $page->ID, [], json_encode($data)); $client->send($request); } echo "I'm so lucky ;)";
/** * Upload event image - this one's a bit special as it's a form post * * Uses Guzzle * * @param string $imagesUri event's images_uri * @param string $fileName the (temp) file to send * @return boolean */ public function uploadIcon($imagesUri, $fileName) { try { $client = new \GuzzleHttp\Client(["timeout" => 10]); $headers = []; $headers["Accept"] = "application/json"; $headers["Authorization"] = "OAuth {$this->accessToken}"; // Forwarded header - see RFC 7239 (http://tools.ietf.org/html/rfc7239) $ip = $_SERVER['REMOTE_ADDR']; $agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown'; $headers["Forwarded"] = "for={$ip};user-agent=\"{$agent}\""; $options = []; $options['headers'] = $headers; if ($this->proxy) { $options['proxy'] = $this->proxy; } // now add the file itself $options['multipart'] = [['name' => 'image', 'contents' => fopen($fileName, 'r')]]; $request = new \GuzzleHttp\Psr7\Request('POST', $imagesUri); $response = $client->send($request, $options); } catch (\GuzzleHttp\Exception\RequestException $e) { $body = $e->getResponse()->getBody(); error_log($e->getMessage()); error_log(json_decode($body)[0]); throw new \Exception(json_decode($body)[0]); } if ($response->getStatusCode() == 201) { return true; } throw new \Exception((string) $response->getBody()); }
/** * Execute a request to the server and return the response, while retrying * based on any Retry-After headers that are sent back. * * @param GuzzleHttp\Client $guzzle The Guzzle instance to use. * @param GuzzleHttp\Message\Request $request The request to send, and * possibly retry. * @param int $timeout The maximum number of seconds to retry for. * * @return GuzzleHttp\Message\Response The Guzzle response object. * @throws GuzzleHttp\Exception\RequestException */ private function execute($guzzle, $request, $timeout) { $response = $guzzle->send($request); $headers = $response->getHeaders(); if (!empty($headers['Retry-After'])) { $seconds = round(time() - $this->timestampRequested); if ($timeout > 0 && $seconds >= $timeout) { $message = 'The request timed out after retrying for ' . $seconds . ' seconds.'; static::error(static::REQUEST_TIMEOUT_ERROR, $message, $request, $response); } sleep($headers['Retry-After'][0]); return $this->execute($guzzle, $request, $timeout); } return $response; }
/** * The base request method for all API access. * * @param string $method The request VERB to use (GET, POST, PUT, DELETE) * @param string $path The API path. * @param array $body The content to be used (either as the query, or the json post/put body) * @return object */ protected function processRestRequest($method = NULL, $path = NULL, $body = NULL) { $client = new \GuzzleHttp\Client(array('defaults' => array('exceptions' => false, 'timeout' => $this->timeout))); $url = PostmarkClientBase::$BASE_URL . $path; $options = array(); if ($body != NULL) { $cleanParams = array(); foreach ($body as $key => $value) { if ($value !== NULL) { $cleanParams[$key] = $value; } } switch ($method) { case 'GET': case 'HEAD': case 'DELETE': case 'OPTIONS': $options['query'] = $cleanParams; break; case 'PUT': case 'POST': case 'PATCH': $options['json'] = $cleanParams; break; } } if (PostmarkClientBase::$CERTIFICATE_PATH != NULL) { $options['verify'] = PostmarkClientBase::$CERTIFICATE_PATH; } $request = $client->createRequest($method, $url, $options); $v = $this->version; $o = $this->os; //TODO: include version info in the request. $request->setHeader('User-Agent', "Postmark-PHP (PHP Version:{$v}, OS:{$o})"); $request->setHeader('Accept', 'application/json'); $request->setHeader('Content-Type', 'application/json'); $request->setHeader($this->authorization_header, $this->authorization_token); $response = $client->send($request); $result = NULL; switch ($response->getStatusCode()) { case 200: $result = $response->json(); break; case 401: $ex = new PostmarkException(); $ex->message = 'Unauthorized: Missing or incorrect API token in header. ' . 'Please verify that you used the correct token when you constructed your client.'; $ex->httpStatusCode = 401; throw $ex; break; case 422: $ex = new PostmarkException(); $body = $response->json(); $ex->httpStatusCode = 422; $ex->postmarkApiErrorCode = $body['ErrorCode']; $ex->message = $body['Message']; throw $ex; break; case 500: $ex = new PostmarkException(); $ex->httpStatusCode = 500; $ex->message = 'Internal Server Error: This is an issue with Postmark’s servers processing your request. ' . 'In most cases the message is lost during the process, ' . 'and Postmark is notified so that we can investigate the issue.'; throw $ex; break; } return $result; }
<?php require __DIR__ . '/../vendor/autoload.php'; $httpClient = new GuzzleHttp\Client(); $request = $httpClient->createRequest('GET', 'http://httpbin.org/get'); $response = $httpClient->send($request); echo "REQUEST:\n\n{$request}\n"; echo "RESPONSE:\n\n{$response}\n";
<?php require "../vendor/autoload.php"; // pull the access creds from another file require "github_access_token.php"; $url = "https://api.github.com/gists/bf6c595b6686d38f44ab/star"; $client = new GuzzleHttp\Client(); $request = $client->createRequest('PUT', $url); $request->setHeader("Authorization", "token " . $gh_key); $request->setHeader("Content-Length", "0"); $response = $client->send($request); echo $response->getStatusCode();
<?php /* Template Name: Hub Pos Test */ $options = get_option(\Tls\TlsHubSubscriber\TlsHubSubscriberWP::get_option_name()); $guzzleClient = new \GuzzleHttp\Client(); // Start empty $hubUrl variable $hubUrl = ''; $callbackUrl = site_url() . '/pushfeed/' . $options['subscription_id']; // Check if the Hub URL finishes with a / or not to be able to create the correct subscribe URL if (preg_match("/\\/\$/", $options['hub_url'])) { $hubUrl = $options['hub_url']; } else { $hubUrl = $options['hub_url']; } // Json Data needed to send to the Hub for Subscription $subscribeJson = json_encode(array("callbackUrl" => esc_url($callbackUrl), "topicId" => esc_url($options['topic_url'])), JSON_UNESCAPED_SLASHES); $subscribeRequest = $guzzleClient->createRequest('POST', $hubUrl); $subscribeRequest->setHeader('Content-Type', 'application/json'); $subscribeRequest->setBody(\GuzzleHttp\Stream\Stream::factory($subscribeJson)); $subscribeResponse = $guzzleClient->send($subscribeRequest);