/**
  * Setup Guzzle client
  *
  * @return Client
  */
 public function getGuzzleClient()
 {
     $client = new Client(['base_url' => $this->url]);
     $client->setDefaultOption('headers', ['Accept' => 'application/vnd.' . $this->name . '.' . $this->version . '+json', 'Authorization' => $this->auth->getGuzzleOptions('token')]);
     $client->setDefaultOption('auth', $this->auth->getGuzzleOptions('auth'));
     $client->setDefaultOption('exceptions', $this->auth->getGuzzleOptions('exceptions'));
     return $client;
 }
Example #2
0
 /**
  * @param string $token
  * @param Client|ClientInterface $client
  * @throws \Exception
  */
 public function __construct($token, ClientInterface $client = null)
 {
     if (is_null($client)) {
         $client = new \GuzzleHttp\Client();
     }
     $this->client = $client;
     $this->client->setDefaultOption('headers', ['loaderio-auth' => $token]);
 }
Example #3
0
 function __construct(array $config)
 {
     $this->config = $config;
     $this->requiredFields = ['api_token', 'inbox_id'];
     $this->validateConfig();
     $this->mailtrap = new Client(['base_url' => $this->base_url]);
     $this->mailtrap->setDefaultOption('query', ['api_token' => $this->config['api_token']]);
 }
Example #4
0
 /**
  * @return Client|null
  */
 protected static function getClient()
 {
     if (self::$client === NULL) {
         self::$client = new Client(['base_uri' => Bitcodin::getBaseUrl()]);
         if (Bitcodin::isHttpsEnabled()) {
             self::$client->setDefaultOption('verify', __DIR__ . '/cacert.pem');
         }
     }
     return self::$client;
 }
 public function _initialize()
 {
     $url = "https://mailtrap.io/";
     $this->mailtrap = new \GuzzleHttp\Client(['base_uri' => $url, 'timeout' => 1.0]);
     if (isset($this->config['guzzleRequestOptions'])) {
         foreach ($this->config['guzzleRequestOptions'] as $option => $value) {
             $this->mailtrap->setDefaultOption($option, $value);
         }
     }
 }
 /**
  * Get a configured client, creating one if one hasn't been set by
  * setClient().
  *
  * @return Client
  */
 public function getClient()
 {
     if (!$this->client) {
         $this->client = new Client();
         $headers = $this->client->getDefaultOption('headers');
         $headers['User-Agent'] = 'PkpPlnBot 1.0; http://pkp.sfu.ca';
         $this->client->setDefaultOption('headers', $headers);
     }
     return $this->client;
 }
 public function _initialize()
 {
     $url = trim($this->config['url'], '/') . ':' . $this->config['port'];
     $this->mailhog = new \GuzzleHttp\Client(['base_uri' => $url, 'timeout' => 1.0]);
     if (isset($this->config['guzzleRequestOptions'])) {
         foreach ($this->config['guzzleRequestOptions'] as $option => $value) {
             $this->mailhog->setDefaultOption($option, $value);
         }
     }
 }
Example #8
0
 /**
  * @param $token
  * @throws Exception
  */
 private function setTinderAuthenticationToken($token)
 {
     if (strlen($token) != 36) {
         throw new Exception("The supplied Tinder Authentication Token is not in UUID4 format, it should be 36 characters long (including dashes).");
     }
     //if(!preg_match("^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$", $token))
     //    throw new Exception("The supplied Tinder Authentication Token is not in UUID4 format.");
     $this->tinderAuthenticationToken = $token;
     $this->guzzleClient->setDefaultOption('headers/X-Auth-Token', $token);
 }
 /**
  * Register the Guzzle driver.
  *
  * @return void
  */
 protected function registerGuzzle()
 {
     $this->app->singleton('http', function ($app) {
         $client = new Client(['base_url' => "https://{$app['school']}.magister.net/api/"]);
         $client->setDefaultOption('exceptions', false);
         $client->setDefaultOption('cookies', new SessionCookieJar($app['cookie']));
         CacheSubscriber::attach($client);
         return $client;
     });
 }
 public static function factory($config = array(), $logger = null)
 {
     $client = new Client(['base_url' => $config['base_url'] . '/']);
     $client->setDefaultOption('headers', array('Authorization' => 'Bearer ' . $config['access_token']));
     $client->setDefaultOption('config', ['curl' => [CURLOPT_SSLVERSION => 1]]);
     if ($logger !== null) {
         $subscriber = new LogSubscriber($logger, ">>>>>>>>\n{request}\n<<<<<<<<\n{response}");
         $client->getEmitter()->attach($subscriber);
     }
     return $client;
 }
