Easy steps… to your Twitter App in PHP (OAuth_Twitter.php)

January 24, 2010 3 comments

Hey…
[tweetmeme service=”bit.ly”]

alert(‘hello’);

Twitter App in php can be done so easily using the   library OAuth_Twitter.php . This library works as a connecting layer between your Application and Twitter API by making use of the package OAuth. If OAuth_Twitter.php is included inside your code, which acts as a gate way for your Application to Twitter API, you can access Twitter data using the methods of this Library

Setup the coding environment

As I stated earlier the library OAuth_Twitter.php works with Zend OAuth package, you have to download and include this package in your code. You can download the same from the Box.net widget of this blog of from the Google code repository. Once you are done this, you can include OAuth_Twitter.php in your code(downloadable from box.net widget in the home page of the blog).  Done!!! Now start playing with twitter…

Register your App with Twitter

For twitter to share its database with your application, you have to register your application with Twitter. The details of the same is there in my previous post You have to use your Application configuration data, provided by twitter once your application is registered, don’t worry. Your headache ends here.  From here onwards all your actions  will be handled by the library, using the its methods
[tweetmeme service=”bit.ly”]
How to use OAuth_Twitter.php

OAuth_Twitter.php library is furnished in object oriented fashion. Once your have included this file to your code, you have to create an object of class OAuth_Twitter. You have to provide your configuration data as a php array to the class

$configuration = array(
‘callbackUrl’ => ‘http://yoursite/callback’,     //callback url for Twitter API
‘siteUrl’ => ‘http://twitter.com/oauth’,
‘consumerKey’ => ‘oPI6Q213VSMd5W84FfHbOA’,            // consumer key provided by twitter
‘consumerSecret’ => ‘0VCb37yQOdfsDSWu50o3XOxA’  // consumerSecret key provided by twitter
);

$my_twitter = new OAuth_Twitter($configuration);

Here I want to introduce you some of the functions… for all others you  are provided with a detailed documentation.

Sometimes, to retrieve some kind of data (Followers list) twitter will ask the user of your application to authenticate with twitter.  For actions like updating your status is mandatory to authenticate your identity to Twitter. Once you have authenticated, then you can do any further action directly. After successful authentication Twitter will always redirect to the call back url of your application, with an access token for your application. Your application will be using this access token for further access. For your application, you dont have to worry about any of these details. A single function  ” $my_twitter->handleCallback() ” will take care of all thses actions for you 🙂

____________________________________

callback.php

$my_twitter->handleCallback()    //  You have to call this single function in your call back url. This will take care of setting and managing your access_token and all

_______________________________________

requestAuth()

Another function which may seem complicated is requestAuth(). This is any user to authenticate with twitter from your application. In high level it does 3 things. Check for already authenticated, if yes return 1, else redirect to twitter to authenticate and on successful authentication, twitter will redirect to your callback url.

Getting Twitter Data

Now you can access any kind of data like, followers, friends , tweets etc… if authentication is required and not done, the function will redirect to authentication page and continue

$my_twitter->updateStatus($status)  –> to update your status

$my_twitter->getFollowersByHandle(‘BasilBThoppil’)  –> to get BasilBThoppil ‘s followers

AS SIMPLE AS THAT ……………… 🙂
[tweetmeme service=”bit.ly”]

Categories: Code Workshop

Tweet from your own Twitter Application in PHP(zend)

December 12, 2009 1 comment

Do you find more power in the 140 characters than, Twitter does.  Do you think that twitter application is not providing enough features to fulfill all your requirements? How about tweeting from your own application, which will be denoted with all your tweets in twitter. Sounds great right? Dude, twitter provides enough APIs to write your own applications and tweet as you like. What else should we wait for??

Twitter is now becoming a business Server. So many applications  for business, marketing, advertising are getting incubated using Twitter APIs making use of twitter’s huge database. Twitter provides powerful APIs to meet with these requirements. Zend provides a library ‘OAuth’ for interacting with twitter. This library allows our PHP application to authenticate with twitter.


Few words…  about O_Auth

This zend library authenticates websites/webapplications to access the protected resources of a web service through the API, provided by the web service. This allows the user of the application, to access the web services’ data, without directly authenticating to the web service.

Here I am specifying about writing a very simple application to tweet. I am leading the way to the destination of our PHP_Zend Twitter application through 5 simple steps. I am using Zend Framework, even though our code is too simple and small in size. This is because I am so comfortable with Zend and also, I want to expand my application in future. So I hope that you are are an expert(??) in MVC architecture already. Yup, time to take a dive get… set…Gooooooo


