Example #1
0
 /**
  * Public factory method to create instance of Client.
  *
  * @param array $options Available properties: [
  *     'consumerKey' => 'foo',
  *     'consumerSecret' => 'bar',
  * ]
  * @param mixed $logger Logger used to log
  *     messages. Pass a LoggerInterface to use a PSR-3 logger. Pass a
  *     callable to log messages to a function that accepts a string of
  *     data. Pass a resource returned from ``fopen()`` to log to an open
  *     resource. Pass null or leave empty to write log messages using
  *     ``echo()``.
  * @return self
  */
 public static function create(array $options = [], $logger = Client::LOG_NONE)
 {
     $client = new \GuzzleHttp\Client(['base_url' => self::$url, 'defaults' => ['auth' => 'oauth']]);
     if ($logger !== false) {
         $subscriber = new LogSubscriber($logger, Formatter::DEBUG);
         $client->getEmitter()->attach($subscriber);
     }
     $oauth = new Oauth1(['consumer_key' => $options['consumerKey'], 'consumer_secret' => $options['consumerSecret']]);
     $client->getEmitter()->attach($oauth);
     $mapper = new ResultObjectMapper();
     return new self(new Guzzle\ClientAdapter($client, new Guzzle\ExceptionMapper($mapper)), new Validator(Validation::createValidator()), $mapper);
 }
Example #2
0
 private function getMockClient(array $responses)
 {
     $http = new \GuzzleHttp\Client();
     $mockResponses = new Mock($responses);
     $http->getEmitter()->attach($mockResponses);
     return $http;
 }
Example #3
0
 /**
  * Public factory method to create instance of Client.
  *
  * @param array $options Available properties: [
  *     'apiKey' => 'xxxxxx',
  *     'sandbox' => true,
  *     'url' => 'https://api.isign.io',
  *     'sandboxUrl' => 'https://developers.isign.io',
  * ]
  * @param LoggerInterface|callable|resource|null $logger Logger used to log
  *     messages. Pass a LoggerInterface to use a PSR-3 logger. Pass a
  *     callable to log messages to a function that accepts a string of
  *     data. Pass a resource returned from ``fopen()`` to log to an open
  *     resource. Pass null or leave empty to write log messages using
  *     ``echo()``.
  * @return self
  */
 public static function create(array $options = [], $log = false)
 {
     $client = new \GuzzleHttp\Client();
     if ($log !== false) {
         $subscriber = new LogSubscriber($log);
         $client->getEmitter()->attach($subscriber);
     }
     return new self(new GuzzleClientAdapter($client), new ResponseMapper(), Validation::createValidator(), $options);
 }
 public function testHMAC()
 {
     $context = new Context(array('keys' => array('pda' => 'secret'), 'algorithm' => 'hmac-sha256', 'headers' => array('(request-target)', 'date')));
     $client = new \GuzzleHttp\Client(['auth' => 'http-signatures']);
     $client->getEmitter()->attach(new RequestSubscriber($context));
     $message = $client->createRequest('GET', '/path?query=123', array('headers' => array('date' => 'today', 'accept' => 'llamas')));
     $context->signer()->sign(new Message($message));
     $expectedString = implode(',', array('keyId="pda"', 'algorithm="hmac-sha256"', 'headers="(request-target) date"', 'signature="SFlytCGpsqb/9qYaKCQklGDvwgmrwfIERFnwt+yqPJw="'));
     $this->assertEquals($expectedString, (string) $message->getHeader('Signature'));
 }
Example #5
0
function getHandler(array $mockResponses = [])
{
    if (class_exists('GuzzleHttp\\HandlerStack')) {
        $mock = new \GuzzleHttp\Handler\MockHandler($mockResponses);
        $handler = \GuzzleHttp\HandlerStack::create($mock);
        $client = new \GuzzleHttp\Client(['handler' => $handler]);
        return new \Google\Auth\HttpHandler\Guzzle6HttpHandler($client);
    }
    $client = new \GuzzleHttp\Client();
    $client->getEmitter()->attach(new \GuzzleHttp\Subscriber\Mock($mockResponses));
    return new \Google\Auth\HttpHandler\Guzzle5HttpHandler($client);
}
Example #6
0
 public function setUp()
 {
     $client = new GuzzleHttp\Client();
     $watcher = new Gsaulmon\GuzzleRecorder\GuzzleRecorder(__DIR__ . '/Fixtures/Http');
     $watcher->includeCookies(false);
     $client->getEmitter()->attach($watcher);
     \PHRETS\Http\Client::set($client);
     $config = new \PHRETS\Configuration();
     $config->setLoginUrl('http://retsgw.flexmls.com/rets2_1/Login')->setUsername(getenv('PHRETS_TESTING_USERNAME'))->setPassword(getenv('PHRETS_TESTING_PASSWORD'))->setRetsVersion('1.7.2');
     $this->session = new PHRETS\Session($config);
     $this->session->Login();
 }
