Snipe.Net - Geeky Stuff
Twitter
Currently: @jonbergan LOL sorry - this one is for a guy I met while working with tigers. We go way back in reply to jonbergan 1 hr ago

Writing Your First Twitter Application with OAuth

If you’re interested in writing a web-based Twitter application but aren’t sure where to start, the Twitter OAuth library from Abraham Wiliams makes authenticating with OAuth and Twitter a breeze.

Please note: Use of the information in this article is conditional on the fact that you swear NOT to to make any of those goddamned Twitter games that spam Twitter timelines or send DMs like Spymaster or Quizzes. If you’re reading this to learn how to create one of those, please fuck right off. Do not pass go, do not collect $200. Those apps are the anal cancer of Twitter and the people who write them should be clubbed like baby seals.

Right then. Moving on.

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. In layman’s terms, it is a system by which you can allow a user to authenticate with an OAuth-enabled service without providing you with their credentials to that service.

In my Twitter anti-social media douchebag service, DoucheNuker.Com, we use Twitter’s OAuth to validate the user and make Twitter API requests on their behalf, specifically sending a DM to the douchebag they are nuking, another DM to @spam to report them to Twitter as a spammer, and then a block request to block the spammer’s account from being able to follow them in the future.

Why OAuth?

Using OAuth allows you to write applications that access the Twitter API but do not require your users to give you their Twitter username and password. This is important for a variety of reasons:

  • If the user changes their Twitter login, they do not have to update that information with you for your application to continue working for them
  • Using OAuth puts the user in control – if they ever wish to stop using your application, they can disable it through Twitter instead of trusting your application to stop using their login information. Once they disable it through Twitter, any requests by your application will require them to manually approve the connection again.
  • Increased sense of trust, since the user doesn’t have to worry about your application stealing their Twitter credentials and using it for nefarious purposes. I personally wouldn’t trust any web-based application that asks for my Twitter username and password, and given Twitter’s recent history of bad press regarding their security, more and more users are following that lead.

Definitions

Before I show you how to use Abraham’s shmancy library to connect to Twitter’s OAuth, you should understand the basics of how OAuth works and what it’s doing. And before we get too caught up in that, it’s important that we establish some definitions that you’ll see if you do any additional research into OAuth:

chartkey-2

User: The users of your application.
Consumer: Your application, which you have registered with Twitter
Service Provider: The third-party service the consumer (your application) is authenticating against – in this case, Twitter.

These terms are used in much of the OAuth documentation, so they’re worth remembering.

So now that you know the lingo, how does OAuth actually work? For a detailed technical view of what gets passed back and forth, check out the core spec documentation on OAuth. Included in that documentation is the detailed chart below.

diagram

As you can see, the documentation frequently uses the terms defined above.

If that flow diagram seems a little overwhelming, don’t sweat it. I have a simplified version just for you (featuring a stoner Twitter user and a Twitter bird with a Thyroid problem), specifically with respect to the bits you need to know to set up your first Twitter application with OAuth. The other things OAuth does are important, but this is the stuff that directly impacts you, and that you need to grok to get started with your app.

chart

boba_fettI was absurdly and inexplicably tempted to randomly throw a Boba Fett icon into that diagram, but was afraid it might confuse people. That said, I have poor impulse control, so here’s a random Boba Fett icon, so I can sleep tonight. As my friend Jason Ramboz says, “Step 4, Boba Fett freezes the key in carbonite for transport.”

Moving on.

Now that you’ve got a good idea of how the basics of OAuth work, you’re ready to get started with Abraham’s great Twitter OAuth library. He does provide an example script in the downloadable code, but it might be confusing for people just starting out.

Getting Started – Registering Your Application with Twitter

Before you even start mucking around in any code, you have to register your new application with Twitter. You’ll need a name and url for your application in order to register it, and you’ll need to define a callback url. The callback url is the full url of the page Twitter should send the user to after it’s done authenticating. This file can be named anything you want, but make sure the one you create on your server matches the one you register with Twitter. All of these details can be changed later if you change your mind or need to update something.

