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

Posting a Message to Twitter

The final script we must implement in our OAuth example is the protected script. I've referred to this as index.php previously in this article.

If a user has already authenticated with Twitter they will be displayed a form with which they can post a message to their Twitter timeline. If they're not authenticated they will be redirected to the login.php script (which in turn will begin the OAuth authentication process).

Earlier in this article we created a function called getTwitterAccessToken. This function returns an instance of Zend_Oauth_Token_Access if the user has authenticated with Twitter. If the user has not authenticated an exception is thrown. Therefore we can use this exception to determine whether or not to begin the login process.

Listing 13 demonstrates the basic algorithm for achieving this. We'll add more code to this shortly.

Listing 13 Retrieving the current access token (listing-13.php)
<?php
    require_once('globals.php');
 
    try {
        $token = getTwitterAccessToken();
 
    }
    catch (Exception $ex) {
        // no auth details found, begin authentication process
        header('Location: login.php');
        exit;
    }
?>

Next we use the Zend_Service_Twitter class to post a message to Twitter. If you're using an API call that does not require authentication, you can instantiate this class then make the API call. However, since our example will post a message to a user's timeline we must be authenticated.

Since we've now authenticated with the Twitter OAuth server we must include details of the access token. The Zend_Service_Twitter class uses Zend_Http_Client to perform its API calls, which is fortunate, since Zend_Oauth_Token_Access has a method getHttpClient() method which returns an instance of Zend_Http_Client with the relevant OAuth headers automatically set.

An important thing to realize with this is that when making an API call using OAuth, you must include your consumer key in addition to the access key. We can therefore pass the Zend_Oauth_Consumer options returned by our getAuthConfig() method to getHttpClient().

Listing 14 demonstrates how to set up Zend_Service_Twitter. We'll plug this in to the index.php script shortly.

Listing 14 Setting up the Zend_Service_Twitter object with OAuth headers (listing-14.php)
<?php
    require_once('Zend/Service/Twitter.php');
 
    $twitter = new Zend_Service_Twitter();
    $twitter->setLocalHttpClient(
        $token->getHttpClient(getAuthConfig())
    );
?>

Finally, we make the Twitter API call to post a message to our timeline. We'll submit this message using post (meaning we access the message from $_POST['message'] - we'll add the form to submit this value shortly).

Without getting to far into the details of Zend_Service_Twitter, we call $twitter->status->update($message) to post a message.

Listing 15 shows this in more detail. It assumes we've already retrieved the access token using getTwitterAccessToken().

Listing 15 Posting a status update to Twitter (listing-15.php)
<?php
    if (array_key_exists('message', $_POST)) {
        $message = $_POST['message'];
 
        require_once('Zend/Service/Twitter.php');
 
        $twitter = new Zend_Service_Twitter();
        $twitter->setLocalHttpClient(
            $token->getHttpClient(getAuthConfig())
        );
 
        $response = $twitter->status->update($message);
    }
?>

To complete this script, let's piece the previous code together. Listing 16 shows the full index.php script. In addition to what's already been covered in this section it also includes a form with which to submit a status update. I've also included a var_dump() of the response from posting a status update.

Listing 16 The complete script to post a Twitter status update (listing-16.php)
<?php
    // this page can be accessed if auth details are stored.
    // if they're not, try to authenticate the user
 
    require_once('globals.php');
 
    try {
        $token = getTwitterAccessToken();
 
        if (array_key_exists('message', $_POST)) {
            $message = $_POST['message'];
 
            require_once('Zend/Service/Twitter.php');
 
            $twitter = new Zend_Service_Twitter();
            $twitter->setLocalHttpClient(
                $token->getHttpClient(getAuthConfig())
            );
 
            $response = $twitter->status->update($message);
        }
 
    }
    catch (Exception $ex) {
        // no auth details found, begin authentication process
 
        header('Location: login.php');
        exit;
    }
?>
<html>
    <head>
        <title>PhpRiot: Zend_Oauth</title>
    </head>
    <body>
        <div>
            <h1>PhpRiot: Zend_Oauth</h1>
 
            <form method="post" action="./">
                <div>
                    <input type="text" name="message" />
                    <input type="submit" value="Submit" />
                </div>
            </form>
 
            <?php if (isset($response)) { var_dump($response); } ?>
        </div>
    </body>
</html>

Now we have a functioning OAuth implementation for Twitter. You can now easily build on the API calls to provide more functionality, both to protected and unprotected API calls.

In This Article