How to Get User Twitter Access Token



In my previous posts I have explained about how to create a Twitter App and get Consumer Keys and your Twitter Access Token. Now In this post I will explain how to get User Twitter Access Token. For this tutorial, we need a Twitter App and consumer key that will communicate with twitter using Twitter API. So please read How to Auto Post on Twitter Using PHP – Part 1 for create a Twitter App and consumer Key and Auto Post on Twitter Using PHP and API 1.1 for PHP library TwitterOAuth and Twitter API.

Create a PHP file as getAccessToken.php to request for the authentication and write below code in this file:

require_once("Twitter/twitteroauth-master/autoload.php");

use Abraham\TwitterOAuth\TwitterOAuth;

$twData = array(
	'consumer_key' => consumer_key,
	'consumer_secret' => consumer_secret,
	'callback_url' => 'callback.php'
);

$tw = new TwitterOAuth($twData['consumer_key'], $twData['consumer_secret']);
$content = $tw->get("account/verify_credentials");

$request_token = $tw->oauth("oauth/request_token", array("oauth_callback" => $twData['callback']));

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

/* Build authorize URL and redirect user to Twitter. */
$url = $tw->url("oauth/authorize", array("oauth_token" => $token));

header('Location: ' . $url);
exit;

You will be redirected to the twitter for authorize the app to use your account. The screen will be as below:

Twitter authorization page
Twitter authorization page

Now when you click on Authorize App you will be redirected to callback.php and the file should have following code:

require_once("Twitter/twitteroauth-master/autoload.php");

use Abraham\TwitterOAuth\TwitterOAuth;

$twData = array(
	'consumer_key' => consumer_key,
	'consumer_secret' => consumer_secret
);

if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
	unset($_SESSION['oauth_token']);
	unset($_SESSION['oauth_token_secret']);

	header('Location: getAccessToken.php');
	exit;
}

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

$tw = new TwitterOAuth($twData['consumer_key'], $twData['consumer_secret'], $twData['oauth_token'], $twData['oauth_token_secret']);

$access_token = $tw->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));

// here are the access token and token secret of the user
$oauth_token = $access_token['oauth_token'];
$oauth_token_secret = $access_token['oauth_token_secret'];

As per the current Twitter policy, Access token will not expire until user rejects your application from their settings or Twitter admin suspends your application. You can use these token for Auto Post on User’s Twitter page.

Hope this tutorial will help you to get user twitter access token.