Once you’ve registered your application, Twitter will issue you a Consumer Key and a Consumer Secret for your new app. You’ll need these to get your sample code from the Twitter OAuth library working. As you can probably tell by the name, your Consumer Secret should remain private and you should never give it out to anyone. It’s used in your code so that Twitter can identify your application when you’re making API calls.

By forcing you to send your consumer key and secret with your API calls, Twitter is able to determine which application is sending the API calls, and can verify that the Twitter user you are attempting to send API requests on behalf of has actually authorized your application to access their account. If the user decides they no longer want to allow your application, they can edit their allowed application preferences and your application will no longer be able to make API calls on their behalf.

You can access a list of all of the applications you have registered with Twitter – and links to edit their details or view the consumer key and consumer secret – by going to your oauth clients page on Twitter.

The Twitter OAuth PHP Library Code

You’ve got your consumer keys from Twitter, so now you’re ready to download Abraham’s Twitter OAuth library code. You can pull the code from http://github.com/abraham/twitteroauth. As I mentioned, he does provide an example script, but there’s not a lot of explanation given to it, so some people might be a little confused by it if its their first foray into Twitter applications with OAuth. We’re going to whip up something a little more straightforward and simple, so you can easily modify it to suit your needs.

Unpack/unzip the archive you downloaded from github. You’ll see the two main files, OAuth.php and twitterOAuth.php are in the top level directory, and there is a directory called ‘example’, that has the included example script.

For our example, we’re going to put the two OAuth files into a directory called ‘twitterOAuth’, which is a sub-directory of where the index.php and callback.php files live. As you may have guessed, the callback.php file is the one we’ve registered with Twitter as being our callback url. We’ll keep common configuration options such as the consumer key and consumer secret, and database credentials in a config.php file.

/* config.php */

/* Consumer key from twitter */
$consumer_key = 'xxhjgxhjxhhjgxjhjxgjyx768678xx'; 

/* Consumer Secret from twitter */
$consumer_secret = 'jhgjdfgfgjhj76jgjgjhxxxjhxxx';

Now we create the index.php file, which will be used to generate the authentication link, inviting users to authorize and login using Twitter.

/* index.php */

session_start();

/* Destroy the session if the user is logging out */
if ((isset($_GET['logout'])) && ($_GET['logout']=='true')) {
    session_destroy();
    session_unset();
}

/* Include the config file */
require_once('config.php');

/* include the twitter OAuth library files */
require_once('twitterOAuth/twitterOAuth.php');
require_once('twitterOAuth/OAuth.php');

    /*
    Create a new TwitterOAuth object, and then
    get a request token. The request token will be used
    to build the link the user will use to authorize the
    application. 

     You should probably use a try/catch here to handle errors gracefully
    */
    $to = new TwitterOAuth($consumer_key, $consumer_secret);
    $tok = $to->getRequestToken();

    $request_link = $to->getAuthorizeURL($tok);

    /*
    Save tokens for later  - we need these on the callback page to ask for the
    access tokens
    */
    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];

echo '<p><a href="'.$request_link.'">login using twitter</a> | ';
echo '<a href="index.php?logout=true">Logout</a></p>';

The callback.php file is the script that Twitter sends the user back to after authenticating. Here you’ll probably want to set some cookies, store some user data in the database, and start letting the user do whatever it is your application does.

/* callback.php */

session_start();

/* Include the config file */
require_once('config.php');

/* include the twitter OAuth library files */
require_once('twitterOAuth/twitterOAuth.php');
require_once('twitterOAuth/OAuth.php');