Step 1 — Setting up the coding environment


1. Zend Framework coding environment

I hope you have already set up the zend framework to start with your application.Our library Zend_Oauth is not there with the default package even in the latest Zend version. So we have to download the whole library from zend’s website and copy into the Libray/Zend. You can access the complete directory from the following my box link box link

2. Domain name which redirects to your application.

And also you need a domain to be redirected to your application from the web , for eg ‘http://myapp.com’. Make sure that our application is accessible using a domain name from the net. This is for the Twitter API to send the responses back to our application.


Step 2 — Registering your application with twitter.

We have to register the details of our application in twitter. Follow this link http://twitter.com/apps/new to get redirected to the registration form. You can give your applications name, a short blahhh blahh about your application. The important data are

Application Website:  your application’s URL — http://myapp.com/

Organization and website — blahh blahh
callback url http://myapp.com/index/callback/                                                                                                                                   (This is the url via the twitter API contacts our application, here in our application to send back the authentication details.)

application type is ‘browser’ , access type is ‘read write’ and select check box for twitter login and SUBMIT. Now you have registered your application with twitter .


Step 3 — Weaving the code…

Here onwards I will be going in MVC fashion since I want to expand this application to meet more requirements. Our simple application contains only 3 controllers. IndexController.php, AppController.php and OperatiosController.php . We have a configuration file, config.php which contains our app’s general configurations, and some minimal view files.
This is our zend directory structure.

|--application
    |--controllers
        |-- IndexController.php
        |-- TwitterController.php
        |-- AppController.php
    |--include
        |-- config.php
    |--model
    |--view
        |--scripts
            |--twitter
                |--index.phtml
            |--index
                |--index.phtml
                |--callback.phtml
|--library
|--public
|--index.php
|--.htaccess

Control Flow

Our app’s home page will have a link, clicking on which, the user will be taken to twitter authentication page. On successful authentication, the user will be redirected again back to our application, from where the user can submit the TWEETS. 🙂

Source Code

config.php — File in which we store our application configurations. The application use these configurations when we try to access Twitter.


<?php
class CONF {
	
	public static $configuration = array(
	    'callbackUrl' => 'http://myapp.com/index/callback',
	    'siteUrl' => 'http://twitter.com/oauth',
	    'consumerKey' => 'oPI6d5W84FffHbfH',
	    'consumerSecret' => '0VCb37yQOy5kdsfsdEDJp3SdsfsdafDFSDFE$xA'
	);
}
?>

AppController.php — Common controller which checks the authentication with Twitter. This class will be extended to TwitterController.

<?php
class AppController extends Zend_Controller_Action{

	function init(){
		$consumer = new Zend_Oauth_Consumer(CONF::$configuration);
		session_start();
		if (!$_SESSION['TWITTER_REQUEST_TOKEN']) {
		    $token = $consumer->getRequestToken();
		    $_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);
		    $consumer->redirect();
		}
	}
}
?>



IndexController.php

<?php
require_once 'config.php';
require_once 'Zend/Oauth/Consumer.php';

class IndexController extends Zend_Controller_Action{

	function indexAction(){
		/*
		 * Rdirects to index/index.phtml
		 */
	}

	function requestauthAction(){
		$consumer = new Zend_Oauth_Consumer(CONF::$configuration);
		session_start();
			/*
			 * Check for already authenticated and
			 * app has TWITTER ACCESS TOKEN
			 */
		if (!$_SESSION['TWITTER_ACCESS_TOKEN']) {
			/*
			 * Redirect to twitter API with REQUEST TOKEN
			 */
		    $token = $consumer->getRequestToken();
		    $_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);
		    $consumer->redirect();
		}else{
			$this->render('callback');
		}
	}

	/*
	 * Twitter authenticate our app with the details provided by user and
	 * if success redirects back to our application
	 *
	 * Twitter redirects to our  app via URL http://myapp.com/index/callback
	 *
	 * handled by callbackAction() function
	 */

	function callbackAction(){
		session_start();
		require_once 'Zend/Oauth/Consumer.php';
		$consumer = new Zend_Oauth_Consumer(CONF::$configuration);

		/*
		 * If REQUEST TOKEN IS set
		 */
		if (isset($_SESSION['TWITTER_REQUEST_TOKEN']) || !isset($_SESSION['logged_in'])) {
		    $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));

		    /*
		     * Set the access key supplied by Twitter
		     * Twiter and our application refer to this access token when perform any action with Twitter
		     */
		    $_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($token);

		    /*
		     * Now we have ACCESS TOKEN which can be used for further actions
		     * Now REQUEST TOKEN can be set to NULL
		     */
		    $_SESSION['TWITTER_REQUEST_TOKEN'] = NULL;

		    /*
		     * Flag for logged in or not
		     */
		    $_SESSION['logged_in'] = 1;
		}
	}

	/*
	 * Unset all sessions
	 * Unset Access Token
	 */
	function logoutAction(){
		session_start();
		$_SESSION['TWITTER_ACCESS_TOKEN'] = null;
		$_SESSION['TWITTER_REQUEST_TOKEN'] = null;
		$_SESSION['logged_in'] = 0;
		session_unset();
		$this->render('index');
	}
}

