Come scaricare la user timeline con le API di Twitter versione 1.1 in php

Il cambio di versione delle Twitter API dalla 1 alla 1.1 ha portato con sè inevitabili problemi per chi aveva già sviluppato client di interfacciamento. Dopo aver googlato, testato e penato un po’ ho aggiornato un vecchio client in php per leggere la timeline di un utente Twitter.

TwitterDevelopers

Raccogliendo le indicazioni dai seguenti link

http://stackoverflow.com/questions/12916539/simplest-php-example-for-retrieving-user-timeline-with-twitter-api-version-1-1

http://stackoverflow.com/questions/14095272/twitter-api-1-1-gives-error-code-32

ho corretto il funzionamento del client in php per leggere la timeline di un utente Twitter, e quindi tutti i suoi ultimi tweet, nel seguente modo:

$twitterId = "mytwitterid";
$count = 20;

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

//oauth array - add oauth variables and all get parameters
$oauth = array(
        'screen_name' => $twitterId,
        'count' => $count,
        'oauth_consumer_key' => $twitter_consumer_key,
        'oauth_nonce' => md5(microtime()),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_token' => $twitter_access_token,
        'oauth_timestamp' => time(),
        'oauth_version' => '1.0'
);

$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($twitter_consumer_secret) . '&' . rawurlencode($twitter_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

//oauth array must be sorted by key name
ksort($oauth);

// Make Requests
$header = array(buildAuthorizationHeader($oauth));
$options = array( CURLOPT_HTTPHEADER => $header,
        CURLOPT_HEADER => false,
        CURLOPT_URL => $url . "?count=$count&screen_name=$twitterId",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false );

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);    
curl_close($feed);

$tweets = json_decode($json);

foreach ($tweets as $tweet) {
    ...
}

Nello script vanno impostati i valori di:

  • twitterId
  • count
  • twitter_consumer_key
  • twitter_access_token
  • twitter_consumer_secret
  • twitter_access_token_secret

Ovviamente lo stesso script può essere usato come base per interazione con gli altri servizi esposti nelle API di Twitter versione 1.1.