Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

前端 未结 14 2294
盖世英雄少女心
盖世英雄少女心 2020-11-21 17:37

Because of the Twitter API 1.0 retirement as of June 11th 2013, the script below does not work anymore.

// Create curl resource 
$ch = curl_init(); 
// Set u         


        
相关标签:
14条回答
  • 2020-11-21 17:50
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
    
    $timelines = $connection->get('statuses/user_timeline', array('screen_name' => 'NSE_NIFTY', 'count' => 100, 'include_rts' => 1));
    
    0 讨论(0)
  • 2020-11-21 17:51

    Thank you Kris!

    It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.

    The problem for me, was in the ampersand encoding. So in your code where it's the following line

    $url .= "?".http_build_query($query);
    

    I added the following line below:

    $url=str_replace("&","&",$url);
    

    And it worked using two or more parameters like screen_name and count.

    The whole code looks like this:

    $token = 'YOUR TOKEN';
    $token_secret = 'TOKEN SECRET';
    $consumer_key = 'YOUR KEY';
    $consumer_secret = 'KEY SECRET';
    
    $host = 'api.twitter.com';
    $method = 'GET';
    $path = '/1.1/statuses/user_timeline.json'; // api call path
    
    $query = array( // query parameters
        'screen_name' => 'twitterapi',
        'count' => '2'
    );
    
    $oauth = array(
        'oauth_consumer_key' => $consumer_key,
        'oauth_token' => $token,
        'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
        'oauth_timestamp' => time(),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_version' => '1.0'
    );
    
    $oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
    $query = array_map("rawurlencode", $query);
    
    $arr = array_merge($oauth, $query); // combine the values THEN sort
    
    asort($arr); // secondary sort (value)
    ksort($arr); // primary sort (key)
    
    // http_build_query automatically encodes, but our parameters
    // are already encoded, and must be by this point, so we undo
    // the encoding step
    $querystring = urldecode(http_build_query($arr, '', '&'));
    
    $url = "https://$host$path";
    
    // mash everything together for the text to hash
    $base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
    
    // same with the key
    $key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
    
    // generate the hash
    $signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
    
    // this time we're using a normal GET query, and we're only encoding the query params
    // (without the oauth params)
    $url .= "?".http_build_query($query);
    $url=str_replace("&","&",$url); //Patch by @Frewuill
    
    $oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
    ksort($oauth); // probably not necessary, but twitter's demo does it
    
    // also not necessary, but twitter's demo does this too
    function add_quotes($str) { return '"'.$str.'"'; }
    $oauth = array_map("add_quotes", $oauth);
    
    // this is the full value of the Authorization line
    $auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
    
    // if you're doing post, you need to skip the GET building above
    // and instead supply query parameters to CURLOPT_POSTFIELDS
    $options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);
    
    // do our business
    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);
    
    $twitter_data = json_decode($json);
    

    Hope It helps somebody with the same problem I had.

    0 讨论(0)
  • 2020-11-21 17:54

    First of all I wanted to thank jimbo and (his post / twitter-api-php simple library).

    If you are going to use the GET search/tweets API with "twitter-api-php" PHP library (TwitterAPIExchange.php):

    First, you have to just comment "Perform a POST request and echo the response " code area.

    Just use "Perform a GET request and echo the response" code and echo the response and change these two lines:

    $url = 'https://api.twitter.com/1.1/followers/ids.json';
    $getfield = '?screen_name=J7mbo';
    

    to

    $url = 'https://api.twitter.com/1.1/search/tweets.json';
    $getfield = '?q=J7mbo';
    

    (Change screen_name to q, that's it :)

    0 讨论(0)
  • 2020-11-21 17:55

    Like stated in other answers, create a Twitter app to get the token, key and secret. Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $request array in returnTweet() function).

    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }
    
    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }
    
    function returnTweet(){
        $oauth_access_token         = "x";
        $oauth_access_token_secret  = "x";
        $consumer_key               = "x";
        $consumer_secret            = "x";
    
        $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me
    
        //  create request
            $request = array(
                'screen_name'       => 'budidino',
                'count'             => '3'
            );
    
        $oauth = array(
            'oauth_consumer_key'        => $consumer_key,
            'oauth_nonce'               => time(),
            'oauth_signature_method'    => 'HMAC-SHA1',
            'oauth_token'               => $oauth_access_token,
            'oauth_timestamp'           => time(),
            'oauth_version'             => '1.0'
        );
    
        //  merge request and oauth to one array
            $oauth = array_merge($oauth, $request);
    
        //  do some magic
            $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
            $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
            $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
            $oauth['oauth_signature']   = $oauth_signature;
    
        //  make request
            $header = array(buildAuthorizationHeader($oauth), 'Expect:');
            $options = array( CURLOPT_HTTPHEADER => $header,
                              CURLOPT_HEADER => false,
                              CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                              CURLOPT_RETURNTRANSFER => true,
                              CURLOPT_SSL_VERIFYPEER => false);
    
            $feed = curl_init();
            curl_setopt_array($feed, $options);
            $json = curl_exec($feed);
            curl_close($feed);
    
        return json_decode($json, true);
    }
    

    and then just call returnTweet()

    0 讨论(0)
  • 2020-11-21 17:55

    Thanks to this thread, and especially budidino because his code is what drove it home for me. Just wanted to contribute how to retrieve the JSON data from a request. Make changes to "//create request" request array part of the code to perform different requests. Ultimately, this will output the JSON onto the browser screen

    <?php
        function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }
    
    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }
    
    function returnTweet(){
        $oauth_access_token         = "2602299919-lP6mgkqAMVwvHM1L0Cplw8idxJzvuZoQRzyMkOx";
        $oauth_access_token_secret  = "wGWny2kz67hGdnLe3Uuy63YZs4nIGs8wQtCU7KnOT5brS";
        $consumer_key               = "zAzJRrPOj5BvOsK5QhscKogVQ";
        $consumer_secret            = "Uag0ujVJomqPbfdoR2UAWbRYhjzgoU9jeo7qfZHCxR6a6ozcu1";
    
        $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me
    
        //  create request
            $request = array(
                'screen_name'       => 'burownrice',
                'count'             => '3'
            );
    
        $oauth = array(
            'oauth_consumer_key'        => $consumer_key,
            'oauth_nonce'               => time(),
            'oauth_signature_method'    => 'HMAC-SHA1',
            'oauth_token'               => $oauth_access_token,
            'oauth_timestamp'           => time(),
            'oauth_version'             => '1.0'
        );
    
        //  merge request and oauth to one array
            $oauth = array_merge($oauth, $request);
    
        //  do some magic
            $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
            $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
            $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
            $oauth['oauth_signature']   = $oauth_signature;
    
        //  make request
            $header = array(buildAuthorizationHeader($oauth), 'Expect:');
            $options = array( CURLOPT_HTTPHEADER => $header,
                              CURLOPT_HEADER => false,
                              CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                              CURLOPT_RETURNTRANSFER => true,
                              CURLOPT_SSL_VERIFYPEER => false);
    
            $feed = curl_init();
            curl_setopt_array($feed, $options);
            $json = curl_exec($feed);
            curl_close($feed);
    
        return $json;
    }
    
    $tweet = returnTweet();
    echo $tweet;
    
    ?>
    
    0 讨论(0)
  • 2020-11-21 17:57

    The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.

    You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:

    $oauth = array(
               'screen_name' => 'DwightHoward',
               'count' => 2,
               'oauth_consumer_key' => $consumer_key,
               'oauth_nonce' => time(),
               'oauth_signature_method' => 'HMAC-SHA1',
               'oauth_token' => $oauth_access_token,
               'oauth_timestamp' => time(),
               'oauth_version' => '1.0'
             );
    
    $options = array(
                 CURLOPT_HTTPHEADER => $header,
                 //CURLOPT_POSTFIELDS => $postfields,
                 CURLOPT_HEADER => false,
                 CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
                 CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
               );
    
    0 讨论(0)
提交回复
热议问题