/* check for an auth access token. If there's no auth token set, go ahead and fetch one from Twitter,
* using the API call. */
if ((!isset($_SESSION['oauth_access_token'])) || ($_SESSION['oauth_access_token'])=='') {

	$to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'], $_SESSION['oauth_request_token_secret']);
	$tok = $to->getAccessToken();

 	/* Save tokens for later  - might be wise to
        * store the oauth_token and secret in a database, and
        * only store the oauth_token in a cookie or session for security purposes */
	$_SESSION['oauth_access_token'] = $token = $tok['oauth_token'];
	$_SESSION['oauth_access_token_secret'] = $tok['oauth_token_secret'];

} 

/* Connect to the Twitter API */
$to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_access_token'], $_SESSION['oauth_access_token_secret']);
$content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
$user = simplexml_load_string($content);

if ($user->screen_name!='') {
	echo '<h2><img src="'.$user-/>profile_image_url.'" align="left">';
	echo 'Hello, '.$user->screen_name.'</h2>';
	echo '<p>You follow '.$user->friends_count.' people, ';
	echo 'you have '.$user->followers_count.' ';
	echo 'people following you, and you joined ';
	echo 'Twitter on '.$user->created_at.'. ';
	echo 'You have posted '.$user->statuses_count.' updates.</p>';
} else {
	echo 'Oops - an error has occurred.';
}

echo '<pre>';
print_r($user);
echo '</pre>';

So we’ve connected to Twitter’s API to authenticate a session on behalf of the user, and then put the XML response of the user’s information into an array called $user, using SimpleXML. Using SimpleXML, we can call up any node values within the XML using $user->field_name, as you can see above.

I’ve included a print_r($user) so that you can see the full details of the array being returned, but you’ll obviously want to comment that out in your live code.

The output array will contain the following fields:

SimpleXMLElement Object
(
    [id] => 14246782
    [name] => snipe
    [screen_name] => snipeyhead
    [location] => New York
    [description] => Codemonkey, designer, author, speaker, blogger, swordfighter, Warcrafter, sarcasticgeek, scuba diver, blacksmith, crimefighter, Mentat, MBTI: ENTP, Totally NSFW
    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/303658881/Photo_4-rcrop2_normal.jpg
    [url] => http://www.snipe.net
    [protected] => false
    [followers_count] => 4224
    [profile_background_color] => 340100
    [profile_text_color] => 3C3940
    [profile_link_color] => 6C2125
    [profile_sidebar_fill_color] => AEA797
    [profile_sidebar_border_color] => 943A39
    [friends_count] => 3756
    [created_at] => Fri Mar 28 20:37:35 +0000 2008
    [favourites_count] => 314
    [utc_offset] => 12600
    [time_zone] => Tehran
    [profile_background_image_url] => http://s3.amazonaws.com/twitter_production/profile_background_images/22127710/twitterback2.jpg
    [profile_background_tile] => false
    [statuses_count] => 20570
    [notifications] => false
    [verified] => false
    [following] => false
    [status] => SimpleXMLElement Object
        (
            [created_at] => Mon Jul 27 01:50:36 +0000 2009
            [id] => 2862508774
            [text] => @elazar In case a name gets blocked/banned - when its reinstated (by someone claiming it, not spamming), it has a new ID#
            [source] => Tweetie
            [truncated] => false
            [in_reply_to_status_id] => 2860170987
            [in_reply_to_user_id] => 9105122
            [favorited] => false
            [in_reply_to_screen_name] => elazar
        )

)

We’re not actually doing anything magical here yet, since that information is all available publicly via a user’s RSS feed, but the key line of code you want to look at in callback.php is this one:

$content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');

The OAuthRequest function is what actually sends the requests to the API, so you’ll be using this a lot. In the example above, all we were doing was getting the access tokens, but you’ll use OAuthRequest for just about everything else, too. For example, to send a Direct Message in Twitter, you’d use:

$params = array('user' => 'username', 'text' => 'this is a test message');
$do_dm = simplexml_load_string($to->OAuthRequest('http://twitter.com/direct_messages/new.xml', $params, 'POST'));

