Wednesday, October 13, 2010

Example using OAuth-PHP to retrieve data from Twitter API

Similar to the OAuth-PHP example for Google Contacts we can retrieve data from Twitter in a similar way. The code is based on the examples from the OAuth-PHP page.

The example describes how to integrate the OAuth authentication with PHP in Symfony, when you take the code of the action class it self it can be used in any php file.

Get a twitter consumer key and consumer secret

Before you start coding you need to get a consumer key and consumer secret that allows your application to communicate with twitter.
To do so sign up for an account at Twitter and login.
Go to the Twitter API section and select Register a new application.

Make sure the callback URL is set up properly you need it later in the php code.

In the action.class.php:

public function executeSyncWithTwitter(sfWebRequest $request)
    {
        include_once sfConfig::get('sf_lib_dir')."/oauth/OAuthStore.php";
        include_once sfConfig::get('sf_lib_dir')."/oauth/OAuthRequester.php";

        define("TWITTER_CONSUMER_KEY",  "your_consumer_secret_here");
        define("TWITTER_CONSUMER_SECRET", "your_consumer_key_here");

        define("TWITTER_OAUTH_HOST", "https://twitter.com");
        define("TWITTER_REQUEST_TOKEN_URL", "https://api.twitter.com/oauth/request_token");
        define("TWITTER_AUTHORIZE_URL", "https://twitter.com/oauth/authorize");
        define("TWITTER_ACCESS_TOKEN_URL", "https://api.twitter.com/oauth/access_token");

        define('OAUTH_TMP_DIR', function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : realpath($_ENV["TMP"]));

        //  Init the OAuthStore
        $options = array(
                'consumer_key' => TWITTER_CONSUMER_KEY,
                'consumer_secret' => TWITTER_CONSUMER_SECRET,
                'server_uri' => TWITTER_OAUTH_HOST,
                'request_token_uri' => TWITTER_REQUEST_TOKEN_URL,
                'authorize_uri' => TWITTER_AUTHORIZE_URL,
                'access_token_uri' => TWITTER_ACCESS_TOKEN_URL
        );

        // Note: do not use "Session" storage in production. Prefer a database
        // storage, such as MySQL.
        OAuthStore::instance("Session", $options);

        try
        {
                //  STEP 1:  If we do not have an OAuth token yet, go get one
                if (empty($_GET["oauth_token"]))
                {
                        $getAuthTokenParams = array('oauth_callback' => 'your_domain.com/twitter/syncWithTwitter.php');

                        // get a request token
                        $tokenResultParams = OAuthRequester::requestRequestToken(TWITTER_CONSUMER_KEY, 0, $getAuthTokenParams);

                        //  redirect to the google authorization page, they will redirect back
                        $this->redirect(TWITTER_AUTHORIZE_URL . "?oauth_token=" . $tokenResultParams['token']);
                }
                else {
                        //  STEP 2:  Get an access token
                        $oauthToken = $_GET["oauth_token"];

                        $tokenResultParams = $_GET;

                        try {
                            OAuthRequester::requestAccessToken(TWITTER_CONSUMER_KEY, $oauthToken, 0, 'POST', $_GET);

                        }
                        catch (OAuthException2 $e)
                        {
                            //if there is any error send the user back to the homepage of your app
                            $this->redirect('@home');
                        }
                }
               
                //get the users information (see below for details about the return)
                $userContainerRequest = new OAuthRequester("https://twitter.com/account/verify_credentials.xml", 'GET', $tokenResultParams);
                $userContainer = $userContainerRequest->doRequest(0);
               
                if ($userContainer['code'] == 200) {
                    $this->user = new SimpleXMLElement($userContainer['body']);
                   }
        }
        catch(OAuthException2 $e) {
            //if there is any error send the user back to the homepage of your app
            $this->redirect('@home');
        }
        return sfView::SUCCESS;
    }

In the template syncWithTwitter.php:

All possible values of the twitter user object can be seen in the Twitter docs. The values from the SimpleXMLElement can be accessed as described below:

<h3>
Show Twitter user</h3>
<?php
echo $user->id; // e.g. 12345678
echo $user->name; // e.g. Peter Parker
echo $user->screen_name; // e.g. Spiderman
?>

In the routing.yml:

syncWithTwitter:
url:    /twitter/syncWithTwitter/*.
param:  { module: twitter, action: syncWithTwitter }

0 comments:

Post a Comment