Mini Tutorial:
Integrating Twitter and Magento: Part 1

With the ever-increasing usage of social media, integrating social media is an oft sought-after feature. Seeing as I’m an active Twitter user (@spyroboy), its API greatly interests me so I’m going to tell you all about the Twitter API and integrating tweet streams into your Magento installation.

This should be used as an introductory guide to writing Twitter applications using the Twitter RESTful API.

Let’s just get right into it.

Creating Your Application

Okay, so we’ll need to register our application to be able to use the API. You’ll need to sign up for a developer account at http://dev.twitter.com or simply sign-in with your twitter account. Keep in mind that if you’re developing the application for a client and not for yourself, a likely story, you’ll need to register the application to their account to make use of certain API calls. For this tutorial, it should not matter.

Once you’ve setup your developer account, go to My applications.

And then click on Create a new application.

From here, you’ll be prompted with a form that requires a little bit of information about your new application. Fill as shown:

The callback URL isn’t required. The website field is necessary but it can be anything you put in there; however, it should eventually reflect the website you are embedding it on.

You will be directed to the Application Details page once you’re done creating your application. From here, you’ll be given a Consumer key and Consumer secret. These will be necessary for authenticating your application. An Access token and Access token secret are also necessary for application authentication which you can create by clicking the Create my access token button at the bottom of the page.

If the page doesn’t refresh shortly, try refreshing the page to reveal your newly created Access token information.

The four keys provided on this page, Consumer key, Consumer secret, Access token, Access token secret, will be necessary for making calls to the Twitter API.

Enough screenshots. It’s time to install the library.

Installing The Interface Library

We’ll be using a lean library for helping us make requests to the Twitter API.

Download the TwitterAPIExchange.php file and install it to lib/TwitterAPIExchange in your Magento instance.

Due to Magento’s marvelous autoloading, all you need to do now is instantiate TwitterAPIExchange as you normally would with any other class:

<?php $twitterApi = new TwitterAPIExchange($settings) ?>

Now onto the good stuff…

Writing Your Helper Class

Here is an example class for retrieving tweets from Twitter.

For the purposes of getting developers on their feet, I’m not going to delve too much into the code here.

<?php
class YourNamespace_YourModule_Helper_Twitter extends Mage_Core_Helper_Abstract
{
// DO NOT actually do this. Store these
// credentials in Magento's configuration.
const OAUTH_ACCESS_TOKEN = 'YOUR ACCESS TOKEN';
const OAUTH_ACCESS_TOKEN_SECRET = 'YOUR ACCESS TOKEN SECRET';
const CONSUMER_KEY = 'YOUR CONSUMER KEY';
const CONSUMER_SECRET = 'YOUR CONSUMER SECRET';
// some default values
const RESPONSE_LIMIT = 5;
const CACHE_LIFETIME = 3600;
public function getTweetsByUsername ($username, $limit = self::RESPONSE_LIMIT)
{
$coreHelper = Mage::helper('core');
$username = trim($username);
$limit = intval($limit);
$cacheKey = 'twitter_' . md5($username);
$cacheTags = array('twitter', $cacheKey);
$tweets = array();
if (!$username || !$limit || $limit <= 0) {
return array();
}
// try to load tweets from cache
$responseJson = $this->_loadCache($cacheKey . '_' . $limit);
if (empty($responseJson)) {
// this is where we instantiate and configure
// our API interface.
$twitter = new TwitterAPIExchange(array(
'oauth_access_token' => self::OAUTH_ACCESS_TOKEN,
'oauth_access_token_secret' => self::OAUTH_ACCESS_TOKEN_SECRET,
'consumer_key' => self::CONSUMER_KEY,
'consumer_secret' => self::CONSUMER_SECRET
));
// set our parameters for accessing user_timeline.json
// see more: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
$getParameters = array(
'screen_name=' . urlencode($username),
'count=' . urlencode($limit)
);
// this is where the request is being made
$responseJson = $twitter->setGetfield('?' . implode('&', $getParameters))
->buildOauth('https://api.twitter.com/1.1/statuses/user_timeline.json', 'GET')
->performRequest();
// save tweets to cache
$this->_saveCache($responseJson,
$cacheKey . '_' . $limit,
$cacheTags,
self::CACHE_LIFETIME);
}
// decode JSON response
$response = $coreHelper->jsonDecode($responseJson);
if (isset($response['statuses'])) {
$response = $response['statuses'];
}
if (empty($response)) {
return array();
}
return $tweets;
}
}

This will enable you to retrieve 3 (configurable, 5 by default) from an account’s twitter.

<?php $_helper = Mage::helper('YourNamespace_YourModule/Twitter') ?>
<ul>
<?php foreach ($_helper->getTweetsByUsername('demacmedia', 3) as $tweet): ?>
<li><?php echo $tweet['text'] ?></li>
<?php endforeach ?>
</ul>

Yes, you are probably looking at the example class above and realizing that we’re caching the response from Twitter. There is a very good reason for this.

Twitter heavily throttles requests. The implication of this is that you should not ever make Twitter API requests on page load. Not only does Twitter not guarantee a reasonable timeframe for a response but if you make too many requests in a window of time you will be throttled and requests cannot be made for a until that window has passed.

By design, Twitter asks, and enforces, developers to cache responses. If real-time access to tweet data is necessary, they encourage you to use the streaming API instead requiring a daemon process to harvest tweets and store them in a cache or database. I will be covering this and other aspects of the API and its usages in greater detail in future releases.