Integrating Twitter Social Login
Implementing login using Twitter directly through their provided API endpoints can be tedious and require knowledge of external systems like the OAuth protocol. There are some useful libraries that can help you to quickly and easily implement a “Login using Twitter” button and get your users tweeting through your site. Below we go through the steps to setup a common PHP library used to handle Twitter social login authentication and functionality. Twitter has information on many common technologies libraries here.
- Begin by downloading the Twitteroauth package which we will be using to setup the login using Twitter button. You can use the following composer package to get this:
=5.4.0", "abraham/twitteroauth": "0.3.0-beta" } }-->
- Import the TwitterOAuth class onto your page and initialize the connection:
<!--require 'vendor/autoload.php'; use Abraham\TwitterOAuth\TwitterOAuth; define('CONSUMER_KEY', ); define('CONSUMER_SECRET', ); define('OAUTH_CALLBACK', ); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);-->
Create a Twitter App on the Twitter dev site that will service the requests for Twitter social login for your site.
Replace the above definitions with the following details from your App:
- <Consumer Key>- The Consumer Key found in the created app found under Keys and Access Tokens.
- <Consumer Secret>- The Consumer Secret found in the created app found under Keys and Access Tokens.
- <Callback Location>- The URL that you would like a user to return to after successfully authenticating.
Next generate a Request token that will be used to generate a URL which will trigger the twitter Authentication popup.
From the response object capture the “oauth_token” and “oauth_token_secret” for further use.
Generate the URL to be used to display the Twitter social login Authentication interface.
Setup a button or trigger to cause users to navigate to this URL which will display the Twitter social login interface.
- Once a user has successfully authenticated they will be redirect to the location that you specified in the request_token OAUTH_CALLBACK URL.
- On your Callback page import the TwitterOAuth class again:
<!--require 'vendor/autoload.php'; use Abraham\TwitterOAuth\TwitterOAuth; define('CONSUMER_KEY', ); define('CONSUMER_SECRET', ); define('OAUTH_CALLBACK', );-->
Define the definitions as you did in step 2.
- Initialize the connection using the stored “oauth_token” and “oauth_token_secret”.
- Finally request an access_token to be used to access user data and actions.
At this point your user is logged in and you can make calls to Twitter social login APIs and you have successfully set login using Twitter on your page.
Want to extend your social systems with additional provider functionality check out this post on LinkedIn social login.