Attaching OAuth1 to GuzzleHttp\Client
Asked Answered
O

1

6

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.

Oarfish answered 8/9, 2015 at 17:27 Comment(0)
O
8

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]
                        ]);
Oarfish answered 9/9, 2015 at 7:41 Comment(1)
Reference github.com/guzzle/guzzle/blob/master/UPGRADING.md the event system was completely removed from Guzzle 6.Bernardinabernardine

© 2022 - 2024 — McMap. All rights reserved.