Twitter 1.1 API and cURL
Posted: Mon Mar 04, 2013 7:37 pm
The title says it all. I'm having issues using cURL and PHP to obtain twitter posts using the 1.1 API and OAuth. Back when 1.0 was functional, I used that all the time. Now it's dying tonight, and I'm doing what I can to learn 1.1 and OAuth in the process. What I did was do a lot of Googling, and the best thing I came up with was using this example:
However, all of this returns a blank screen. So naturally, I used the OAuth tool on the twitter dev site, generated a request and sent it though cURL in Terminal, SUCCESS! I generate one using this method as it seems to work for everyone, FAIL! It cannot be authenticated. I've been at this all day, and I'm getting a stress headache because I cannot figure this thing out. Any suggestions or something to help me get this to actually do something? 
Code: Select all
<?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 buildAutorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "ACCESS_TOKEN";
$oauth_access_token_secret = "ACCESS_TOKEN_SECRET";
$consumer_key = "CONSUMER_KEY";
$consumer_key_secret = "CONSUMER_KEY_SECRET";
$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');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAutorizationHeader($oauth), 'Except:');
$options = array(CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
print_r($twitter_data);
?>