?>

index/index.phtml — home page of our application, contains a link to the auth request action



<?php 
echo '<?xml version="1.0" encoding="UTF-8"?>';
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
  <head>
    <title>Tweet Via smart bee</title>

  </head>
  <body>
  	<a href="http://myapp.com/index/requestauth"< Enter bEE'z app </a>
  </body>
</html>



twitter/index.phtml and index/callback.phtml wil be our home page which contains a link to enter the app

    <form action="http://basiltestsite.isa-geek.org/callback/twitter" method="post" id="statusform">
        <p<What are you upto?</p>
        <!-- We are not making any validation for 140 chars in our application -->
        <textarea name="status" id="status" rows="2" cols="70%" onkeypress="return imposemax(this);"></textarea>
        <br/><input type="submit" id="submit" value="Tweet"/>
    </form>
   Click to
    <a href="http://basiltestsite.isa-geek.org/index/logout">Logout</a>
</pre>
TwitterController.php --- Contains action for tweeting and other related actions
<pre>

TwitterController.php — Collection of twitter action. Now it has only TwitterAction() which tweets our updates to twitter. This extends AppController which checks for twitter authentication before each action

<?php
Zend_Loader::loadClass('Zend_Oauth_Consumer');
require_once 'AppController.php';
include_once 'config.php';

class TwitterController extends AppController{
	function indexAction(){
		set_include_path(
		    '/home/padraic/projects/zf/trunk/library'
		    . PATH_SEPARATOR . '/home/padraic/projects/zf/incubator/library'
		    . PATH_SEPARATOR . get_include_path()
		);

		require_once 'Zend/Oauth/Consumer.php';

		$consumer = new Zend_Oauth_Consumer(CONF::$configuration);

		if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {

		    $token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
		    $_SESSION['TWITTER_ACCESS_TOKEN'] = serialize($token);

		    // Now that we have an Access Token, we can discard the Request Token
		    // Keep on eye on gathering RTs in real life which are never used.

		    $_SESSION['logged_in'] = 1;

		}
	}

/*
  *  Will be called when post the tweet
  * check for authentication
  * if yes post the tweet text to twitter
  *
  */

	function twitterAction(){
		//echo $_SESSION['TWITTER_ACCESS_TOKEN'];die;
		if (!empty($_POST) && isset($_POST['status'])) {

		    // Easiest way to use OAuth now that we have an Access Token is to use
		    // a preconfigured instance of Zend_Http_Client which automatically
		    // signs and encodes all our requests without additional work
		    $consumer = new Zend_Oauth_Consumer(CONF::$configuration);

		    $token = unserialize($_SESSION['TWITTER_ACCESS_TOKEN']);
		    $token = (object)$token;

		    $client = $token->getHttpClient(CONF::$configuration);
		    $client->setUri('http://twitter.com/statuses/update.json');
		    $client->setMethod(Zend_Http_Client::POST);
		    $client->setParameterPost('status', $_POST['status']);
		    $response = $client->request();

		    // Check if the json response refers to our tweet details (assume it
		    // means it was successfully posted). API gurus can correct me after.

		    $data = json_decode($response->getBody());
		    $result = $response->getBody(); // report in error body (if any)
		    if (isset($data->text)) {
		        $result = 'true'; // response includes the status text if a success
		        echo $_POST['status']."

";
		    }

		    echo $_POST['status']."";
			$this->render('index');
		} else {
		   print "Error error!!";die;
		}
	}
}
?>



Closing Note

This is the code for an application which functions in a minimal mode. Validations and some exceptional case hadling are not at all covered in our code.  Other than make our tweet get posted to the Twitter, I haven’t  considered any kind of  security issues too. I hope you guys will join the voyage and come up with your suggetion to make this article complete. Cheers 🙂

Access Token