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!
It’s awesome to visit this web pae and reading the views of all friends concerning this article, while I am also zealous of gettig knowledge. http://boyarka-inform.com
I really like and appreciate your blog. Really Great.
Actually no matter if someone doesn’t understand then its up to other visitors that they will help, so here it takes place.
revive rx pharmacy canadian pet meds pharmacy
free slots vegas slots online slots for real money
Im grateful for the blog post.Thanks Again. Keep writing.
I am so grateful for your blog post. Will read on…
Fantastic blog.Thanks Again. Really Cool.
I cannot thank you enough for the blog.Really thank you! Really Cool.
Say, you got a nice article post.Really thank you! Much obliged.
Wow, great post.Thanks Again. Fantastic.
Im thankful for the article post.Thanks Again. Awesome.
Muchos Gracias for your blog. Want more.
You made various nice points there. I did a search on the topic and found mainly folks will go along with with your blog.
Hey There. I discovered your blog the usage of msn. That is a really smartly written article. I’ll be sure to bookmark it and come back to read extra of your helpful info. Thanks for the post. I’ll certainly comeback.
Very informative blog article.Thanks Again. Keep writing.
I am not sure where you are getting your info, but great topic.I needs to spend some time learning more or understanding more.Thanks for wonderful info I was looking for this information for my mission.
Awesome article post. Will read on…
I really liked your article post. Awesome.
I will immediately take hold of your rss as I can’t find your email subscription link or e-newsletter service. Do you have any? Please let me know in order that I could subscribe. Thanks.
I think this is a real great blog.Really looking forward to read more. Really Great.
What’s up, this weekend is nice in favor of me, since this moment i am reading this fantastic educational paragraph here at my residence.
play slots vegas slots online slots games free
This was a really good article. Thank you for creating it. I’ll return for more.
Nice read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch since I found it for him smile Therefore let me rephrase that: Thanks for lunch!
Say, you got a nice article post.Much thanks again.
Hi, just wanted to mention, I liked this blog post. Itwas helpful. Keep on posting!
Thank you ever so for you article post.Thanks Again. Really Great.
Many thanks. Loads of facts!write argumentative essay online coursework i need someone to write my assignment