I am new to OAuth, and am struggling to exchange a request token for an access token with the Twitter API using PHP.
I am using OAuth - Consumer and Server library for PHP from http://code.google.com/p/oauth-php/
I successfully get a request token and store the token and secret in a cookie:
$options = array('consumer_key' => $this->key, 'consumer_secret' => $this->secret);
OAuthStore::instance("2Leg", $options);
$request = new OAuthRequester('https://api.twitter.com/oauth/request_token', "POST", null);
$result = $request->doRequest(0, array(CURLOPT_CAINFO=>$_SERVER["DOCUMENT_ROOT"].'/cacert.pem'));
$params = explode('&',$result['body']);
foreach ($params as $param)
{
list($key, $value) = explode('=', $param);
if ($key == 'oauth_token')
$oauth_token = $value;
else if ($key == 'oauth_token_secret')
$oauth_token_secret = $value;
}
setcookie('twitter_token',$oauth_token);
setcookie('twitter_token_secret',$oauth_token_secret);
header("Location: http://api.twitter.com/oauth/authorize?oauth_token=$oauth_token");
exit;
When Twitter redirects back to my site, I attempt to exchange the token for an access token using the following code:
try
{
$params = array('oauth_token'=>$_COOKIE['twitter_token'], 'oauth_token_secret'=>$_COOKIE['twitter_token_secret']);
$request = new OAuthRequester('https://api.twitter.com/oauth/access_token', 'POST', $params);
///!!! THIS FAILS, throws an exception
$result = $request->doRequest(0, array(CURLOPT_CAINFO=>$_SERVER["DOCUMENT_ROOT"].'/cacert.pem'));
}
catch(OAuthException2 $e)
{
die("<pre>OAuth Exception for url " . $request->getRequestUrl() . "<br />$e</pre>");
}
But it always fails with:
OAuth Exception for url https://api.twitter.com/oauth/access_token
exception 'OAuthException2' with message 'Request failed with code 401:
/oauth/access_token
Invalid / expired Token
' in library/OAuthRequester.php:117
Stack trace:
#0 twitter.php(50): OAuthRequester->doRequest(0, Array)
#1 index.php(15): Twitter->authenticate(true)
#2 {main}
Can anyone point me in the right direction? Perhaps I'm missing something fundamental - the docs on the web are quite confused.
Many thanks
-- Craig