Example #11
0
 /**
  * Sets the default options to the client
  */
 private function setDefaultOptions()
 {
     // Either use user bundle or the system bundle if nothing is specified
     if ($this->certificateManager->listCertificates() !== []) {
         $this->client->setDefaultOption('verify', $this->certificateManager->getAbsoluteBundlePath());
     } else {
         $this->client->setDefaultOption('verify', $this->certificateManager->getAbsoluteBundlePath(null));
     }
     $this->client->setDefaultOption('headers/User-Agent', 'ownCloud Server Crawler');
     if ($this->getProxyUri() !== '') {
         $this->client->setDefaultOption('proxy', $this->getProxyUri());
     }
 }
Example #12
0
 /**
  * Sets the default options to the client
  */
 private function setDefaultOptions()
 {
     // Either use default bundle or the user bundle if nothing is specified
     if ($this->certificateManager->listCertificates() !== []) {
         $dataDir = $this->config->getSystemValue('datadirectory');
         $this->client->setDefaultOption('verify', $dataDir . '/' . $this->certificateManager->getCertificateBundle());
     } else {
         $this->client->setDefaultOption('verify', \OC::$SERVERROOT . '/config/ca-bundle.crt');
     }
     $this->client->setDefaultOption('headers/User-Agent', 'ownCloud Server Crawler');
     if ($this->getProxyUri() !== '') {
         $this->client->setDefaultOption('proxy', $this->getProxyUri());
     }
 }
Example #13
0
 /**
  * @return \GuzzleHttp\Client
  */
 protected function getClient()
 {
     $config = $this->getConfiguration();
     $client = new Client(['base_url' => 'https://rest.nexmo.com', 'defaults' => ['body' => ['api_key' => $config['api_key'], 'api_secret' => $config['api_secret'], 'from' => $config['account_from_number']]]]);
     $client->setDefaultOption('body/api_key', $config['api_key']);
     return $client;
 }
 /**
  * @Request({"update": "json"})
  * @Response("json")
  */
 public function downloadAction($update = null)
 {
     try {
         if ($update) {
             $this['session']->set('system.update', $update);
         } else {
             throw new Exception(__('Unable to find update.'));
         }
         $this['session']->set('system.updateDir', $path = $this->temp . '/' . sha1(uniqid()));
         $client = new Client();
         $client->setDefaultOption('query/api_key', $this->apiKey);
         $downloader = new PackageDownloader($client);
         $downloader->downloadFile($path, $update['url'], $update['shasum']);
         $response = ['message' => __('Copying files...'), 'step' => $this['url']->route('@system/update/copy'), 'progress' => 33];
     } catch (ArchiveExtractionException $e) {
         $response = ['error' => __('Package extraction failed.')];
     } catch (ChecksumVerificationException $e) {
         $response = ['error' => __('Package checksum verification failed.')];
     } catch (UnauthorizedDownloadException $e) {
         $response = ['error' => __('Invalid API key.')];
     } catch (DownloadErrorException $e) {
         $response = ['error' => __('Package download failed.')];
     } catch (NotWritableException $e) {
         $response = ['error' => __('Path is not writable.')];
     } catch (Exception $e) {
         $response = ['error' => $e->getMessage()];
     }
     return $response;
 }