To block a user, you’d do:

$doblock = simplexml_load_string($to->OAuthRequest('http://twitter.com/blocks/create/username.xml', array(), 'POST'));

To send a status update:

$content = simplexml_load_string($to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => 'Test OAuth update. #testoauth'), 'POST'));

Important! Storing user IDs

Whenever you’re storing Twitter IDs in a database, be sure to store the Twitter ID number in addition to (or instead of) the Twitter username. While it may seem obvious to use a numeric value over a mixed alphanumeric, Twitter doesn’t expose user’s ID numbers without a little digging, so it might be easy to forget that they exist.

There are two main reasons why using the numeric ID is critical:

  • Users can change their Twitter usernames. If they did this, your entire database could potentially be screwed up, since username key you’re looking for won’t match any longer.
  • If an account has been suspended due to spam or imposters, it can potentially be available for registration again after a grace period. If a spammer had a username before, and then a legitimate user reclaimed it, your records could potentially have old data from the previous user’s account.

The second point above became crystal clear while working on DoucheNuker.Com. If a user account was suspended due to spamming, and then a legitimate user took it over, that new, legitimate user could potentially be considered a spammer in our database if we didn’t store (and query against) the ID number, too. When a username is reissued or reclaimed, it gets a new user ID number, so as long as you store and use the Twitter user’s ID number, your database can remain agnostic to name changes and reissues.

You’ll note in the Twitter REST API documentation that almost all API requests allow the option of using the username or the user ID, and some actually require the user ID and cannot be used with just a username.

Important! Error Messages and Throttling

You do not want to authenticate against Twitter every single time you load the page, but will instead want to store the request tokens in a database or session so that you don’t keep hammering Twitter’s API each time the page loads.

Remember that the although the Request Token you used to generate the authorization link will change often, a user’s Access Token and Access Secret Token do not, so you can safely store those in a database and use those instead of re-validating every time.

As of right now, Twitter is throttling validation requests to 15 per Twitter account per hour. This was implemented to improve Twitter’s security and make it harder for bad guys to brute force their way into someone else’s Twitter account. There is discussion about rolling this change back, or only throttling to 15 failed attempts per hour, but as of this moment, if you attempt to authenticate more than 15 times in an hour, you’ll get a message that says “Too many requests in this time period. Try again later.” There is no way around this message for now, so plan your application accordingly.

This limit is entirely separate from the Twitter Rate Limit that throttles the number of times you can hit the API. Whitelisting your account and IP address with Twitter will NOT circumvent this rate limit, so make sure you design your app in a smart way that will not attempt to authenticate more than absolutely necessary.

The default rate limit for calls to the REST API is 150 requests per hour. The REST API does account- and IP-based rate limiting. Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment.

You’ll notice in all of API requests, we’re using SimpleXML to capture the value of the XML that’s returned. We need to do this in order to make sure we’re capturing any error messages that Twitter returns to us. Without error messages, when stuff doesn’t work as expected, we’re flying completely blind. Always make sure to plan your application in a way that handles errors intelligently. Let’s take a look at the API call to send a Direct Message again:

$params = array('user' => 'username', 'text' => 'this is a test message');
$do_dm = simplexml_load_string($to->OAuthRequest('http://twitter.com/direct_messages/new.xml', $params, 'POST'));

/* Check for an error response from Twitter */
if ($do_dm->error!='') {
	echo '<h2>ERROR: '.$do_dm->error.'</h2>';
}

Now we’re capturing the error returned from Twitter, and can handle this appropriately with our users. The error might be indicating that the user cannot send a Direct Message to someone they’re not following. Or there might be something else amiss – so you’ll want to make provisions in your script to help the user understand why something might not be working.

And that’s honestly all there is to it. Now that you’ve got the OAuthRequest function sussed, you just need to check with the Twitter API Wiki to determine the correct urls and parameters to send, based on what you’re trying to do.

