Zend_Service_Twitter and OAuth – How to use twitter API in Zend Framework

Zend_Service_Twitter, OAuth, Twitter API and how the f*ck to do it right..?

Using Zend Framework is a very pleasant thing, but sometimes you may.. sort of.. hit the wall. When you need to use Twitter Applications API in your web application, you may find some lack of information about the best practice and workflow of this subject. The flow is pretty simple actually, and I will explain it in short descriptions and code snippets as examples.

The flow

The first step is to build a method to authorize your application and to request permissions from the user. This is done by using the Zend_Oauth_Consumer library’s mechanism to obtain the so called “request token”. The request token is used later by your application, to authenticate it’s self and to obtain the “access token” needed to initialize the Zend_Service_Twitter.
Here is an example of how to do this:

	protected function _authTwitter()
	{
		$config = array(
			'callbackUrl' => $this->view->serverUrl() . '/tweet/twitter-callback',
			'siteUrl' => 'http://twitter.com/oauth',
			'consumerKey' => "YOUR_APPLICATION_KEY",
			'consumerSecret' => "YOUR_APPLICATION_SECRET"
		);

		$consumer = new Zend_Oauth_Consumer($config);

		$token = $consumer->getRequestToken(); //this may throw an exception if something goes wrong, so don't hesitate to try/catch it

		$this->session->twitter_request_token = serialize($token); //$this->session is an Zend_Session_Namespace instance, we save the request token in the session for later usage in the callback

		$consumer->redirect();
	}

The code above will redirect your application to twitter.com/oauth to request permissions from the user. This requires a “callback” url to land after finishing the process of authentication and authorization.
You should call this method when you don’t have a access token stored and you need to request permissions to perform an API call.

The second step is to implement the callback action method, to do the following tasks:

  1. Check if there is a request token set in the session to continue the OAuth authentication flow
  2. Check if there is an OAuth response in the $_GET
  3. If both conditions are true, initialize the Zend_Oauth_Consumer again and obtain access token, based on the signed request and the request token.
  4. If access token is granted, save it for later usage, if not, handle the exception and fallback
	public function twitterCallbackAction()
	{
		$config = array(
			'callbackUrl' => $this->view->serverUrl() . '/tweet/twitter-callback',
			'siteUrl' => 'http://twitter.com/oauth',
			'consumerKey' => "YOUR_APPLICATION_KEY",
			'consumerSecret' => "YOUR_APPLICATION_SECRET"
		);

		$consumer = new Zend_Oauth_Consumer($config);

		//$this->session is an instance of Zend_Session_Namespace
		if (!empty($_GET) && isset($this->session->twitter_request_token))
		{
			try
			{
				$token = $consumer->getAccessToken(
						$_GET, unserialize($this->session->twitter_request_token)
				);
			}
			catch (Exception $e)
			{
				$this->log("TWITTER SUBMIT TWEET ERROR: ".$e->getMessage());
				//$this->log is an instance of Zend_Log

				$this->_redirect("/tweet");
				
				return;
			}

			//save the access token and clear the request token			

			$this->session->twitter_access_token = serialize($token);

			$this->session->twitter_request_token = null;

			//go back to application

			$this->_redirect("/tweet");
		}
		else
		{
			$this->session->errors = array("Invalid twitter connection...");

			$this->_redirect("/tweet");
		}
	}

If everything goes well you can now implement a form, that will post a message to your application, that will be tweeted in the user’s twitter account. You may do a lot of things actually. Take a look at the official Zend_Service_Twitter API.

Here is a Zend_Service_Twitter example of a twitter API call:

	protected function _sendMessage($message)
	{
		$twitter = new Zend_Service_Twitter(array(
					'accessToken' => unserialize($this->session->twitter_access_token)
				));//use access token from session

		$response = $twitter->status->update($message); //post tweet (less than 140 chars)

		$this->log("TWITTER SUBMIT TWEET RESPONSE: ".$response); //log, just in case of failures
	}

Good luck and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *


five × = 30

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>