Example #15
0
 public function testAuthenticateClient()
 {
     $guzzle = new Client(['base_url' => 'http://example.com/api']);
     $guzzle->setDefaultOption('headers', ['X-Test' => '1']);
     $expiresIn = 5000;
     $expires = time() + $expiresIn;
     $mock = new Mock([new Response(200, [], Stream::factory(json_encode((object) ['headerToken' => 1234, 'queryToken' => 4321, 'expiresIn' => $expiresIn]))), new Response(200, [], Stream::factory(json_encode((object) ['data' => [1, 2, 3]]))), new Response(200, [], Stream::factory(json_encode((object) ['data' => [1, 2, 3]])))]);
     $guzzle->getEmitter()->attach($mock);
     $history = new History();
     $guzzle->getEmitter()->attach($history);
     $restClient = new RestClient($guzzle);
     $attrs = ['first' => 1, 'second' => 'two'];
     $api = ['authentication' => ['loginRequest' => ['endpoint' => 'login', 'params' => ['par' => ['attr' => 'first']], 'headers' => ['X-Header' => ['attr' => 'second']], 'method' => 'POST'], 'apiRequest' => ['headers' => ['X-Test-Auth' => 'headerToken'], 'query' => ['qToken' => 'queryToken']], 'expires' => ['response' => 'expiresIn', 'relative' => true]]];
     $auth = new Login($attrs, $api);
     $auth->authenticateClient($restClient);
     $request = $restClient->createRequest(['endpoint' => '/']);
     $restClient->download($request);
     $restClient->download($request);
     // test creation of the login request
     self::assertEquals($attrs['second'], $history->getIterator()[0]['request']->getHeader('X-Header'));
     self::assertEquals(json_encode(['par' => $attrs['first']]), (string) $history->getIterator()[0]['request']->getBody());
     // test signature of the api request
     self::assertEquals(1234, $history->getIterator()[1]['request']->getHeader('X-Test-Auth'));
     self::assertEquals('qToken=4321', (string) $history->getIterator()[1]['request']->getQuery());
     self::assertEquals(1234, $history->getIterator()[2]['request']->getHeader('X-Test-Auth'));
     self::assertEquals('qToken=4321', (string) $history->getIterator()[2]['request']->getQuery());
     $expiry = self::getProperty($restClient->getClient()->getEmitter()->listeners('before')[0][0], 'expires');
     self::assertGreaterThan($expires - 2, $expiry);
     self::assertLessThan($expires + 2, $expiry);
 }
 public static function factory($options = array())
 {
     $defaultOptions = array('base_url' => self::getDefaultServiceUrl(), 'defaults' => array('exceptions' => false, 'connect_timeout' => 10, 'timeout' => 60));
     //        $requiredOptions = array();
     //
     //        foreach ($requiredOptions as $optionName) {
     //            if (!isset($options[$optionName]) || $options[$optionName] === '') {
     //                throw new Exception\InvalidArgumentException(
     //                    sprintf('Missing required configuration option "%s"', $optionName)
     //                );
     //            }
     //        }
     $config = Collection::fromConfig($options, $defaultOptions);
     $headers = array('Accept' => 'application/json', 'User-Agent' => 'denner-client/' . self::CLIENT_VERSION);
     if (isset($options['app_id'])) {
         $headers['App-ID'] = $options['app_id'];
     }
     if (isset($options['app_key'])) {
         $headers['App-Key'] = $options['app_key'];
     }
     $httpClient = new HttpClient($config->toArray());
     $httpClient->setDefaultOption('headers', $headers);
     $httpClient->getEmitter()->attach(new Subscriber\ErrorHandler());
     $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;
 }
