Cameron
Cameron

Reputation: 28783

Twitter API not authenticating when using search query

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?

Upvotes: 0

Views: 246

Answers (1)

Cameron
Cameron

Reputation: 28783

Well I'm not sure what was wrong with my code, but using this:

https://github.com/J7mbo/twitter-api-php

works great, so I'd recommend using this code if anyone wants to use the Twitter API.

Apparently the parameters MUST be alphabetical order, e.g. count=1&q=#twitter

Upvotes: 3

Related Questions