I have to say, having worked with a LOT of APIs, including Facebook, Amazon, and at least a half-dozen others, Twitter’s API is actually the most well-documented and simplest to use. Surprising, really, since Facebook and Amazon have actual business models, so you’d think they’d invest just an iota of time into documenting their shit. I’ve gone into long tirades here on my blog about how miserably awful the Facebook API documentation is, and Amazon’s API is probably 10x worse. Twitter’s API is, overall, pretty accurate and up to date. If its your first foray into writing an application with an API, I think Twitter is actually a good place to start – before you graduate to Facebook and wish you were dead.

Recap – Important Links

And that’s all there is to it. Please use your new powers for good and not evil. No annoying games, no “increase your followers” services, etc. If you have any questions, leave ‘em in the comments.

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!) My entire concept of self-worth is in your hands, so that makes you kind of a big deal. Srsly.

Also check out:  

This entry was posted on Thursday, July 23rd, 2009 at 6:26 pm and is filed under Featured, PHP/mySQL, Web Development. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
  • Pete
    helpful article, thanks, but

    you gotta fix this line:
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
    should be:
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', GET, array());

    time is precious
    thanks
  • Pete - that's been posted in the comments several times now. If time is precious, you might have checked there first ;)
  • neocambell
    Wonderful. This is the best artcile I found about oAuth for twitter. Thanks a lot.
  • peterson
    Figured out the logout issue - you have to change your code in index.php (line 29 in your snippet) to:

    $request_link = $to->getAuthorizeURL($tok, !isset($_SESSION['oauth_access_token']));

    The second parameter is what determines if the user has logged out or still has the access token in the session - otherwise clearing the session does nothing since the second parameter in getAuthorize URL is TRUE by default. This might be helpful for others.
  • Are you using the new OAuth library or the old one? This code hasn't ben updated for Abraham's most recent library release.
  • peterson
    Thanks for the tutorial, this is really helping me get things started.

    one problem though, the Logout link is not working. when I logout, then click login again it bypasses the login screen and shows callback.php again with my previous login info. any ideas? Is session_destroy() and session_unset() all that is required to logout?
  • lucarocchi
    it seems that params order in your code snippet is swapped

    $to->OAuthRequest('https://twitter.com/statuses/update.xml', array('status' => 'Test OAuth update. #testoauth'), 'POST')

    while twitteroauth.php states
    function oAuthRequest($url, $method, $parameters) {

    Thx for the great tutorial
  • This tutorial is based on an earlier version of the library.
  • lucarocchi
    thx now it is even more clear ... i just realize that similar message was posted more than once before
  • Line 29 in callback.php needs to be
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
    instead of
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');

    The latter will give you the following error "Argument #2 is not an array in OAuth.php on line 249"
  • Hi Gaurav - yep, several people have posted that in the comments already - haven't had a chance to update the post to match Abraham's most recent version.
  • Kewl App
  • Not even using PHP and this article was very helpful! Thanks!
  • davehenderson1234
    Hi There,

    I have followed your tutorial, however when I am being redirected back to my site I am getting the following error:

    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home/ixelscom/public_html/twitterauth/twitterOAuth/OAuth.php on line 249
    Oops - an error has occurred.

    Anyone had this issue before?

    Thanks
    David
  • The solution to this was posted in the comments.
  • @snipe: Awesome awesome awesome tutorial. Keep the good work going.
    Can you please tell me the code for displaying the tweets of ppl whom i follow, like the twitter home. How can i do it?
  • Adnan
    Hi Snipe,
    Nice code just wanted tell you it may be a change Abraham’s Twitter OAuth library because I was having problem running the code. After debugging, the problem was in this call

    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');

    it should be like this

    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
  • I think a few people noted the change in earlier comments - but thanks! I haven't had a chance to update the article yet.
  • Hi, is there someone who can build an oauth application at a fairly low or reasonable price? Thinking of starting a business that uses the application.
  • Thanks for the awesome right up!

    I'm having some trouble with just displaying the screen name of the verified account. I'm at a complete loss.

    Any help would be great!
  • H James - check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first...

    Let me know if that helps :)
  • Marc
    So, I ended up grabbing the oauth files from the link hosted on your site, and its working. Obviously theres been an update to the github files which is breaking this.
  • Hi Marc - check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first...
  • Marc
    Thanks for this great tutorial, however, I am getting this error:

    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /home/xmasdev/releases/xmas-head/twit/OAuth.php on line 249

    and I am following this to a tee.
    Anyone have any suggestions?
  • Hello, this is great i'm using it for my project. I have some problem, how to make "Logout"? In index.php i have Logout and the clearsessions.php is like this http://pastie.org/738286 Can you help me please
  • Hi Viktor - Sorry for the delay - are you still having this problem?
  • Yes snipe, can you help me please. Thanks
  • Please try turning on all error reporting to display any and all errors that might be triggered

    At the top of your script, type:

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors',1);
    ?>

    Try logging in and logging out again, and then tell me if you see any errors output.
  • can you give me your e-mail adress to send you some files to check, no errors
  • It's New Years Eve, so cannot promise to be able to find a solution for you tonight, but my email address is available on this page: http://www.snipe.net/hire-me/
  • Luke
    I'm having trouble getting this to work, I think I'm having an issue with the Twitter OAuth Library - I get the following error when coming back to the callback page from authentication:

    Fatal error: Cannot unset string offsets in .../public_html/twitterOAuth/twitterOAuth.php on line 145

    Just wondered if anybody has any ideas. I'm new to PHP.
  • Luke, did you get this resolved? I'm having the same issue and haven't found a solution.
  • Nice article...
  • Thanks for putting the time into this article! I like the camaraderie.

    -Steve
  • This is by far the *best* post I've seen on this subject. THANK YOU! :-)

    - Greg J
  • Figures I'd find this after trudging my way through Abraham's example, but your post definitely provided a little more clarity on things. However, I think I'm looking for confirmation on the same thing kaeo is: creating a new instance of TwitterOAuth() with the saved access token pair once you've authorized a user does NOT affect the login limit, correct?
  • Bob I
    Tried again this AM and got the 'could not authenticate' return again. I also tried the example index file that comes with Abraham's download. Same result. I've tried a couple different Twitter profiles and that's no help. When I check the authorized connections for those profiles, my application does not show up. In fact, when I login to those profiles via Twitter after one of my failed attempts, I get a whoa nellie error from Twitter: "This page requires some information that was not provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake." (Then that page disappears if I hit back or cancel and it logs in normally.) So obviously when my application is sending the request, some crucial bit of info isn't getting included somehow. Again, thanks for you help on this!
  • ninjacipher
    I know I'm a bit late to the party, but I was having the same 'could not authenticate' issue. Turns out that (at least in my case) this was due to the fact I was using the 0.2.0-beta2 version of twitteroauth. I swapped it out with the 0.1.1 download and everything works as it should. So for anyone that is reading this and having the same issue give that a shot. :)

    Also thx a bunch for the writeup snipe. Very clear and helpful and well written.
  • Thank you for the follow-up, ninja :) Abraham had mentioned there was a new version of the library out, and I have yet to update this tutorial, so I'm sure a lot of people are grateful for your post :)
  • Twitter has been up and down for a few hours. Might want to give it until tomorrow. Happens sometimes.
  • Bob I.
    Great tutorial. Thanks for putting this together. I've got my secret keys in a config file and index & callback pages set up. The login request gets submitted, but I'm getting an error I can't figure out. Login won't authenticate. Any suggestions? Is there something wrong with the way the request is being assembled? The XML object returned is this:

    SimpleXMLElement Object
    (
    [request] => /account/verify_credentials.xml?oauth_version=1.0&oauth_nonce=xxx283ba189a49dc19e773b9c64xxxxx&oauth_timestamp=1252468457&oauth_consumer_key=xxxMMDtVZdwnqIyTUxxxx&oauth_signature_method=HMAC-SHA1&oauth_signature=xxxZ%2FKvvuMZOw65jha49gLExxxx%3D
    [error] => Could not authenticate you.
    )
  • Mosiur Rahman Khan
    This is a great tutorial. It worked perfect to me.

    Thanks a lot.
  • Great tutorial, but when ever I try to test it it show this error:
    Fatal error: Cannot redeclare class OAuthException in /home/twtz7ma/public_html/twitterOAuth/OAuth.php on line 8
  • kaeo
    Love your work, and your tweets!

    I just successfully used your code (copied, pasted, and understood) to connect, authorize, and display my twitter account info from my application site. Now, a question:

    I understand that there is the need to use (and store) the access token and access token secret to to avoid hammering the twitter API. But what I'm not completely 100% sure about is if the code above is using only the access token and access token secret to request data from the twitter API, instead of authenticating over and over (or hammering the API). Just wanna make sure.

    Smaller version of my question: can I sit on callback.php at my site and hit refresh as many times as I want without being locked out??

    Thanks a ton!
  • dave
    hi again - did you receive the email I sent you over the weekend in regards to possibly hiring you to make one of these apps?
  • @Ram - the Twitter OAuth documentation has all of the requests documented.http://apiwiki.twitter.com/Twitter-API-Documentation
  • @Mauro - sorry for the delay - yes, please feel free.
  • Hi Dave - Looks like Github is having an issue - I'm running into the same thing. I zipped up the files from my hard drive and posted them here - snipe.net/wp-content/uploads/abraham-twitteroauth.zip

    I can't promise they haven't been altered, since I wasn't expecting to distribute them, so keep trying at Github, but this should at least get you started.
  • dave
    Dude your awesome for making this post thank you - I'm stuck on downloading the twitteroauth files all I see is this box "Hardcore Archiving Action" and it never finishes - is that normal?
  • Great post! Can I translate in italian and post on my blog? (with you reference!)
  • you wrote definitely awesome article. very well and easy to understand.

    thanks
    .-= Mahmud Ahsan´s last blog ..please vote my application =-.
  • Thanks for writing this, it helped me out with integrating OAuth in my site. Cuz i didn't like that fact that it store passwords. http://boostfollowers.com Thanks once again.
  • Ram
    Thanks for the detailed info.

    Can you also please provide a list of HTTP requests for using OAuth with Twitter

    For example the first request may be => HTTP GET request with consumer_key and consumer_secret as query string parameters (or HTTP headers ?). Another HTTP message would be from Twitter with the oauth_token etc.

    Seeing a list of these HTTP requests (in sequence) will be very helpful for experienced devs who know how to make a request, save the token in a db etc, but don't know twitter oauth.
  • Emil Sinclair
    Thanks a lot for this documentation. I'm plannig to develop my own Twitter-App, but i've got a hard time since I learned PHP for myself, so it's finest trial & error and i will need months for this. But I'm happy that people like you share there knowledge for people like me to rely on.
  • Umair Jabbar
    what kind if error would I get if #twitter #oauth accesstoken as expired, of a user for my app ?
  • Umair Jabbar
    as far as i have learned u cant store the oauth token and token secret, u need to get a new one everytime for each url
  • Char
    I figured it out.
  • Char
    How would I go about storing the oauth_token and token secret into a mysql database? Also after it is stored what code would I need embedded so that my user doesn't have to keep getting redirected to twitter when using my site.
  • Umair Jabbar
    Hey Alison, how are you,
    I was just wondering about the request token
    can I save it in my database for further access?
    can it be same for everyuser ?
    and whats the best practice ?
  • good to see people other than me are also getting helped :)
  • LILI
    Great Thanks for your help!
  • Lili - when you're returning a multi-dimensional array with more than one value, you have to loop through the results. If you don't, you'll only get results for the first array value.

    http://pastebin.com/f6c11bdec
  • LILI
    Hello Snipe, I am having a similar problem to the one that Jorge reported. I am trying to list all past tweets using the user_timeline.xml but I am getting only the last tweet.

    This is my code, the return line is what I am confused about. I am not sure what to put there.

    $content = $to->OAuthRequest('http://twitter.com/statuses/user_timeline.xml?', array('screen_name'=>"$user->profile_twitterusername"), 'GET');
    $usert= simplexml_load_string($content);
    return $usert->status->text;
  • Jorge
    You are awesome!!! Thank you very much! That did it.
  • http://pastebin.com/m3ef53500 The changes are highlighted. You have to concatenate properly and you cannot have opening and closing php tags *within* a PHP variable string value
  • Jorge
    Hi, I tried removing the tags and placing in different places as per your comments and it did not work. Could you be so kind to perhaps show me in the what to remove or where to place that line in order to make it work? Thanks
  • See my HTML comments here for clarity: http://pastebin.com/d148b3c80
  • The problem is not with the braces - the problem is that you have opening php tags inside an existing php block.

    http://pastebin.com/m42276c89
  • Jorge
    It says is on line 216. Which is this line of code:
    echo "Your last tweet was {$user->status->text}";
  • what line number is the parse error on in your error message? I already see an unrelated syntax problem
  • Jorge
    Yeah I tried both ways and this is the error I get, "Parse error: syntax error, unexpected T_STRING "
  • Did you copy and paste what I wrote exactly? The quotes are showing up as curly quotes (or "smart quotes") in pastebin, probably because Wordpress converts quotes into smart quotes automatically. Try manually re-typing the quotation marks around that line.
  • Jorge
    BTW, the segment of code is all the way at the bottom.
  • Jorge
    Thank you so much you are the best! I have to say I'm using the code to work in a module in Drupal. I'm using PHP version 5. Here's the link:

    http://pastebin.com/m16bf1ce0

    Thanks a bunch!
  • Hi Jorge - can you paste the segment of your code into pastebin.com? I think Wordpress is breaking it. Also, what version of PHP are you using?
  • Jorge
    Thank you so much for your fast reply. The line of code you gave me works great within the php function, but I'm trying to embed that piece of code in an html section and is giving me an error. I was able to call the other attributes but when I try to retrieve this information it gives me an error. Any suggestions?


    //this is how I'm putting the code within the html, it doesn't seem to like the double quotes and brackets

    status->text}"; ?>

    //this doesn't give me any problem
    screen_name.''; ?>

    Thank you for your help
  • Jorge - btw, ignore the line breaks in the echo statement above - wordpress added them. Should be all on one line, enclosed in double - not single - quotes.
  • Hi Jorge - you would use:

    echo "

    Your last tweet was {$user->status->text}

    ";

    The braces are important - won't work if you leave them out.

    To show more than one recent status update by a user, see the Twitter API documentation:
    http://apiwiki.twitter.com/Twitter-REST-API-Met...

    You can also bypass the API altogether as long as the user's timeline isn't protected, by just getting their Twitter ID (numeric) using the API, and then pulling their RSS feed. For example, mine is:
    http://twitter.com/statuses/user_timeline/14246...

    Because my Twitter ID is 14246782.

    Remember that using the rss method won't work if a user's timeline is protected though - you'll have to use the API to grab those and display them to the authenticating user in those cases.
  • Jorge
    Awesome tutorial! I'm new at this I have a couple of questions, how can I just post the tweets without the additional information? I tried "echo 'Tweets'.$user->status.'. ';" I know it has a 'status' has a second part called 'text' that's where the msg is, but I cannot get it to work. And how would I post all the tweets? Thank you for your help.
  • thankyou i am gona try firebugging the site
blog comments powered by Disqus