In this video we learn how to create a Twitter app, get the Twitter apps credentials, and use those credentials to log a user in through Twitter using their API. Once the user is logged in and authenticated through Twitter’s API, we can get all their user info and display it on our website.
Step 1: Create a Twitter App
In order to connect to the API with a script, we need some credentials so we can authenticate with Twitter. To get these credentials we need to setup a Twitter App.
- Go to https://developer.twitter.com/en/apps and click on the “create an app” button. To create an App, you need to be setup with a developer account. If you do not have a developer account, Twitter will send you to a form which will set you up with a developer account. Then you can come back here and try creating an app again.
- Fill out the create app form, create the app, and the page should refresh.
- Click on the “Keys and Tokens” tab. This tab contains the credentials required in our code in order to make a successful request to the Twitter API. For logging in we need to focus on the Consumer Api Keys. These will be used in our code and must match what we have in our app.
- The last bit we need to define is the callback URL. This can be found in the “App Details” tab. Here we need to set the callback URL. This is the URLTwitter will send the user to once they click the “Authorize App” button. This callback url will also be specified in our code and must match what we have in the Twitter app dashboard otherwise the user will not be able to authenticate and login with our Twitter App. You can have multiple callback URLs for your app. I have one for local testing, and one for my website. All that matters is the callback URL we specify in our code, exists in the Twitter app dashboard for our app.
Step 2: Get Twitter-API-Login-PHP from GitHub
This repository will do the heavy lifting for us in terms of talking to the API. Clone or download this repository into the directory setup for this project.
Twitter-API-Login-PHP on GitHub -> https://github.com/AmirMustafa/Twitter-API-Login-PHP
Step 3: Code!
Now that we have our credentials and our Twitter-API-Login-PHP repository, we are all set to begin coding.
config.php
Create a config.php file in the working directory. This will contain our credentials and callback URL. We separate out credentials to make updating them easier. In case we need our credentials in multiple scripts, all we have to do is require the config.php. If the credentials change, we only have to update them in one place, config.php. Update the defines with the credentials and callback URL for the working Twitter app. Here is what the file should look like.
<?php // your app consumer key define( 'CONSUMER_KEY', 'YOUR-CONSUMER-KEY' ); // your app consumer secret define( 'CONSUMER_SECRET', 'YOUR-CONSUMER-SECRET' ); // your app callback url define( 'OAUTH_CALLBACK', 'YOUR-CALLBACK-URL' );
index.php
The index.php file is where all the action happens! Here is where we require our config.php file, Twitter-API-Login-PHP repository, and display things in the browser depending on the current status of the user.
To do this, we need to determine the state of the user. The user can either be authorized with our twitter app, coming from our Twitter callback url, or not authorized with our app. If the user is no authorized with our app, we will display a “Login with Twitter” link. If they are authorized with our app, we will use their access token, which we have stored in the $_SESSION variable, to call the Twitter API and request their user information.
The last thing to cover is authorizing a user for the first time. This happens when the user clicks on the “Authorize App” button. Once they click on that button, Twitter will send them to the callback URL we have defined in our config.php file. Twitter appends onto that callback URL an oauth_verifier variable, and an oauth_token variable. We use these $_GET variables to generate an access token for the user. We then save the access token to the $_SESSION variable and use it to call the Twitter API and request the users info.
<?php // using sessions to store token info session_start(); // require config and twitter helper require 'config.php'; require 'twitter-login-php/autoload.php'; // use our twitter helper use Abraham\TwitterOAuth\TwitterOAuth; if ( isset( $_SESSION['twitter_access_token'] ) && $_SESSION['twitter_access_token'] ) { // we have an access token $isLoggedIn = true; } elseif ( isset( $_GET['oauth_verifier'] ) && isset( $_GET['oauth_token'] ) && isset( $_SESSION['oauth_token'] ) && $_GET['oauth_token'] == $_SESSION['oauth_token'] ) { // coming from twitter callback url // setup connection to twitter with request token $connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret'] ); // get an access token $access_token = $connection->oauth( "oauth/access_token", array( "oauth_verifier" => $_GET['oauth_verifier'] ) ); // save access token to the session $_SESSION['twitter_access_token'] = $access_token; // user is logged in $isLoggedIn = true; } else { // not authorized with our app, show login button // connect to twitter with our app creds $connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET ); // get a request token from twitter $request_token = $connection->oauth( 'oauth/request_token', array( 'oauth_callback' => OAUTH_CALLBACK ) ); // save twitter token info to the session $_SESSION['oauth_token'] = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; // user is logged in $isLoggedIn = false; } if ( $isLoggedIn ) { // logged in // get token info from session $oauthToken = $_SESSION['twitter_access_token']['oauth_token']; $oauthTokenSecret = $_SESSION['twitter_access_token']['oauth_token_secret']; // setup connection $connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, $oauthToken, $oauthTokenSecret ); // user twitter connection to get user info $user = $connection->get( "account/verify_credentials", ['include_email' => 'true'] ); if ( property_exists( $user, 'errors' ) ) { // errors, clear session so user has to re-authorize with our app $_SESSION = array(); header( 'Refresh:0' ); } else { // display user info in browser ?> <img src="<?php echo $user->profile_image_url; ?>" /> <br /> <b>User:</b> <?php echo $user->name; ?> <br /> <b>Location:</b> <?php echo $user->location; ?> <br /> <b>Twitter Handle:</b> <?php echo $user->screen_name; ?> <br /> <b>User Created:</b> <?php echo $user->created_at; ?> <br /> <hr /> <br /> <h3>User Info</h3> <textarea style="height:400px;width:100%"><?php echo print_r( $user, true ); ?></textarea> <?php } } else { // not logged in, get and display the login with twitter link $url = $connection->url( 'oauth/authorize', array( 'oauth_token' => $request_token['oauth_token'] ) ); ?> <a href="<?php echo $url; ?>">Login With Twitter</a> <?php }
Running the index.php should present a flow like the screenshots below. First, a “Login with Twitter” link will be displayed. Clicking on the link will take the user to Twitter where the have to authorize with our Twitter App. When they click authorize, Twitter will redirect to our callback URL and we will use the API to get the users info and display it in the browser.
“Login With Twitter” link.
Authorize with our Twitter App page on Twitter.
Twitter sends user back to our callback URL and we display the users info on our website.
Links
The full code example can be found in the GitHub link above along with a live demo! The video tutorial for this can also be found in the YouTube link above. That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!
Hi Justin, That already not work https://www.screencast.com/t/lHbcBkSufX
Not sure, I just tested it out and it displayed my info. Maybe try again or try refreshing your browser.
Es ist die richtige Zeit, Pläne für die Zukunft zu machen und es ist Zeit, glücklich zu sein. Ich habe diesen Beitrag gelesen und wenn ich könnte, möchte ich Ihnen einige interessante Dinge oder Ratschläge vorschlagen. Vielleicht könnten Sie folgenden Artikel auf diesen Artikel Bezug nehmen. Ich möchte noch
mehr Dinge darüber lesen!
This is so great to read We have do more things like this for the police men They are protecting us and we need to support them in this way
whoah this blog is wonderful i love reading your articles Keep up the great work! You know, lots of people are searching around for this information, you could aid them greatly
I know tthis web sige gifes qulity depending content and extra information, iss
there anyy other site which presents thhese ata in quality?
Whhen someone writtes an piece off wriuting he/she
retains the irea oof a uaer inn his/her mimd that hhow a user ccan know it.
Thhus that’s whhy this post iss outstdanding. Thanks!
Inspirig ques there. Whaat occurred after?
Take care!
Hey there, Youu have done an incredible job.
I ill definitedly digg it annd personaally suggest
tto my friends. I’m confident they’ll bee benefited from
thiks web site.