public function getAllProjects() { $key = "{$this->cachePrefix}-all-projects"; if ($this->cache && ($projects = $this->cache->fetch($key))) { return $projects; } $first = json_decode($this->client->get('projects.json', ['query' => ['limit' => 100]])->getBody(), true); $projects = $first['projects']; if ($first['total_count'] > 100) { $requests = []; for ($i = 100; $i < $first['total_count']; $i += 100) { $requests[] = $this->client->getAsync('projects.json', ['query' => ['limit' => 100, 'offset' => $i]]); } /** @var Response[] $responses */ $responses = Promise\unwrap($requests); $responseProjects = array_map(function (Response $response) { return json_decode($response->getBody(), true)['projects']; }, $responses); $responseProjects[] = $projects; $projects = call_user_func_array('array_merge', $responseProjects); } usort($projects, function ($projectA, $projectB) { return strcasecmp($projectA['name'], $projectB['name']); }); $this->cache && $this->cache->save($key, $projects); return $projects; }
protected function getClientWithBody($body) { $client = new Client(); $mock = new Mock([new Response(200, [], Stream::factory($body))]); $client->getEmitter()->attach($mock); return $client; }
public function handle() { $this->totalPageCount = count($this->users); $client = new Client(); $requests = function ($total) use($client) { foreach ($this->users as $key => $user) { $uri = 'https://api.github.com/users/' . $user; (yield function () use($client, $uri) { return $client->getAsync($uri); }); } }; $pool = new Pool($client, $requests($this->totalPageCount), ['concurrency' => $this->concurrency, 'fulfilled' => function ($response, $index) { $res = json_decode($response->getBody()->getContents()); $this->info("请求第 {$index} 个请求,用户 " . $this->users[$index] . " 的 Github ID 为:" . $res->id); $this->countedAndCheckEnded(); }, 'rejected' => function ($reason, $index) { $this->error("rejected"); $this->error("rejected reason: " . $reason); $this->countedAndCheckEnded(); }]); // 开始发送请求 $promise = $pool->promise(); $promise->wait(); }
/** * Get the list of videos from YouTube * * @param string $channelId * @throws \Mcfedr\YouTube\LiveStreamsBundle\Exception\MissingChannelIdException * @return array */ public function getStreams($channelId = null) { if (!$channelId) { $channelId = $this->channelId; } if (!$channelId) { throw new MissingChannelIdException("You must specify the channel id"); } if ($this->cache) { $data = $this->cache->fetch($this->getCacheKey($channelId)); if ($data !== false) { return $data; } } $searchResponse = $this->client->get('search', ['query' => ['part' => 'id', 'channelId' => $channelId, 'eventType' => 'live', 'type' => 'video', 'maxResults' => 50]]); $searchData = json_decode($searchResponse->getBody()->getContents(), true); $videosResponse = $this->client->get('videos', ['query' => ['part' => 'id,snippet,liveStreamingDetails', 'id' => implode(',', array_map(function ($video) { return $video['id']['videoId']; }, $searchData['items']))]]); $videosData = json_decode($videosResponse->getBody()->getContents(), true); $streams = array_map(function ($video) { return ['name' => $video['snippet']['title'], 'thumb' => $video['snippet']['thumbnails']['high']['url'], 'videoId' => $video['id']]; }, array_values(array_filter($videosData['items'], function ($video) { return !isset($video['liveStreamingDetails']['actualEndTime']); }))); if ($this->cache && $this->cacheTimeout > 0) { $this->cache->save($this->getCacheKey($channelId), $streams, $this->cacheTimeout); } return $streams; }
/** * @param string $method * @param string $uri * @param array $options * * @return ResponseInterface */ public function request($method, $uri, array $options = []) { $this->lazyLoadGuzzle(); $this->lastRequest = $this->guzzle->createRequest($method, $uri, $options); $response = $this->guzzle->send($this->lastRequest); return $response; }
/** * Execute the command. * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $client = new Client(); $modname = $input->getArgument('modname'); $modversion = $input->getArgument('modversion'); $config = solder_config(); $response = $client->get($config->api); $server = $response->json(); $response = $client->get($config->api . '/mod/' . $modname . '/' . $modversion); $json = $response->json(); if (isset($json['error'])) { throw new \Exception($json['error']); } $rows = array(); foreach ($json as $key => $value) { if ($key == 'versions') { $rows[] = array("<info>{$key}</info>", implode($value, "\n")); } else { $rows[] = array("<info>{$key}</info>", mb_strimwidth($value, 0, 80, "...")); } } $output->writeln('<comment>Server:</comment>'); $output->writeln(" <info>{$server['api']}</info> version {$server['version']}"); $output->writeln(" {$api}"); $output->writeln(''); $output->writeln("<comment>Mod:</comment>"); $table = new Table($output); $table->setRows($rows)->setStyle('compact')->render(); }
/** * Send the notification */ public function send() { $Client = new Client(); $failures = array(); $result = array(); $data = ["registration_ids" => [], "data" => ["title" => $this->data['subject'], "message" => $this->data['body']]]; foreach ($this->data['recipients'] as $user_id => $userdata) { $ThisUser = UserFactory::CreateUser($user_id); $subscriptions = Notifications::getPushSubscriptions($ThisUser); foreach ($subscriptions as $sub) { $data['registration_ids'][] = $sub['registration_id']; } } if (empty($data['registration_ids'])) { return; } try { $response = $Client->post($sub['endpoint'], ["headers" => ["Content-Type" => "application/json", "Authorization" => "key=" . GOOGLE_SERVER_KEY], "json" => $data]); $body = $response->getBody(); $result = json_decode($body, true); $this->removeStaleSubscriptions($result, $data['registration_ids']); $return = array("stat" => true, "failures" => $result); } catch (RequestException $e) { $return = ["stat" => false, "failures" => ["message" => $e->getMessage(), "body" => $e->getRequest()->getBody()]]; } return $return; }
public function run() { if (Yii::$app->getRequest()->isPost) { Yii::$app->getRequest()->parsers = ['application/json' => 'yii\\web\\JsonParser']; $user_class = Satellizer::getComponent()->identityClass; $params = ['code' => Yii::$app->getRequest()->getBodyParam('code'), 'client_id' => Yii::$app->getRequest()->getBodyParam('clientId'), 'redirect_uri' => Yii::$app->getRequest()->getBodyParam('redirectUri'), 'client_secret' => Satellizer::getComponent()->facebook['clientSecret']]; $cliente = new Client(); $accessToken = $cliente->get(Satellizer::getComponent()->facebook['accessTokenUrl'], ['query' => $params])->json(); $profile = $cliente->get(Satellizer::getComponent()->facebook['graphApiUrl'], ['query' => $accessToken])->json(); if (Yii::$app->getRequest()->getHeaders()->get('Authorization')) { $user = $user_class::findOne(['facebook' => $profile['id']]); if ($user) { throw new \yii\web\ConflictHttpException('There is already a Facebook account that belongs to you', 409); } $token = explode(' ', Yii::$app->getRequest()->getHeaders()->getHeaders()->get('Authorization'))[1]; $payload = (array) Satellizer::getComponent()->decodeToken($token); $user = $user_class::find($payload['sub']); $this->facebook = $profile['id']; $user->save(); $user->facebookLink($profile); } else { $user = $user_class::findOne(['facebook' => $profile['id']]); if ($user) { return ['token' => Satellizer::getComponent()->createToken($user)]; } $user = Yii::createObject($user_class); $this->facebook = $profile['id']; $user->save(); $user->facebookLink($profile); } return ['token' => Satellizer::getComponent()->createToken($user)]; } }
/** * Soundcloud login callback. */ public function login(Request $request) { // Check if we have code query. if (!$request->has('code')) { // If not, redirect to homepage. return redirect('/'); } // Parse returned code. $code = $request->get('code'); // Use Guzzle to form request. $client = new Client(); // Get access_token. $response = $client->request('POST', 'https://api.soundcloud.com/oauth2/token', ['form_params' => ['code' => $code, 'client_id' => env('SOUNDCLOUD_CLIENT_ID'), 'client_secret' => env('SOUNDCLOUD_CLIENT_SECRET'), 'redirect_uri' => env('SOUNDCLOUD_CALLBACK_URL'), 'grant_type' => 'authorization_code']]); // Redirect to homepage if response status is not 200. if ($response->getStatusCode() != 200) { return redirect('/'); } // Parse access_token. $response = json_decode($response->getBody()->getContents()); $access_token = $response->access_token; //Init GoogleRepository after authentication when we have access_token. $this->initSoundcloudRepository($request, $access_token); $this->saveSession($request, $access_token); return redirect('/'); }
private function getUrls($url) { $httpClient = new Client(); $content = $httpClient->get(new Uri($url)); $config = json_decode($content->getBody()); $projects = array(); foreach ($config as $configElement) { $urls = array(); $pageKey = $configElement->system->name; $url = $configElement->system->url; $urls[$pageKey]["url"] = $url; $urls[$pageKey]["project"] = $configElement->system->project; $requests = array(); foreach ($configElement->collections as $collection) { $requests[$collection->name] = array(); foreach ($collection->requests as $collectionRequest) { $requests[$collection->name][] = $collectionRequest->pattern; } } $urls[$pageKey]['requests'] = $requests; if (!array_key_exists($configElement->system->project->identifier, $projects)) { $projects[$configElement->system->project->identifier] = array(); } if (!array_key_exists('urls', $projects[$configElement->system->project->identifier])) { $projects[$configElement->system->project->identifier]['urls'] = []; } $projects[$configElement->system->project->identifier]['project'] = $configElement->system->project; $projects[$configElement->system->project->identifier]['urls'] = array_merge($urls, $projects[$configElement->system->project->identifier]['urls']); } return $projects; }
/** * Tests non-existent drug to ensure http response code passed correctly. */ public function testNonExistent() { $client = new Client(); $request = $client->get('http://web/v1/fda/RAINBOWS', ['http_errors' => false]); $response = $request; $this->assertEquals(404, $response->getStatusCode()); }
public function postMo(array $messageArr) { try { $this->msgCounter++; $words = explode(' ', $messageArr['text']); $moParams = array_merge($this->config['mo'], $messageArr, array('message_id' => $this->msgCounter, 'keyword' => $words[0] . '@' . $messageArr['short_id'])); echo "Posting params from MO to client @" . $messageArr['url'] . ': ' . json_encode($moParams) . "\n"; $response = $this->httpClient->post($messageArr['url'], ['body' => $moParams]); if ($response->getStatusCode() != 200) { echo 'received MO reply with status code: ' . $response->getStatusCode() . ', and body' . $response->getBody() . "\n"; return $this->sendError($response->getBody()); } $responseBody = $response->getBody(); echo 'received MO reply:' . $responseBody . "\n"; $this->broadcast('mo_reply', array('message' => $this->parseXMLResponse($responseBody))); } catch (\GuzzleHttp\Exception\RequestException $requestException) { echo 'received MO reply error of class [' . get_class($requestException) . '] and message: ' . $requestException->getMessage() . "\n"; if ($requestException->hasResponse()) { echo "\nbody: " . $requestException->getResponse()->getBody() . "\n"; echo "\ncode: " . $requestException->getResponse()->getStatusCode() . "\n"; $this->sendError($requestException->getMessage(), $this->parseXMLResponse($requestException->getResponse()->getBody())); } $this->sendError($requestException->getMessage()); } catch (\Exception $exc) { echo 'received MO reply error of class [' . get_class($exc) . '] and message: ' . $exc->getMessage() . "\n"; $this->sendError($exc->getMessage()); } }
public function send() { if (!$this->validate()) { throw new SMSMessageException('Could not send message'); } if (empty($this->strId)) { $objUuid = Uuid::uuid4(); $this->strId = $objUuid->toString(); } $arrParams = ['cc' => $this->strUsername, 'ekey' => $this->strPassword, 'message' => $this->strBody, 'title' => $this->strSenderId, 'network' => $this->strNetwork, 'value' => $this->fltValue, 'currency' => $this->strCurrency, 'encoding' => $this->strEncoding, 'number' => $this->strMsisdn, 'id' => $this->strId, 'reply' => $this->intReply]; if ($this->blBinary) { $arrParams['binary'] = (int) $this->blBinary; $arrParams['udh'] = $this->strUdh; } if (!empty($this->shortcode)) { $arrParams['shortcode'] = $this->shortcode; } $this->objLogger->addDebug('Sending the following to txtNation:', $arrParams); $objClient = new Client(['base_uri' => 'http://client.txtnation.com/', 'timeout' => 10.0]); $objResponse = $objClient->get('/gateway.php', [RequestOptions::QUERY => $arrParams, RequestOptions::SYNCHRONOUS => true, RequestOptions::ALLOW_REDIRECTS => true, RequestOptions::HEADERS => ['User-agent' => 'txtNationGatewayLibraryPHP/1.0'], RequestOptions::HTTP_ERRORS => false]); $objResult = new SMSMessageResult($objResponse); $objResult->setCallbackId($this->strId); if (!$objResult->success()) { $this->objLogger->addAlert('Message was not sent. ', ['error' => $objResult->getErrorMessage()]); } return $objResult; }
/** * Send the request and return the response. * * @param Request $request * @param string $url * @return Response */ public function send(Request $request, $url) { $guzzleRequest = $this->convertRequest($request); $guzzleRequest->setUrl($url); $guzzleResponse = $this->client->send($guzzleRequest); return $this->convertResponse($guzzleResponse); }
/** * @param \DonePM\ConsoleClient\Http\Commands\Command $command * * @return mixed|\Psr\Http\Message\ResponseInterface */ public function send(Command $command) { if ($command instanceof NeedsToken) { $command->token($this->token); } return $this->client->send($command->request()); }
private function getStubbedHttpClient($responses = []) { $client = new HttpClient(); $mockSubscriber = new SubscriberMock($responses); $client->getEmitter()->attach($mockSubscriber); return $client; }
/** * @param array $options * @param JobBuilderInterface|null $jobBuilder * @return FileConversionClient */ public static function factory($options = array(), JobBuilderInterface $jobBuilder = null) { // $requiredOptions = array( // 'application_id', // ); // // foreach ($requiredOptions as $optionName) { // if (!isset($options[$optionName]) || $options[$optionName] === '') { // throw new Exception\InvalidArgumentException( // sprintf('Missing required configuration option "%s"', $optionName) // ); // } // } $defaultOptions = array('base_url' => 'https://dws-fileconversion.detailnet.ch/api', 'defaults' => array('connect_timeout' => 10, 'timeout' => 60)); $headers = array('Accept' => 'application/json', 'User-Agent' => 'dfw-fileconversion/' . self::CLIENT_VERSION); if (isset($options[self::OPTION_APP_ID])) { $headers[self::HEADER_APP_ID] = $options[self::OPTION_APP_ID]; } if (isset($options[self::OPTION_APP_KEY])) { $headers[self::HEADER_APP_KEY] = $options[self::OPTION_APP_KEY]; } // These are always applied $overrideOptions = array('defaults' => array('exceptions' => false, 'headers' => $headers)); // Apply options $config = array_replace_recursive($defaultOptions, $options, $overrideOptions); $httpClient = new HttpClient($config); $httpClient->getEmitter()->attach(new Subscriber\Http\ProcessError()); $description = new ServiceDescription(require __DIR__ . '/ServiceDescription/FileConversion.php'); $client = new static($httpClient, $description, $jobBuilder); return $client; }
public static function factory($options = array()) { // $requiredOptions = array(); // // foreach ($requiredOptions as $optionName) { // if (!isset($options[$optionName]) || $options[$optionName] === '') { // throw new Exception\InvalidArgumentException( // sprintf('Missing required configuration option "%s"', $optionName) // ); // } // } // These are applied if not otherwise specified $defaultOptions = array('base_url' => self::getDefaultServiceUrl(), 'defaults' => array('connect_timeout' => 10, 'timeout' => 60)); $headers = array('Accept' => 'application/json', 'User-Agent' => 'denner-client/' . self::CLIENT_VERSION); if (isset($options[self::OPTION_APP_ID])) { $headers[self::HEADER_APP_ID] = $options[self::OPTION_APP_ID]; } if (isset($options[self::OPTION_APP_KEY])) { $headers[self::HEADER_APP_KEY] = $options[self::OPTION_APP_KEY]; } // These are always applied $overrideOptions = array('defaults' => array('exceptions' => false, 'headers' => $headers)); // Apply options $config = array_replace_recursive($defaultOptions, $options, $overrideOptions); $httpClient = new HttpClient($config); $httpClient->getEmitter()->attach(new Subscriber\Http\ProcessError()); $serviceDescriptionFile = __DIR__ . sprintf('/ServiceDescription/%s.php', self::getServiceDescriptionName()); if (!file_exists($serviceDescriptionFile)) { throw new Exception\RuntimeException(sprintf('Service description does not exist at "%s"', $serviceDescriptionFile)); } $description = new ServiceDescription(require $serviceDescriptionFile); $client = new static($httpClient, $description); return $client; }
/** * Execute the console command. * * @return mixed */ public function handle() { $client = new Client(); $end_point = 'http://api.serviceu.com/rest/events/occurrences?orgKey=b96cd642-acbb-4eb7-95a2-f18c0f01d5b1&format=json'; $response = $client->get($end_point); $data = json_decode($response->getBody(true)); $active_records = []; CalendarEvent::unguard(); foreach ($data as $event) { array_push($active_records, $event->OccurrenceId); $record = CalendarEvent::withPast()->where('id', '=', $event->OccurrenceId)->first() ?: new CalendarEvent(); $record->{'id'} = $event->OccurrenceId; $record->{'event_number'} = $event->EventId; $record->{'title'} = $event->Name; $record->{'starts_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceStartTime); $record->{'ends_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceEndTime); $record->{'location'} = $event->LocationName; $record->{'address'} = $event->LocationAddress; $record->{'address2'} = $event->LocationAddress2; $record->{'city'} = $event->LocationCity; $record->{'state'} = $event->LocationState; $record->{'zip'} = $event->LocationZip; $record->{'description'} = $event->Description; $record->{'contact'} = $event->ContactName; $record->{'contact_email'} = $event->ContactEmail; $record->{'contact_phone'} = $event->ContactPhone; $record->{'department'} = $event->DepartmentName; $record->save(); } CalendarEvent::reguard(); // Remove non-existing events CalendarEvent::withPast()->whereNotIn('id', $active_records)->delete(); // Purge old events CalendarEvent::where('ends_at', '<', Carbon::now()->subMonth(2))->delete(); }
protected function download() { $this->output->writeln(sprintf("\n Downloading %s...\n", $this->projectName)); $distill = new Distill(); $componentFile = $distill->getChooser()->setStrategy(new MinimumSize())->addFile($this->remoteFileUrl)->getPreferredFile(); $downloadCallback = function ($expected, $total, $client, $request, $response) { // Don't initialize the progress bar for redirects as the size is much smaller if ($response->getStatusCode() >= 300) { return; } printf(" Download: %d %% \r", 100 * ($total / $expected)); }; $client = new Client(); $client->getEmitter()->attach(new Progress(null, $downloadCallback)); // store the file in a temporary hidden directory with a random name $this->downloadedFilePath = getcwd() . DIRECTORY_SEPARATOR . '.' . uniqid(time()) . DIRECTORY_SEPARATOR . $this->projectName . '.' . ltrim(strstr($componentFile, '.'), '.'); //pathinfo($symfonyArchiveFile, PATHINFO_EXTENSION); try { $response = $client->get($componentFile); } catch (ClientException $e) { throw new \RuntimeException(sprintf("There was an error downloading %s from server:\n%s", $this->getDownloadedFileName(), $e->getMessage())); } $this->fs->dumpFile($this->downloadedFilePath, $response->getBody()); $this->output->writeln("\n"); return $this; }
/** * Guzzle 4 Request method implementation * * @param string $httpMethod * @param string $path * @param array $params * @param null $version * @param bool $isAuthorization * * @return Response|mixed * @throws ClientException * @throws AuthorizeException * @throws ServerException * @throws Error */ public function request($httpMethod = 'GET', $path = '', $params = array(), $version = null, $isAuthorization = false) { $guzzleClient = new GuzzleClient(); switch ($httpMethod) { case 'GET': $request = $guzzleClient->createRequest($httpMethod, $path, array('query' => $params)); break; default: $request = $guzzleClient->createRequest($httpMethod, $path, array('body' => $params)); } try { $res = $guzzleClient->send($request); } catch (GuzzleException\ClientException $e) { //catch error 404 $error_message = $e->getResponse(); if ($isAuthorization) { throw new AuthorizeException($error_message, $e->getCode(), $e->getPrevious()); } else { throw new ClientException($error_message, $e->getCode(), $e->getPrevious()); } } catch (GuzzleException\ServerException $e) { throw new ServerException($e, $e->getCode(), $e->getPrevious()); } catch (GuzzleException\BadResponseException $e) { throw new Error($e->getResponse(), $e->getCode(), $e->getPrevious()); } $response = new Response($res->json(), $res->getCode()); return $response; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->has('token')) { return response()->json(config('status.messages.404'), 404); } $token = $request->input('token'); //Check for API Authentication $authUrl = config('app.auth'); $client = new Client(['base_url' => $authUrl['base_url']]); //ToDo : Header or Auth Type need to change later according to Main App Authentication $headers = ['X-API-KEY' => env('AUTH_APP_KEY'), 'X-API-SECRET' => env('AUTH_APP_SECRET')]; try { $response = $client->get($authUrl['uri'] . '/' . $token, ['headers' => $headers]); } catch (ClientException $e) { $response = $e->getResponse(); } switch ($response->getStatusCode()) { case 401: return response()->json(config('status.messages.401'), 401); break; case 200: $request->session()->put('request_user', $response->json()); return $next($request); break; } return response()->json(config('status.messages.401'), 401); }
/** * Runs http calls. * * @param string $method * @param string $url * @param array $content * @param boolean $auth * @return object */ public static function runRequest($method, $url, $content, $auth) { $guzzle = new GuzzleClient(['http_errors' => false, 'allow_redirects' => true]); $url = self::$base_url . "/{$url}"; $headers = ['User-Agent' => self::getUserAgent(), 'Content-Type' => 'application/json']; if (!$auth) { $headers['authorization'] = DISCORD_TOKEN; } $done = false; $finalRes = null; while (!$done) { $content = is_null($content) ? null : json_encode($content); $request = new Request($method, $url, $headers, $content); $response = $guzzle->send($request); // Rate limiting if ($response->getStatusCode() == 429) { $tts = $response->getHeader('Retry-After') * 1000; usleep($tts); continue; } // Not good! if ($response->getStatusCode() < 200 || $response->getStatusCode() > 226) { self::handleError($response->getStatusCode(), $response->getReasonPhrase()); continue; } $done = true; $finalRes = $response; } return json_decode($finalRes->getBody()); }
/** * Make API Call * @param string $path API Path * @param array $query Additional query parameters (optional) * @return GuzzleHttp\Response */ public function fetch($path, array $query = []) { if (!$this->api instanceof Http) { $this->setupHttpClient(); } return $this->api->get($path, ['query' => $query])->json(); }
/** * Method to get an array of rock artists from last.fm */ public static function get_lastfm_rock_stations() { $api_key = config('app.api_key_lastfm'); $client = new \GuzzleHttp\Client(); $res = $client->get('http://ws.audioscrobbler.com/2.0', ['query' => ['method' => 'tag.getTopArtists', 'tag' => 'rock', 'format' => 'json', 'limit' => 5, 'api_key' => $api_key]]); if ($res->getStatusCode() != 200) { return false; } $stations = json_decode((string) $res->getBody(), true); if ($stations == NULL) { return false; } $rock_stations = array(); if ($stations != NULL && isset($stations['topartists']['artist'])) { foreach ($stations['topartists']['artist'] as $rock_station) { $obj = new \stdClass(); $obj->id = md5($rock_station['mbid']); if (isset($rock_station['name'])) { $obj->name = $rock_station['name']; } if (isset($rock_station['image'][2]['#text'])) { $obj->thumb_url = $rock_station['image'][2]['#text']; } if (isset($rock_station['url'])) { $obj->website = $rock_station['url']; } $rock_stations[md5($rock_station['mbid'])] = $obj; } } return $rock_stations; }
private function proxy($grantType, array $data = []) { try { $config = app()->make('config'); $data = array_merge(['client_id' => $config->get('secrets.client_id'), 'client_secret' => $config->get('secrets.client_secret'), 'grant_type' => $grantType], $data); $client = new Client(); $guzzleResponse = $client->post(sprintf('%s/oauth/access-token', $config->get('app.url')), ['form_params' => $data]); } catch (\GuzzleHttp\Exception\BadResponseException $e) { $guzzleResponse = $e->getResponse(); } $response = json_decode($guzzleResponse->getBody()); if (property_exists($response, "access_token")) { $cookie = app()->make('cookie'); $crypt = app()->make('encrypter'); $encryptedToken = $crypt->encrypt($response->refresh_token); // Set the refresh token as an encrypted HttpOnly cookie $cookie->queue('refreshToken', $crypt->encrypt($encryptedToken), 604800, null, null, false, true); $response = ['accessToken' => $response->access_token, 'accessTokenExpiration' => $response->expires_in]; } $response = response()->json($response); $response->setStatusCode($guzzleResponse->getStatusCode()); $headers = $guzzleResponse->getHeaders(); foreach ($headers as $headerType => $headerValue) { $response->header($headerType, $headerValue); } return $response; }
/** * @return MailTesterMessage */ public function getLastEmail() { $inboxId = $this->config['inbox_id']; $messageId = $this->getAllEmails()[0]['id']; $email = $this->mailtrap->get("/api/v1/inboxes/{$inboxId}/messages/{$messageId}")->json(); return $this->populateMessage($messageId, $email); }
public function registerWebPayModule($payment = 'capture') { $I = $this; $I->login(); $I->amOnPage('/admin/load_module_config.php?module_id=' . MDL_WEBPAY_ID); $I->fillField('secret_key', WEBPAY_SECRET_KEY); $I->fillField('publishable_key', WEBPAY_PUBLISHABLE_KEY); $I->selectOption('input[name=payment]', $payment); $I->click('この内容で登録する'); $I->amOnPage('/admin/ownersstore/'); $uri = 'http://localhost:9999/admin/ownersstore/'; $transactionId = $I->grabAttributeFrom('input[name=transactionid]', 'value'); $sessionId = $I->grabCookie('ECSESSID'); // posting file and handling confirm window are impossible for ghostdriver $client = new Client(); $I->expectTo('install plugin'); $client->post($uri, ['body' => ['transactionid' => $transactionId, 'mode' => 'install', 'plugin_file' => fopen('WebPayExt.tar.gz', 'r')], 'cookies' => ['ECSESSID' => $sessionId]]); $client->post($uri, ['body' => ['transactionid' => $transactionId, 'mode' => 'enable', 'plugin_id' => 1, 'enable' => 1], 'cookies' => ['ECSESSID' => $sessionId]]); $I->amOnPage('/admin/ownersstore/'); $I->see('WebPay決済モジュール拡張プラグイン'); $I->seeCheckboxIsChecked('input#plugin_enable'); $I->seeInDatabase('dtb_payment', array('payment_id' => 5, 'memo03' => MDL_WEBPAY_CODE)); $I->haveInDatabase('dtb_payment_options', array('deliv_id' => 1, 'payment_id' => 5, 'rank' => 5)); $I->haveInDatabase('dtb_payment_options', array('deliv_id' => 2, 'payment_id' => 5, 'rank' => 2)); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $outputFile = $input->getArgument('output'); $outputHandle = fopen($outputFile, 'w'); $client = new Client([]); $headers = ['Accept' => 'application/json', 'Accept-Encoding' => 'gzip,deflate', 'User-Agent' => 'crossref-dois/0.1 (+https://github.com/hubgit/crossref-dois/)']; // https://api.crossref.org/works?filter=type:journal-article&cursor=* $filters = ['type' => 'journal-article']; $filter = implode(',', array_map(function ($key) use($filters) { return $key . ':' . $filters[$key]; }, array_keys($filters))); $params = ['filter' => $filter, 'cursor' => '*', 'rows' => 1000]; $progress = new ProgressBar($output); $progressStarted = false; do { $response = $client->get('https://api.crossref.org/works', ['connect_timeout' => 10, 'timeout' => 120, 'query' => $params, 'headers' => $headers]); $data = json_decode($response->getBody(), true); if (!$progressStarted) { $progress->start($data['message']['total-results']); $progressStarted = true; } $items = $this->parseResponse($data); foreach ($items as $item) { fwrite($outputHandle, json_encode($item) . "\n"); } $params['cursor'] = $data['message']['next-cursor']; $progress->advance(count($items)); } while ($params['cursor']); $progress->finish(); }
public function consulta($cnpj, $cpf, $codigo, $captcha, $stringCookie, $viewState, $eventValidation) { $jar = new \GuzzleHttp\Cookie\CookieJar(); $requisicao = new Client(['cookies' => true]); $param = ['form_params' => ['__VIEWSTATE' => $viewState, '__EVENTVALIDATION' => $eventValidation, 'ctl00$txtBusca' => '', 'ctl00$ContentPlaceHolder$txtCNPJ' => $cnpj, 'ctl00$ContentPlaceHolder$txtCPFResponsavel' => $cpf, 'ctl00$ContentPlaceHolder$txtCodigoAcesso' => $codigo, 'txtTexto_captcha' => $captcha, 'hdn_client_id' => '00000000000000000000000000000000', 'ctl00$ContentPlaceHolder$btContinuar' => 'Continuar'], 'headers' => ['Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding' => 'gzip, deflate', 'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4', 'Cache-Control' => 'max-age=0', 'Connection' => 'keep-alive', 'Content-type' => 'application/x-www-form-urlencoded', 'Cookie' => $stringCookie, 'Host' => 'www8.receita.fazenda.gov.br', 'Origin' => 'http://www8.receita.fazenda.gov.br', 'Referer' => 'http://www8.receita.fazenda.gov.br/SimplesNacional/controleAcesso/Autentica.aspx?id=6', 'Upgrade-Insecure-Requests' => '1', 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'], 'timeout' => 20, 'connect_timeout' => 20]; $resposta = $requisicao->post('http://www8.receita.fazenda.gov.br/SimplesNacional/controleAcesso/Autentica.aspx?id=6', $param); require_once 'simple_html_dom.php'; $html = str_get_html($resposta->getBody()->getContents()); // echo $resposta->getBody()->getContents(); $erros = $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblErroCaptcha'); if (is_object($erros)) { $mensagemErro = 'Ocorreu algum erro, tente novamente mais tarde'; switch (trim($erros->plaintext)) { case 'Caracteres anti-robô inválidos. Tente novamente.': $mensagemErro = 'Erro ao consultar. Verifique se digitou corretamente o captcha.'; break; case 'O CNPJ informado deve conter 14 dígitos.': $mensagemErro = 'Erro ao consultar. CNPJ deve conter 14 dígitos.'; break; case 'O CNPJ digitado é inválido.': $mensagemErro = 'Erro ao consultar. CNPJ inválido.'; break; } throw new \Exception($mensagemErro, 99); } return str_replace('./', 'http://www8.receita.fazenda.gov.br/SimplesNacional/Aplicacoes/ATSPO/pgdasd.app/', $resposta->getBody()); return ['cnpj' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblCNPJ')->plaintext, 'nome_empresarial' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblNomeEmpresa')->plaintext, 'situacao_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoSimples')->plaintext, 'situacao_simei' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSituacaoMei')->plaintext, 'opcoes_pelo_simples_nacional_periodos_anteriores' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblPeriodoAnterior > b > font')->plaintext, 'opcoes_pelo_simei_periodos_anteriores' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblSIMEIPeriodosAnteriores > b > font')->plaintext, 'agendamentos_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblAgendamentosOpcaoSinac > b > font')->plaintext, 'eventos_futuros_simples_nacional' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturos > b > font')->plaintext, 'eventos_futuros_simei' => $html->getElementById('ctl00_ContentPlaceHolderConteudo_lblEventosFuturosSimei > b > font')->plaintext]; }