Example #7
0
 protected function getMockHttpClient($successfulLogin, $response = null)
 {
     if ($successfulLogin) {
         $data = '{"data":{"CSRFPreventionToken":"csrf","ticket":"ticket","username":"******"}}';
         $login = "******";
     } else {
         $login = "******";
     }
     $mock = new \GuzzleHttp\Subscriber\Mock([$login, "HTTP/1.1 202 OK\r\nContent-Length: 0\r\n\r\n{$response}"]);
     $httpClient = new \GuzzleHttp\Client();
     $httpClient->getEmitter()->attach($mock);
     return $httpClient;
 }
 /**
  * @param string $token
  * @param string $tokenSecret
  * @return GuzzleHttp\Client
  */
 public function createInstance($token = NULL, $tokenSecret = NULL)
 {
     $oauthClient = new \GuzzleHttp\Client(['base_url' => $this->baseUrl, 'defaults' => array('auth' => 'oauth')]);
     $params = array('consumer_key' => $this->key, 'consumer_secret' => $this->secret);
     if ($token !== NULL) {
         $params['token'] = $token;
     }
     if ($tokenSecret !== NULL) {
         $params['token_secret'] = $tokenSecret;
     }
     $oauth = new \GuzzleHttp\Subscriber\Oauth\Oauth1($params);
     $oauthClient->getEmitter()->attach($oauth);
     return $oauthClient;
 }
Example #9
0
 /**
  * Make request
  *
  * @param \GuzzleHttp\Psr7\Uri $url
  * @param string $method
  * @param array $oauth_params
  *
  * @return string
  */
 protected function makeRequest(\GuzzleHttp\Psr7\Uri $url, $method = 'post', array $oauth_params = array())
 {
     if (!isset($this->getProviderConfig()['consumer_key'], $this->getProviderConfig()['consumer_secret'])) {
         throw new InvalidArgumentException('Keys consumer_key and consumer_secret must be set in config');
     }
     $oauth_params = array_replace(array('consumer_key' => $this->getProviderConfig()['consumer_key'], 'consumer_secret' => $this->getProviderConfig()['consumer_secret'], 'callback' => $this->getCallbackUrl()), $oauth_params);
     $oauth = new \GuzzleHttp\Subscriber\Oauth\Oauth1($oauth_params);
     $http_client = new \GuzzleHttp\Client(array('defaults' => ['auth' => 'oauth']));
     $http_client->getEmitter()->attach($oauth);
     try {
         $result = $http_client->{$method}($url);
     } catch (\GuzzleHttp\Exception\RequestException $exception) {
         throw new Apishka_SocialLogin_Exception('Provider return an error', 0, $exception);
     }
     $result->getBody()->seek(0);
     return $result->getBody()->getContents();
 }
Example #10
0
 public function boot()
 {
     $this->bindService('log', \Monolog\Logger::class, function ($this) {
         $log = new \Monolog\Logger($this->getName());
         $log->pushHandler(new \Monolog\Handler\StreamHandler($this['log_file'], \Monolog\Logger::DEBUG));
         return $log;
     });
     $this->bindAliased('request', \Illuminate\Http\Request::class, function ($this) {
         return \Illuminate\Http\Request::createFromGlobals();
     });
     $this->bindAliased('guzzle', \GuzzleHttp\Client::class, function ($app) {
         $client = new \GuzzleHttp\Client();
         $client->getEmitter()->attach($app->make(\IpnForwarder\Guzzle\GuzzleSubscriber::class));
         return $client;
     });
     $this->bindService('paypal', \PayPal\Ipn\Listener::class);
     $this->bindService('urls', \IpnForwarder\UrlCollection::class);
     $this->bindService('ipnForwarder', \IpnForwarder\Forwarder::class);
     $this->bindService('ipnProcessor', \IpnForwarder\Processor::class);
 }
 public function setup()
 {
     $this->client = new GuzzleHttp\Client(['defaults' => ['headers' => ['User-Agent' => 'GuzzleRecorder']]]);
     $this->recorder = new GuzzleRecorder(__DIR__ . '/responses');
     $this->client->getEmitter()->attach($this->recorder);
 }
