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.
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);
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 Cached
[ "oauth_token" => "zlgW3QAAAAAA2_NZAAABfxxxxxxk", "oauth_token_secret" => "pBYEQzdbyMqIcyDzyn0X7LDxxxxxxxxx", "oauth_callback_confirmed" => "true" ]
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'];
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 Cached
https://api.twitter.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hxxxxxx
Redirect the user to Twitter where they will authorize your application to access their account and be redirected back to the `OAUTH_CALLBACK` URL.