I have a website on which a user can create an account and I also have set up a complementary Twitter application. I would like to allow my users to link their Twitter account to their account on my site, so that when they log in with their credentials for my website, they have quick access to Twitter functionality such as posting a tweet of content from my site without having to go through another Twitter login. Worded differently, I want to store my users OAuth access token and OAuth secret token so that I can, for example, show their profile picture when they login to my site (NOT logging in with Twitter). Would storing those tokens be the correct way to accomplish my goal? Right now I am trying to use the EpiTwitter Library. Here is my php for how I’m currently going about this:
$page = new PageCreator($pageinfo); //My class to handle building the HTML for my pages
$twitterObj = new EpiTwitter($__TWITTER['ConsumerKey'], $__TWITTER['ConsumerSecret']); //Make a twitter object with my app's tokens
if(isset($_GET['oauth_token'])) { //If they have been redirected here from Twitter
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
$username = $twitterInfo->screen_name;
$t = new TwitterToken; //My class to hold basic twitter info
$t->access = $token->oauth_token;
$t->secret = $token->oauth_token_secret;
$t->handle = $username;
$userDBA = UserDBA::getInstance(); //My class for interacting with my User table
$userDBA->addTwitter($_SESSION['user'],$t); //Updates the user record
$page->addContent("<p>Thanks! @$username is now linked to your NBAQuotes account!</p>");
} else {
if(isset($_SESSION['user']) && !isset($_SESSION['user']->twitter)) { //If they are logged in but do not have Twitter info stored
$url = $twitterObj->getAuthorizationUrl();
$page->addContent("<a href='$url'>Link your twitter account!</a>");
} else { //They are not logged in at all
$page->addContent("<p>Please sign in with your NBAQuotes.com account first!</p>");
}
}
The database interactions all work just fine. I know the keys retrieved here are correct at first because retrieving their Twitter username with these new tokens is always successful. However, after changing the page, if I make a new EpiTwitter object like:
$twitterObj = new EpiTwitter($__TWITTER['ConsumerKey'], $__TWITTER['ConsumerSecret'],$t->access,$t->secret);
$twitterInfo= $twitterObj->get_accountVerify_credentials();
where $t is my TwitterToken for the logged in user and var_dump($t) shows that it is populated with the correct values, I get an ‘EpiOAuthNotAuthorized’ exception. I’ve noticed that if I try this multiple times for the same Twitter account, the tokens it returns are different every time. How do I get permanent access tokens using PHP and OAuth?