如何使用twitter API使用guzzle?

时间:2016-12-03 12:33:39

标签: laravel twitter laravel-5 twitter-oauth guzzle

我在laravel 5.3中使用guzzle并尝试访问twitters API以检索users timeline。但是当我尝试时,我不断收到错误,内容为if you have tow function with same name, one in head and another one in an external .js file and both of them write a value in <a>, the result will be from the internal one, let's look at an example <html> <head> <script src="myscripts.js"></script> <script type="text/javascript"> function test(){ document.getElementById("tester").innerHTML="Internal"; } </script> </head> <body onload="test()"> <a id="tester"></a> </div> </body> </html> ------------------------------------- in myscripts.js function test(){ document.getElementById("tester").innerHTML="external"; } ------------------------------------- when the page run it shows: Internal

这是我的代码:

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

我已经检查并验证了令牌是最新的,但它一直给我这个错误。我不确定我错过了什么。

1 个答案:

答案 0 :(得分:0)

Twitter Api使用oauth 1.1,因此您需要使用oauth-subscriber

composer require guzzlehttp/oauth-subscriber

这是一个有效的例子:

<?php

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;

class TwitterApiController extends Controller{


    public function getUserTimeline() 
    {
        $stack = HandlerStack::create();

        $middleware = new Oauth1([
            'consumer_key'    => 'env('TWITTER_CLIENT_ID')',
            'consumer_secret' => 'env('TWITTER_SECRET')',
            'token'           => $token,
            'token_secret'    => '$secret'
        ]);

        $stack->push($middleware);

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

        $res = $client->get('statuses/user_timeline.json',['query' => [
            'screen_name' => 'laravelphp',
            'count' => '5',
        ]]);

        dd(json_decode($res->getBody()), true);
    }
}