I'm building a Twitter app with PHP using the TwitterOAuth library for user authentication.
I am able to redirect the user to Twitter for authentication and to receive the oauth token, oauth secret and oauth verifier, however I am not able to complete the last step of authentication where I get the access token. I'm developing on localhost and I have set up the callback path with
http://127.0.0.1:80/TwitterApp/update.php
My app has read and write permissions.
Here's my code:
index.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// request authentication tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $oauth->getRequestToken(
'http://127.0.0.1/TwitterApp/update.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_secret'] = $request_token['oauth_token_secret'];
if($oauth->getLastHttpCode()==200){
// Let's generate the URL and redirect
$url = $oauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
echo "something went wrong";
}
?>
update.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token'])
&& !empty($_SESSION['oauth_secret'])) {
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION['oauth_token'], $_SESSION['oauth_secret']);
$access_token = $oauth->oauth("oauth/access_token",
array("oauth_verifier" => $_GET['oauth_verifier']));
$_SESSION['access_token'] = $access_token;
}
else {
header('Location: index.php');
}
?>
On execution, $access_token in update.php becomes
'{"error":"Invalid / expired Token","request":"/oauth/access_token"}' with HTTP response status 401 instead of returning the authentication values.