PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Oauth

Setting Up Our OAuth Consumer

In order to implement Twitter access with Zend_Oauth we're going to have three scripts facing our web application:

  1. The protected script that posts a message on Twitter
  2. A login script that begins the OAuth authentication process
  3. A callback script that Twitter redirects to after the user authorizes our application

Additionally, we are going to create a utility script that holds data and functions required in all scripts.

First though, let's create a database. For the purposes of this article, we need only a single table. This table stores access tokens. As mentioned previously, this article assumes you already have some kind of protected area on your web site, and thus some kind of account identifier that the access token will be linked against.

Listing 1 shows the twitter_auth database table. The fields needed to make a request on the Twitter API are the token and secret fields. You can adjust any other fields as required.

Listing 1 Database table to store OAuth access tokens (listing-1.sql)
create table twitter_auth (
    user_id     int             not null,
    token       varchar(255)    not null,
    secret      varchar(255)    not null
);

Now we must implement code to access this table. We'll now set up the entires globals.php file. The other scripts in this article will make use of this. We're going to use Zend_Db to communicate with the database.

Listing 2 shows the code to connect to the database with. You can substitute your own database connection details as required.

Listing 2 Connecting to OAuth access token database (listing-2.php)
<?php
    require_once('Zend/Db.php');
 
    $db = Zend_Db::factory('Pdo_Mysql', array(
        'host'     => 'localhost',
        'username' => 'zend_oauth',
        'password' => 'zend_oauth',
        'dbname'   => 'zend_oauth'
    ));
?>

When you register your Twitter application you are given a consumer key and secret that allows your application to use the platform. Since these values are needed in multiple scripts we'll now include a function to get the configuration details for Zend_Oauth. You can access these values from within your account on http://dev.twitter.com.

Listing 3 shows the configuration details that we'll make use of later in this article. The key names for the array are dictated by the Zend_Oauth_Consumer class. The consumer key and secret

Listing 3 Retrieving configuration for Zend_Oauth_Consumer (listing-3.php)
<?php
    function getAuthConfig()
    {
        require_once('Zend/Service/Twitter.php');
 
        return array(
            'callbackUrl'    => 'http://yoursite/callback.php',
            'siteUrl'        => Zend_Service_Twitter::OAUTH_BASE_URI,
            'consumerKey'    => 'Your Consumer Key',
            'consumerSecret' => 'Your Consumer Secret'
        );
    }
?>
Note: The callback URL is one of the scripts we'll create shortly. You need to specify the full URL (including domain) to this script since Twitter redirects the user back to this URL after the user has approved your application.

Next I have included a function called getUserId(), as shown in Listing 4. This is used to return the local ID of the user currently logged-in to your web application. You should update this code to reflect your own application accordingly.

Listing 4 Placeholder for retrieving ID of current user (listing-4.php)
<?php
    function getUserId()
    {
        // replace this code to suit your own application
        return 123;
    }
?>

Finally, Listing 5 shows a function to retrieve the access token and secret for the user currently logged-in (based on the ID returned from getUserId()). If no access token was found an exception is thrown. We'll use this exception later on the protected script.

Listing 5 Function to retrieve Twitter access token for current user (listing-5.php)
<?php
    function getTwitterAccessToken()
    {
        $db = $GLOBALS['db'];
        $select = $db->select();
        $select->from('twitter_auth', array('token', 'secret'))
               ->where('user_id = ?', getUserId());
 
        $row = $db->fetchRow($select);
 
        if (!is_array($row)) {
            throw new Exception('Auth details not found');
        }
 
        require_once('Zend/Oauth/Token/Access.php');
 
        $ret = new Zend_Oauth_Token_Access();
        $ret->setToken($row['token'])
            ->setTokenSecret($row['secret']);
 
        return $ret;
    }
?>

In this script we try to retrieve a row from the twitter_auth table. If a row is found we build an instance of Zend_Oauth_Token_Access. This is a utility script for Zend_Oauth that is used both when authenticating, but also when using the Twitter API.

Listing 6 shows how all of this code fits together inside globals.php. We'll make use of this script in each of the other scripts covered later in this article.

Listing 6 Global functions for web application (globals.php)
<?php
    // create the database connection so we can read/write auth details
    require_once('Zend/Db.php');
 
    $db = Zend_Db::factory('Pdo_Mysql', array(
        'host'     => 'localhost',
        'username' => 'zend_oauth',
        'password' => 'zend_oauth',
        'dbname'   => 'zend_oauth'
    ));
 
    /**
     * Get the configuration for communicating with oAuth server
     */
    function getAuthConfig()
    {
        require_once('Zend/Service/Twitter.php');
 
        return array(
            'callbackUrl'    => 'http://yoursite/callback.php',
            'siteUrl'        => Zend_Service_Twitter::OAUTH_BASE_URI,
            'consumerKey'    => 'Your Consumer Key',
            'consumerSecret' => 'Your Consumer Secret'
        );
    }
 
    /**
     * Get the ID of the current user of your web app
     */
    function getUserId()
    {
        // replace this code to suit your own application
        return 123;
    }
 
    /**
     * Get the token and secret for the current user
     *
     * @return  Zend_Oauth_Token_Access
     * @throws  Exception   If access token can't be found
     */
    function getTwitterAccessToken()
    {
        $db = $GLOBALS['db'];
        $select = $db->select();
        $select->from('twitter_auth', array('token', 'secret'))
               ->where('user_id = ?', getUserId());
 
        $row = $db->fetchRow($select);
 
        if (!is_array($row)) {
            throw new Exception('Auth details not found');
        }
 
        require_once('Zend/Oauth/Token/Access.php');
 
        $ret = new Zend_Oauth_Token_Access();
        $ret->setToken($row['token'])
            ->setTokenSecret($row['secret']);
 
        return $ret;
    }
?>

Next we'll look at the login script. This script gets a request token (whcih we must then store) and then redirects the user to Twitter so they can authenticate.

In This Article