ZF Version: 1.10.8
The source code of this post is available at GitHub.
At this short tutorial i will show to how use Zend_Service_Twitter and Zend_OAuth. I’m considering that:
- You have a working ZF environment.
- You have registered your application at Twitter.com and have the consumer key and secret.
I won’t get into the details of how OAuth work, since there are many tutorials about it. But to summarize what our controller will do:
- User access authenticate action and it’s redirected to Twitter.com
- If user allow application access, he gets back to our application on callback action.
- Callback action process the request and if user is authenticated, redirect to index action.
- Index action uses twitter service class to get user timeline ( or do other actions ).
The first thing is to define a few configuration parameters. Since they are common between your controller actions, we will place it at application.ini. So open file applications/configs/application.ini and add the following lines:
twitter.callbackUrl = "http://localhost/twitter/callback" twitter.siteUrl = "http://twitter.com/oauth" twitter.consumerKey = "yourConsumerKey" twitter.consumerSecret = "yourConsumerSecret"
The directives are self explanatory, just make sure that the callback url is set to the correct action.
Now that you have the config, let’s create a controller for it. In this example, it will be called twitter:
<?php
class TwitterController extends Zend_Controller_Action
{
public function init()
{
}
public function indexAction()
{
}
public function authenticateAction()
{
}
public function callbackAction()
{
}
}
Since we will need the config variables on all actions, we define it at init method:
public function init()
{
// Define zend config on registry. I'm doing it here, but you probably have this on your bootstrap
$zendConfig = new Zend_Config_Ini( APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV );
Zend_Registry::set( 'Zend_Config' , $zendConfig );
}
We have to redirect user to Twitter.com, so that he can allow our application to access his account. This is done at authenticate action:
public function authenticateAction()
{
$zendConfig = Zend_Registry::get( 'Zend_Config' );
// Instance oauth consumer with config options
$consumer = new Zend_Oauth_Consumer($zendConfig->twitter->toArray());
// Using the default session namespace, we store the request token serialized
$session = new Zend_Session_Namespace();
$session->requestToken = serialize( $consumer->getRequestToken() );
// Redirect user to twitter.com
$consumer->redirect();
}
If user clicks on allow, he will be redirected to the callback action with a series of GET parameters containing the auth info. We have to process it in order to get the access token.
public function callbackAction()
{
$zendConfig = Zend_Registry::get( 'Zend_Config' );
// Instance oauth consumer with config options
$consumer = new Zend_Oauth_Consumer($zendConfig->twitter->toArray());
// Use default session namespace
$session = new Zend_Session_Namespace();
// Check if we got a get request and that user already have a request token
if ( !empty( $this->_request->getQuery() ) && !empty( $session->requestToken ) ) {
// Get access token
$token = $consumer->getAccessToken( $this->_request->getQuery() , unserialize( $session->requestToken ) );
// Store access token on a session variable. You can also store on DB, in case you want to use later
$session->accessToken = serialize( $token );
// Remove request token, not necessary anymore
unset( $session->requestToken );
// Redirect to index action
return $this->_helper->redirector( 'index' );
} else {
throw new Exception( 'Invalid access. No token provided.' );
}
}
As you can see, if everything works user is redirected to index action. At index action, i’ve placed an example of how to get user recent tweets. Zend_Service_Twitter offers many functions, you can check them at ZF manual.
public function indexAction()
{
// Default namespace
$session = new Zend_Session_Namespace();
try {
// Check if user have access token.
if ( empty( $session->accessToken ) ) {
throw new Exception( 'You are not logged in. Please, try again.' );
}
// Unserialize access token
$token = unserialize($session->accessToken);
$zendConfig = Zend_Registry::get( 'Zend_Config' );
// Prepare a config array with access token and config options
$config = $zendConfig->twitter->toArray();
$config['username'] = $token->getParam( 'screen_name' );
$config['accessToken'] = $token;
$twitter = new Zend_Service_Twitter( $config );
// Verify if credentials work
$response = $twitter->account->verifyCredentials();
if ( !$response || !empty( $response->error ) ) {
throw new Exception( 'Wrong credentials. Please, try to login again.' );
}
// Vardump user timeline ( one tweet )
var_dump( $twitter->status->userTimeLine() );
} catch ( Exception $e ) {
echo $e->getMessage();
}
die();
}
That’s it. Hope you found this tutorial userful.
If you want, you can download the full source-code: TwitterController.php.
Thanks a ton for this tutorial.
I got an error because of the empty checks, but otherwise this is a really clear explenation to get twitter running in a Zend application!
Thanks for the article.
But in my implementation I’ve added one more option to the config
twitter.authorizeUrl = “https://twitter.com/oauth/authenticate”
This option changes behaviour a little: if user have already given an authentication – then twitter will not ask again for it.
I had to fight a bit to tell Zend Framework 2 that this code was working fine even if just with PHP 5.3 namespaces 😀
Thank you for sharing, OAuth is still a confusing beast when you have lots of hours of work on your back 🙂