Monday, 9 May 2016

2. [How-to] Integrate Twitter into app in order to view tweets timeline, view user's mentions, post tweets and more!

This is the tutorial I found and used: http://code.tutsplus.com/tutorials/how-to-authenticate-users-with-twitter-oauth-20--cms-25713
It's simple and short.
You definitely should use the TwitterOAuth library to simplify the entire process.
You will need to upload the *.php files to a web server. I use Arvixe which costs money, but you can use the free x10hosting.
I did not use Composer to install the TwitterOAuth. I used the manual way instead.

I also followed the this tutorial to save the user's token and secret into MySQL database: http://code.tutsplus.com/articles/how-to-authenticate-users-with-twitter-oauth--net-13595
I used this tutorial as well to get things going in PHP and for Twitter developer setup: http://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/

This is my config.php file:
 <?php  
   
 return [  
   // key and secret of your application  
   'consumer_key'   => 'REPLACE_WITH_YOUR_OWN_CONSUMER_KEY_FROM_TWITTER',  
   'consumer_secret'  => 'REPLACE_WITH_YOUR_OWN_CONSUMER_SECRET_FROM_TWITTER',  
   // callbacks for your application  
   'url_login'     => 'REPLACE_WITH_YOUR_OWN_URL_LOGIN_EXAMPLE: http://www.gerrycao.com/pinkarmr/twitter_login.php',  
   'url_callback'   => 'REPLACE_WITH_YOUR_OWN_URL_CALLBACK_FROM_TWITTER_EXAMPLE: http://www.gerrycao.com/pinkarmr/twitter_callback.php',  
 ];  
   
 ?>  
   
This is my twitter_login.php file:
 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
   
 $config = require_once 'config.php';  
   
 // create TwitterOAuth object  
 $twitteroauth = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);  
   
 // request token of application  
 $request_token = $twitteroauth->oauth(  
   'oauth/request_token', [  
     'oauth_callback' => $config['url_callback']  
   ]  
 );  
   
 // throw exception if something gone wrong  
 if($twitteroauth->getLastHttpCode() != 200) {  
   throw new \Exception('There was a problem performing this request');  
 }  
   
 // save token of application to session  
 $_SESSION['oauth_token'] = $request_token['oauth_token'];  
 $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];  
   
 // generate the URL to make request to authorize our application  
 $url = $twitteroauth->url(  
   'oauth/authorize', [  
     'oauth_token' => $request_token['oauth_token']  
   ]  
 );  
   
 // and redirect  
 header('Location: '. $url);  
 ?>  
This is my twitter_callback.php file:
 <?php  
   
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 mysql_connect('localhost', 'REPLACE_WITH_YOUR_DB_USERNAME', 'REPLACE_WITH_YOUR_DB_PASSWORD');  
 mysql_select_db('REPLACE_WITH_YOUR_DB_NAME');  
   
 session_start();  
   
 $config = require_once 'config.php';  
   
 // get and filter oauth verifier  
 $oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');  
   
 // check tokens  
 if (empty($oauth_verifier) ||  
   empty($_SESSION['oauth_token']) ||  
   empty($_SESSION['oauth_token_secret'])  
 ) {  
   // something's missing, go and login again  
   header('Location: ' . $config['url_login']);  
 }  
   
 // connect with application token  
 $connection = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   $_SESSION['oauth_token'],  
   $_SESSION['oauth_token_secret']  
 );  
   
 // request user token  
 $token = $connection->oauth(  
   'oauth/access_token', [  
     'oauth_verifier' => $oauth_verifier  
   ]  
 );  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   $token['oauth_token'],  
   $token['oauth_token_secret']  
 );  
   
 $user_info = $twitter->get('account/verify_credentials');  
   
 // if something's wrong, go and log in again  
 if(isset($user_info->error)){  
   // Something's wrong, go back to square 1  
   echo "something wrong\n";  
   //header('Location: twitter_login.php');  
 } else {  
    echo "adding new user\n";  
   
     $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, oauth_token, oauth_secret, username) VALUES ('twitter', '{$user_info->id}', '{$token['oauth_token']}', '{$token['oauth_token_secret']}', '{$user_info->screen_name}')");  
     $query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());  
     echo $query;  
     echo "\n";  
     $result = mysql_fetch_array($query);  
     echo $result;  
     echo "\n";  
 }  
 ?>  
Warnings
If you get HTTP 500 - Internal Server Error like me previously.

It's because you already got the $token for the user already! You can't run the twitter_callback.php page for the same user twice! You must save the $token['oauth_token'] and $token['oauth_token_secret'] like to a SQL database or somewhere, and use those two oauth_token and oauth_token_secret from now on, or until the user revoke your application access in his Twitter settings!

I modified my twitter_callback.php to the following for testing after successfully receiving the $token['oauth_token'] and $token['oauth_token_secret'] and then queried for all the user's mentions in Twitter:

 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
 $config = require_once 'config.php';  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   "REPLACE_WITH_YOUR_OWN_OAUTH_TOKEN_FOR_AUTHENTICATED_USER",  
   "REPLACE_WITH_YOUR_OWN_OAUTH_TOKEN_SECRET_FOR_AUTHENTICATED_USER"  
 );  
   
 // post a tweet  
 $statuses = $twitter->get("statuses/mentions_timeline", ["count" => 195]);  
   
 //$string = json_decode($statuses, $assoc = TRUE);  
   
   
   
 foreach($statuses as $status) {  
   echo "Time and Date of Tweet: ".$status->created_at."<br />";  
     echo "Tweet: ". $status->text."<br />";  
     echo "Tweeted by: ". $status->user->name."<br />";  
     echo "Screen name: ". $status->user->screen_name."<br />";  
     echo "Listed: ". $status->user->listed_count."<br /><hr />";  
 }  
 ?>  
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/10/2016]

No comments:

Post a Comment

Thank you for not blocking our ads =)

Please consider adding this blog to the whitelist of your ads blocker :)