Twitter API not authenticating when using search query


#1

I’m trying to use the Twitter API in PHP to list tweets that match a hashtag:

$url = ‘https://api.twitter.com/1.1/search/tweets.json’;
$count = 3;
$hashtag = ‘#twitter’;
$oauth = array(
‘oauth_consumer_key’ => ‘##########’,
‘oauth_nonce’ => hash(‘SHA1’, time()),
‘oauth_signature’ => ‘’,
‘oauth_signature_method’ => ‘HMAC-SHA1’,
‘oauth_timestamp’ => time(),
‘oauth_token’ => ‘##########’,
‘oauth_version’ => ‘1.0’
);

$oauth_vals[] = “q={$hashtag}”;
foreach ($oauth as $key => $value)
{
if (empty($value)) continue;
$oauth_vals[] = “{$key}={$value}”;
}
$oauth_vals[] = “count={$count}”;

$base = ‘GET&’ . rawurlencode($url) . ‘&’ . rawurlencode(implode(’&’, $oauth_vals));
$composite_key = rawurlencode(’##########’) . ‘&’ . rawurlencode(’##########’);
$oauth_signature = base64_encode(hash_hmac(‘sha1’, $base, $composite_key, true));
$oauth[‘oauth_signature’] = rawurlencode($oauth_signature);

foreach ($oauth as $key => $value)
{
$auth_header[] = “{$key}=”{$value}"";
}
$auth_header = implode(’, ', $auth_header);

$options = array(
CURLOPT_HTTPHEADER => array(“Authorization: OAuth {$auth_header}”),
CURLOPT_HEADER => false,
CURLOPT_URL => “https://api.twitter.com/1.1/search/tweets.json?q={$hashtag}&count={$count}”,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPGET => true
);

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

var_dump($tweets); exit;

But I get this error:

array(1) { [“errors”]=> array(1) { [0]=> array(2) { [“message”]=> string(26) “Could not authenticate you” [“code”]=> int(32) } } }

What have I done wrong? All the tokens and keys are correct from my apps section on Twitter… so can’t understand why I’m getting this error.

If I do: https://api.twitter.com/1.1/statuses/user_timeline.json?count={$count}&screen_name={$screen_name} then it works… so perhaps I’m using incorrect code for the search api?


#2

OAuth is hard to get right, I would recommend to use an existing library for it like, for PHP:

For example, when computing the OAuth signature if I remember properly the parameters have to be sorted by name.


#3

But why does it work when using the user_timeline endpoint, but NOT work when using the search endpoint? Can you see anything wrong with my code?


#4

What do you mean has to be sorted by name?


#5

No idea why the code above doesn’t work! Be awesome if someone could tell me what the problem was… but in the end I’ve used this: https://github.com/J7mbo/twitter-api-php to do the API call.


#6

I mean a parameter whose name start with A must be before a parameter whose name start with B. In your code the “q” parameter is before the “count” parameter even though Q is after C in the alphabet.