Example #17
0
 public function post($account = null)
 {
     FacebookSession::setDefaultApplication(getenv('EVC_FACEBOOK_APP_ID'), getenv('EVC_FACEBOOK_APP_SECRET'));
     $client = new Client();
     $client->setDefaultOption('verify', false);
     $res = $client->get('https://graph.facebook.com/v2.2/oauth/access_token', ['query' => ['client_id' => getenv('EVC_FACEBOOK_APP_ID'), 'client_secret' => getenv('EVC_FACEBOOK_APP_SECRET'), 'grant_type' => 'client_credentials']]);
     $access_token = substr($res->getBody(), 13);
     // var_dump($access_token);
     // die();
     $session = new FacebookSession($access_token);
     // Get the GraphUser object for the current user:
     // try {
     //
     $graphObject = (new FacebookRequest($session, 'GET', '/me/accounts'))->execute()->getGraphObject();
     // $graphObject = (new FacebookRequest(
     //     $session, 'GET', '/' . getenv("EVC_FACEBOOK_APP_ID")
     // ))->execute()->getGraphObject();
     // $graphObject = (new FacebookRequest(
     //     $session, 'POST', '/' . getenv("EVC_FACEBOOK_PAGE_ID") . '/feed', array(
     //     	// 'link' => '',
     //     	'message' => 'President Goodluck Jonathan hosted the eight presidential media chat, since May 2011, talks on Security, Elections and debunks rumours #EVC'
     //     )
     // ))->execute()->getGraphObject(GraphPage::className());
     var_dump($graphObject);
     // }
     // catch (FacebookRequestException $e) {}
     // catch (\Exception $e) {}
 }
 public static function factory($options = array())
 {
     $defaultOptions = array('base_url' => 'https://lw-inside.detailnet.ch/api/', 'defaults' => array('exceptions' => false, 'connect_timeout' => 10, 'timeout' => 60));
     //        $requiredOptions = array();
     //
     //        foreach ($requiredOptions as $optionName) {
     //            if (!isset($options[$optionName]) || $options[$optionName] === '') {
     //                throw new Exception\InvalidArgumentException(
     //                    sprintf('Missing required configuration option "%s"', $optionName)
     //                );
     //            }
     //        }
     $config = Collection::fromConfig($options, $defaultOptions);
     $headers = array('Accept' => 'application/json', 'User-Agent' => 'lw-inside-client/' . self::CLIENT_VERSION);
     if (isset($options['app_id'])) {
         $headers['App-ID'] = $options['app_id'];
     }
     if (isset($options['app_key'])) {
         $headers['App-Key'] = $options['app_key'];
     }
     $httpClient = new HttpClient($config->toArray());
     $httpClient->setDefaultOption('headers', $headers);
     $httpClient->getEmitter()->attach(new Subscriber\ErrorHandler());
     $description = new ServiceDescription(require __DIR__ . '/ServiceDescription/Inside.php');
     $client = new self($httpClient, $description);
     return $client;
 }
Example #19
0
 /**
  * @param Client $client
  *
  * @return $this
  */
 public function setClient(Client $client)
 {
     // Assign the client.
     $this->client = $client;
     $this->client->setDefaultOption('headers', ['Content-Type' => 'application/json']);
     // Allow chaining.
     return $this;
 }
Example #20
0
 /**
  * @return ClientInterface
  */
 public function createClient()
 {
     $client = new Client();
     $certPath = __DIR__ . '/cacert.pem';
     if (is_file($certPath)) {
         $client->setDefaultOption('verify', $certPath);
     }
     return $client;
 }
Example #21
0
 /**
  * @return HttpClient
  */
 public static function getHttpClient()
 {
     if (self::$httpClient) {
         return self::$httpClient;
     }
     $client = new HttpClient();
     $client->setDefaultOption('timeout', self::$defaultTimeout);
     return self::$httpClient = $client;
 }
Example #22
0
 public function __construct(Configuration $configuration)
 {
     // save the configuration along with this session
     $this->configuration = $configuration;
     // start up our Guzzle HTTP client
     $this->client = PHRETSClient::make();
     $this->cookie_jar = new CookieJar();
     // set the authentication as defaults to use for the entire client
     $this->client->setDefaultOption('auth', [$configuration->getUsername(), $configuration->getPassword(), $configuration->getHttpAuthenticationMethod()]);
     $this->client->setDefaultOption('headers', ['User-Agent' => $configuration->getUserAgent(), 'RETS-Version' => $configuration->getRetsVersion()->asHeader(), 'Accept-Encoding' => 'gzip']);
     // disable following 'Location' header (redirects) automatically
     if ($this->configuration->readOption('disable_follow_location')) {
         $this->client->setDefaultOption('allow_redirects', false);
     }
     // start up the Capabilities tracker and add Login as the first one
     $this->capabilities = new Capabilities();
     $this->capabilities->add('Login', $configuration->getLoginUrl());
 }
 public function boot()
 {
     $this->app->make('Illuminate\\Broadcasting\\BroadcastManager')->extend('pushstream', function ($app, $config) {
         $client = new Client(['base_url' => $config['base_url'], 'query' => isset($config['access_key']) ? ['access_key' => $config['access_key']] : null]);
         if (!empty($config['cert'])) {
             $client->setDefaultOption('verify', $config['cert']);
         }
         return new PushStreamBroadcaster($client);
     });
 }
 /**
  * Configures the Guzzle Client.
  *
  * @param \GuzzleHttp\Client|Callback|null $client
  */
 public function setClient($client = null)
 {
     if (is_callable($client)) {
         $this->client = value($client);
     } elseif (is_null($client) and is_null($this->client)) {
         $this->client = new Client();
     } else {
         $this->client = $client;
     }
     $this->client->setDefaultOption('verify', false);
 }
