Pages

2010/10/01

Single User Zend_Service_Twitter

When running a website for yourself or your company based on Zend Framework, you might want to show the Twitter messages to your audience.

Although the Zend Framework manual extensively describes how to set up a true Twitter application with the new OAuth implementation of Twitter using Zend_Service_Twitter and Zend_Oauth (since ZF-1.10.0), this is not what you're looking for. You need a simple approach, using the single user OAuth implementation of Twitter.

Registration at Twitter.
Register your "app" to twitter at http://dev.twitter.com/apps/new where you'll be presented a registration form for your app. Since it's not really an app, you should register your website as the app.
Once registered, you need to accept the general terms for usage of the Twitter API.


Once accepted, your applications registered and you can start implementing it. But for a single user approach, you need to retrieve your access tokens.
Fetching tweets
Now it's time to fetch those tweets and post them on your website.

Since these tokens are config elements, we store them in our application.ini as we keep this as our main configuration file for our whole website.

[edited 10/3] These configuration settings are bogus and won't work on my personal account!

; Twitter service
service.twitter.oauth.username = "DragonBe"
service.twitter.oauth.oauth_token = "1234567-xPhPanDz3nDfRam3W0RkN0wW1THS1nGl3Z3nd0aUth"
service.twitter.oauth.oauth_token_secret = "8tH1sStr1nGmUstB3sT0r3ds0MwH3r3V3RryS3cr3t"

Now a simple model can be used to set up the verification process and retrieve the Twitter instance.

<?php
class Application_Model_TwitterClient
{
protected $_config;
protected $_twitter;

public function __construct()
{
$config = new Zend_Config_Ini(
APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
$this->_config = $config->service->twitter->oauth;
$this->_twitter = new Zend_Service_Twitter();
}

public function authenticate()
{
$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken($this->_config->oauth_token)
->setTokenSecret($this->_config->oauth_token_secret);

$this->_twitter->setLocalHttpClient(
$accessToken->getHttpClient($this->_config->options->toArray()));
return $this->_twitter->account->verifyCredentials(); } public function getTwitter() { return $this->_twitter; } }

Now we just need to call this model in our controller to retrieve the messages themselves

<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$twitterClient = new Application_Model_TwitterClient();
$result = $twitterClient->authenticate();
$twitter = $twitterClient->getTwitter();
$status = $twitter->status->userTimeline();
$this->view->statusMsgs = $status;
}
}

And in your view you just loop through those status messages

<li class="myTweetList">
<?php foreach ($this->statusMsgs as $tweet): ?>
<li><?php echo $this->escape($tweet->text); ?></li>
<?php endforeach; ?>
</ul>

Of course you need to add your own validation and caching to this code. But in a nutshell this works pretty damn good.

I've even build a model around retrieving those twitter messages and the actual properties of a Twitter status, but this is beyond the scope of this article.

If you find this information useful, or if you have a better approach, let me know in the comments.

16 comments:

  1. I hope the tokens you exposed here are not valid any longer, other wise, you should quickly invalidate them if you like to keep your account :-)

    ReplyDelete
  2. Nice article, quick overview of the functionality!

    @pilif come on, do they look anywhere near real keys?

    ReplyDelete
  3. @pilif,

    Just as Iwan pointed out, these keys are bogus and won't work (unless someone at Twitter puts a prank on me).

    But thanks for mentioning it, I added a small message explaining the configuration is bogus.

    ReplyDelete
  4. Thanks for this article, I was searching a way to update my application which was using simple auth. and was not working any more.

    I had to modify a bit your code (the config come from a DB), but twitter return an error: Invalid Signature.

    I have double checked token and secret, I'm sure it's correct, and I can retrieve my timeline, but I can't update my status.

    On this post, it said that more parameters are need: http://bit.ly/bnBkRi

    Any idea about this?

    Thx!

    ReplyDelete
  5. @pvledoux,


    I'm not sure about updating status messages using above code, but I've been using a simple twitter script to update our company's dev-box twitter account when someone commits to SVN.

    Check out http://dragonbe.pastebin.com/HGiGsa8V for my example script (of course with bogus account details)

    ReplyDelete
  6. Thanks a lot! In fact I was trying to inject my token (the string) as the accessToken (which is in fact an object). I better understand how it is suppose to work (or not) now!

    ReplyDelete
  7. Anonymous6/10/10 14:11

    $accessToken->getHttpClient($this->_config->options->toArray()));

    or

    $accessToken->getHttpClient($this->_config->toArray()));

    ?

    ReplyDelete
  8. Very nice article if you look at the technique used. The only thing that I was wondering is why you prefer retrieving tweets on the application level of twitter when there is an RSS feed available for each twitter account?

    I can imagine to use this solution to connect and send status updates.

    ReplyDelete
  9. @Martin,

    I posted this article since I already had a working Twitter client that needed to be converted to use with their change to OAuth and that the Zend_Twitter manual only explains a full application approach and not a single user usage of the API.

    Besides, using the API you can do so much more than with a simple RSS feed.

    ReplyDelete
  10. Anonymous above is right, there is an ->options-> too many in the code. In the authenticate() function, the source layout breaks at the end slightly.

    Apart from that, the code seems to run, but I'm consistently getting a 'could not authenticate you' from Twitter..

    ReplyDelete
  11. Fixed my problem; for people struggling with the same issue, in the above tutorial 2 options are missing. Make sure your options also contain the consumer key and secret, which is necessary to sign the requests that are sent to Twitter.

    E.g.:

    service.twitter.oauth.consumerKey = 'your consumer key';
    service.twitter.oauth.consumerSecret = 'your consumer secret';

    ReplyDelete
  12. @Ivo,


    Hey thanks. Apparently I forgot to put them in here, cause I have those set in my configuration.

    But thanks for your feedback, much appreciated.

    ReplyDelete
  13. Hey Thanks, single user are a large part users of twitter

    ReplyDelete
  14. Anonymous7/5/11 14:50

    Thx!
    Yours tips help me. I used them on www.megafonik.pl

    ReplyDelete
  15. Anonymous18/1/12 20:18

    Thanks for the tips above. This saved me a ton of work - Thanks!

    ReplyDelete