Starting authorization

Generating a request_token should only happen when a user shows intent to sign into your site. It requires making an API request to Twitter. In your implementation this page should generally have no HTML rendered and instead do a redirect to the generated URL.

Bootstrapping

First we set need to autoload the TwitterOAuth class and the need Twitter application details. We will also construct a TwitterOAuth instance with the application consumer_key and consumer_secret.

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

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

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

Generating a request_token

Authorizing access to a users account through OAuth starts with getting a temporary request_token. This request_token is only good for a few minutes and will soon be forgotten about.

Request
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
Response Live
array(3) {
  ["oauth_token"]=>
  string(27) "MMasigAAAAAAAAAbAAABiIsX0mU"
  ["oauth_token_secret"]=>
  string(32) "PbFm2H3U1esGvuMxqZnLBdzcJQtCM6FQ"
  ["oauth_callback_confirmed"]=>
  string(4) "true"
}

Sessions

This demo site uses basic PHP sessions but you can use whatever session/storage implementation you want.

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

Build authorize URL

Here we are building a URL the authorizing users must navigate to in their browser. It is to Twitter's authorize page where the list of permissions being granted is displayed along with allow/deny buttons.

Request
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
Response Live
string(79) "https://api.twitter.com/oauth/authorize?oauth_token=MMasigAAAAAAAAAbAAABiIsX0mU"

Next step: authorize on twitter.com