Example #25
0
 public function __construct($orgName, $apiKey = '')
 {
     if (is_a($orgName, 'Bouncefirst\\Hiveage\\Api\\Requestor')) {
         $this->requestor = $orgName;
         return;
     }
     $http = new Client(['base_url' => Requestor::getApiUrl($orgName)]);
     $http->setDefaultOption('verify', false);
     $requestor = new Requestor($http);
     $requestor->setKey($apiKey);
     $this->requestor = $requestor;
 }
 /**
  * Configures the Guzzle Client.
  *
  * @param \GuzzleHttp\Client|Callback|null $client
  */
 public function setClient($client = null)
 {
     if (is_callable($client)) {
         $this->client = value($client);
     } elseif (is_null($client) and is_null($this->client)) {
         $this->client = new Client(['verify' => false]);
     } else {
         $this->client = $client;
     }
     if (method_exists($this->client, 'setDefaultOption')) {
         $this->client->setDefaultOption('verify', false);
     }
 }
Example #27
0
 public function testRequestHeaders()
 {
     $guzzle = new Client();
     $guzzle->setDefaultOption('headers', ['X-Test' => '1234']);
     $mock = new Mock([new Response(200, [], Stream::factory('{}'))]);
     $guzzle->getEmitter()->attach($mock);
     $history = new History();
     $guzzle->getEmitter()->attach($history);
     $restClient = new RestClient($guzzle);
     $request = new RestRequest('ep', [], 'GET', ['X-RTest' => 'requestHeader']);
     $restClient->download($request);
     self::assertEquals(['X-RTest' => ['requestHeader'], 'X-Test' => ['1234']], $history->getLastRequest()->getHeaders());
 }
Example #28
0
 public function __construct($id, $token, Client $client = null)
 {
     if (!$client) {
         $client = new Client(['base_url' => self::ENDPOINT]);
     }
     if (!$client->getBaseUrl()) {
         throw new Exception\ClientException('API client is not configured with a base URL');
     }
     if (!ctype_xdigit($id) || !ctype_xdigit($token)) {
         throw new Exception\ClientException('User credentials are invalid');
     }
     $client->setDefaultOption('headers', ['Auth' => "Bearer {$id} {$token}", 'User-Agent' => 'WIU PHP Client/1.0']);
     $this->client = $client;
 }
Example #29
0
 public function testAuthenticateClientJson()
 {
     $config = YamlFile::create(ROOT_PATH . '/tests/data/oauth20bearer/config.yml');
     // FIXME base_url from cfg
     $client = new Client(['base_url' => 'http://example.com']);
     $client->setDefaultOption('headers', ['X-Test' => 'test']);
     $restClient = new RestClient($client);
     $auth = new OAuth20($config->get('authorization'), $config->get('parameters', 'api', 'authentication'), new Builder());
     $auth->authenticateClient($restClient);
     $request = $client->createRequest('GET', '/');
     $client->send($request);
     self::assertEquals('Bearer testToken', $request->getHeader('Authorization'));
     self::assertEquals('test', $request->getHeader('X-Test'));
 }
 /**
  * {@inheritDoc}
  * @return Sender
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     if ($serviceLocator instanceof ServiceLocatorAwareInterface) {
         $serviceLocator = $serviceLocator->getServiceLocator();
     }
     /** @var \Detail\Notification\Options\ModuleOptions $moduleOptions */
     $moduleOptions = $serviceLocator->get('Detail\\Notification\\Options\\ModuleOptions');
     /** @var \Detail\Notification\Options\Sender\WebhookSenderOptions $senderOptions */
     $senderOptions = $moduleOptions->getSender('webhook', 'Detail\\Notification\\Options\\Sender\\WebhookSenderOptions');
     /** @todo Fetch from ServiceLocator by configurable name (provided through options) */
     $httpClient = new HttpClient();
     /** @todo Make configurable */
     $httpClient->setDefaultOption('headers', array('User-Agent' => $senderOptions->getUserAgent()));
     return new Sender($httpClient);
 }