Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching OAuth1 to GuzzleHttp\Client

I'm trying to upgrade a class to use GuzzleHttp\Client to search tweets using twitter api. I'm having trouble attaching Oauth1. It worked fine with Guzzle3 and OAuthPlugin.

Here is the code block:

        $client = new Client(['base_uri' => 'https://api.twitter.com']);

        $auth = new Oauth1([
            'consumer_key' => Config::get('twitter.consumer_key'),
            'consumer_secret' => Config::get('twitter.consumer_secret'),
            'token' => Config::get('twitter.token'),
            'token_secret' => Config::get('twitter.token_secret')

        ]);

// Not sure if this is correct
$client->getEmitter()->attach($auth); // This is line 40 inside TwitterServiceProvider.php

I get the following error:

InvalidArgumentException in Client.php line 80: Magic request methods require a URI and optional options array

1. in Client.php line 80
2. at Client->__call('getEmitter', array()) in TwitterServiceProvider.php line 40

P.S So far, I have figured, I should be using https://github.com/guzzle/oauth-subscriber. However, no luck yet.

like image 764
mishka Avatar asked Sep 08 '15 17:09

mishka


1 Answers

Resolved.

  1. I couldn't get it to work using getEmitter. This may not be the right approach.
  2. I switched over to guzzle/oauth-subscriber and it works now. There is a good example here: https://github.com/guzzle/oauth-subscriber
  3. base_uri options should have a trailing slash.

New Code:

        $stack = HandlerStack::create();

        $auth = new Oauth1([
            'consumer_key' => Config::get('twitter.consumer_key'),
            'consumer_secret' => Config::get('twitter.consumer_secret'),
            'token' => Config::get('twitter.token'),
            'token_secret' => Config::get('twitter.token_secret')

        ]);

        $stack->push($auth);

        $client = new Client([
            'base_uri' => 'https://api.twitter.com/1.1/',
            'handler' => $stack,
            'auth' => 'oauth'
        ]);

A request is made like below:

$client->get('search/tweets.json', [
                                'query' => ['q' => $query]
                        ]);
like image 71
mishka Avatar answered Sep 28 '22 07:09

mishka