Archive

Posts Tagged ‘twitter api’

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
Advertisements