Finish authorization

The user should now have returned from Twitter having authorized access to their account. A request_token is a short-lived one time use value so if it is invalid users will have to start the authorization flow over.


Set up as before but hold off on the TwitterOAuth instance.

require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

define('CONSUMER_KEY', getenv('CONSUMER_KEY'));


Pull the temporary oauth_token back out of sessions. If the oauth_token is different from the one you sent them to Twitter with, abort the flow and don't continue with authorization.

$request_token = [];
$request_token['oauth_token'] = $_SESSION['oauth_token'];
$request_token['oauth_token_secret'] = $_SESSION['oauth_token_secret'];

if (isset($_REQUEST['oauth_token']) && $request_token['oauth_token'] !== $_REQUEST['oauth_token']) {
    // Abort! Something is wrong.

Finish bootstrapping

Now we make a TwitterOAuth instance with the temporary request token.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);

Get access_token

At this point we will use the temporary request token to get the long lived access_token that authorized to act as the user.

$access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_REQUEST['oauth_verifier']]);
Response Cached
  "oauth_token" => "62532xx-eWudHldSbIaelX7swmsiHImEL4KinwaGloxxxxxx",
  "oauth_token_secret" => "2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYxxxxxx",
  "user_id" => "6253282",
  "screen_name" => "twitterapi"

Credentials storage

This is the important part where you save the credentials to your database of choice.

$_SESSION['access_token'] = $access_token;

You now know the users identity and can start interacting with their Twitter account.

Next step: get your profile data