<?php

/*
 * You can authenticate directly to an OAuth-secured URL by
 * providing an access_token, assuming you already have one
 */
use kamermans\GuzzleOAuth2\OAuth2Subscriber;
require_once __DIR__ . '/../vendor/autoload.php';
// Setup OAuth
$oauth = new OAuth2Subscriber();
// Manually specify access_token.  When it expires, you will get an exception
$oauth->getTokenData()->accessToken = 'somelongtoken';
$client = new GuzzleHttp\Client();
// Attach OAuth subscriber to the Guzzle client and all URLs will be authenticated
$client->getEmitter()->attach($oauth);
$response = $client->get('http://somehost/some_secure_url');
echo "Status: " . $response->getStatusCode() . "\n";
Example #13
0
 public function twitter()
 {
     $requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
     $accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
     $authenticateUrl = 'https://api.twitter.com/oauth/authenticate';
     $client = new GuzzleHttp\Client();
     if (!Request::get('oauth_token') || !Request::get('oauth_verifier')) {
         $oauth = new Oauth1(['consumer_key' => Config::get('secrets.TWITTER_KEY'), 'consumer_secret' => Config::get('secrets.TWITTER_SECRET'), 'callback' => Config::get('secrets.TWITTER_CALLBACK')]);
         $client->getEmitter()->attach($oauth);
         // Step 1. Obtain request token for the authorization popup.
         $requestTokenResponse = $client->post($requestTokenUrl, ['auth' => 'oauth']);
         $oauthToken = array();
         parse_str($requestTokenResponse->getBody(), $oauthToken);
         $params = http_build_query(array('oauth_token' => $oauthToken['oauth_token']));
         // Step 2. Redirect to the authorization screen.
         return Redirect::to($authenticateUrl . '?' . $params);
     } else {
         $oauth = new Oauth1(['consumer_key' => Config::get('secrets.TWITTER_KEY'), 'consumer_secret' => Config::get('secrets.TWITTER_SECRET'), 'token' => Request::get('oauth_token'), 'verifier' => Request::get('oauth_verifier')]);
         $client->getEmitter()->attach($oauth);
         // Step 3. Exchange oauth token and oauth verifier for access token.
         $accessTokenResponse = $client->post($accessTokenUrl, ['auth' => 'oauth']);
         $profile = array();
         parse_str($accessTokenResponse, $profile);
         // Step 4a. If user is already signed in then link accounts.
         if (Request::header('Authorization')) {
             $user = User::where('twitter', '=', $profile['user_id']);
             if ($user->first()) {
                 return Response::json(array('message' => 'There is already a Twitter account that belongs to you'), 409);
             }
             $token = explode(' ', Request::header('Authorization'))[1];
             $payloadObject = JWT::decode($token, Config::get('secrets.TOKEN_SECRET'));
             $payload = json_decode(json_encode($payloadObject), true);
             $user = User::find($payload['sub']);
             $user->twitter = $profile['user_id'];
             $user->displayName = $user->displayName || $profile['screen_name'];
             $user->save();
             return Response::json(array('token' => $this->createToken($user)));
         } else {
             $user = User::where('twitter', '=', $profile['user_id']);
             if ($user->first()) {
                 return Response::json(array('token' => $this->createToken($user)));
             }
             $user = new User();
             $user->twitter = $profile['user_id'];
             $user->displayName = $profile['screen_name'];
             $user->save();
             return Response::json(array('token' => $this->createToken($user)));
         }
     }
 }
Example #14
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
// Push response into ring Server
$mock = new GuzzleHttp\Subscriber\Mock(array(file_get_contents(__DIR__ . '/../fixtures/response.findOneBy.txt'), file_get_contents(__DIR__ . '/../fixtures/response.findBy.txt')));
$client = new GuzzleHttp\Client();
$client->getEmitter()->attach($mock);
$client->getEmitter()->attach(new GuzzleHttp\Subscriber\Log\LogSubscriber(null, GuzzleHttp\Subscriber\Log\Formatter::DEBUG));
$client = new O3Co\Query\Bridge\GuzzleHttp\ProxyClient($client);
$repository = new O3Co\Query\SampleClient\ModelRepository($client);
$data = $repository->findOneById(1);
//var_dump($data);
$data = $repository->getByNameAndCategory('name', 'category');
var_dump($data);