Snipe.Net Geeky, sweary things.

Writing Your First Twitter Application with OAuth

W

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.

[box type=”warning”]This article was written in July 2009, so some of the APIs and libraries mentioned here may no longer be available or may be invalid.[/box]

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.

/* 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.

[sourcecode language=”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 ‘

login using twitter | ‘;
echo ‘Logout

‘;
[/sourcecode]

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.

[sourcecode language=’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 ‘

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:

[source lang=’html’]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
)

)[/sourcecode]

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:

[source lang=’php’]$content = $to->OAuthRequest(‘https://twitter.com/account/verify_credentials.xml’, array(), ‘GET’);[/source]

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:

[source lang=’php’] $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’));[/source]

To block a user, you’d do:

[source lang=’php’]$doblock = simplexml_load_string($to->OAuthRequest(‘http://twitter.com/blocks/create/username.xml’, array(), ‘POST’));[/source]

To send a status update:
[source lang=’php’]$content = simplexml_load_string($to->OAuthRequest(‘https://twitter.com/statuses/update.xml’, array(‘status’ => ‘Test OAuth update. #testoauth’), ‘POST’));[/source]

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:

[source lang=’php’]$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 ‘

ERROR: ‘.$do_dm->error.’

‘;
}[/source]

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.

About the author

snipe

Iโ€™m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead or read more

  • the code works perfect, thank you alison
    hey is there anyway we can do this authentication via ajax and the user need
    not to go away from my page.
    i saw tweetizen implemented it this way but I am not sure how to do this :s

  • the code works perfect, thank you alison
    hey is there anyway we can do this authentication via ajax and the user need
    not to go away from my page.
    i saw tweetizen implemented it this way but I am not sure how to do this :s

  • Hi Umair – looks like they’re just opening a new window to do the actual OAuth allow part, which still requires the same number of clicks as doing it normally, so I don’t know that there’s a big advantage to doing it this way.

  • Hi Umair – looks like they’re just opening a new window to do the actual OAuth allow part, which still requires the same number of clicks as doing it normally, so I don’t know that there’s a big advantage to doing it this way.

  • alison, number of clicks isnt a big issue for me, I cant let a user get redirected to a twitter page, as in normal flow the user gets redirected to twitter and the IFF he allows the twitter app, otherwise he will not be redirected back to the original app page.
    secondly and importantly i cant let the user leave my page just to authenticate twitter. That will break the original flow of the app.
    It would have been great of there was something like facebook connect which as far as i know opens up another window and according to my understanding would call a function of JS function on the same page from where it was called, after the user allows or denies the app

    hope the comment wasnt long enough ๐Ÿ™‚

  • alison, number of clicks isnt a big issue for me, I cant let a user get redirected to a twitter page, as in normal flow the user gets redirected to twitter and the IFF he allows the twitter app, otherwise he will not be redirected back to the original app page.
    secondly and importantly i cant let the user leave my page just to authenticate twitter. That will break the original flow of the app.
    It would have been great of there was something like facebook connect which as far as i know opens up another window and according to my understanding would call a function of JS function on the same page from where it was called, after the user allows or denies the app

    hope the comment wasnt long enough ๐Ÿ™‚

  • Not sure I know what you mean by ‘the normal flow of the application’ – if the user hasn’t authenticated, there isn’t any flow to the application yet. Your only option would be to redesign the flow of your application, or the way they’re doing it, by calling a popup/modal window and then using ajax to switch the contents of the div once the user has authenticated. Ajax isn’t really my thing tho, so I can’t help you mush there.

  • Not sure I know what you mean by ‘the normal flow of the application’ – if the user hasn’t authenticated, there isn’t any flow to the application yet. Your only option would be to redesign the flow of your application, or the way they’re doing it, by calling a popup/modal window and then using ajax to switch the contents of the div once the user has authenticated. Ajax isn’t really my thing tho, so I can’t help you mush there.

  • Hey thanks alison,
    I m trying to figure out something, the real problem is that they need a callback URL and will only send request to that URL
    which for ajax i will need something which gives me a response to a JS function on the same page

  • Hey thanks alison,
    I m trying to figure out something, the real problem is that they need a callback URL and will only send request to that URL
    which for ajax i will need something which gives me a response to a JS function on the same page

  • Probably easiest just to look at the code tweetizen is using

  • Probably easiest just to look at the code tweetizen is using

  • how can I get their code alison
    is there a way ?

  • how can I get their code alison
    is there a way ?

  • Uhm – view > source ? Ajax is client-side, not server side, so just view the source of their site (and whatever external javascript/CSS files they’re pulling in.)

  • Uhm – view > source ? Ajax is client-side, not server side, so just view the source of their site (and whatever external javascript/CSS files they’re pulling in.)

  • thankyou i am gona try firebugging the site

  • thankyou i am gona try firebugging the site

  • 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.

  • 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.

  • 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-Method%3A-statuses-user_timeline?SearchFor=status&sp;=4

    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/14246782.rss

    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.

  • 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-Method%3A-statuses-user_timeline?SearchFor=status&sp=4

    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/14246782.rss

    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 – 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.

  • 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.

  • 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

    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

  • 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?

  • 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 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!

  • 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!

  • Jorge

    BTW, the segment of code is all the way at the bottom.

  • Jorge

    BTW, the segment of code is all the way at the bottom.

  • 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.

  • 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

    Yeah I tried both ways and this is the error I get, “Parse error: syntax error, unexpected T_STRING “

  • Jorge

    Yeah I tried both ways and this is the error I get, “Parse error: syntax error, unexpected T_STRING “

  • what line number is the parse error on in your error message? I already see an unrelated syntax problem

  • what line number is the parse error on in your error message? I already see an unrelated syntax problem

  • Jorge

    It says is on line 216. Which is this line of code:
    echo “Your last tweet was {$user->status->text}”;

  • Jorge

    It says is on line 216. Which is this line of code:
    echo “Your last tweet was {$user->status->text}”;

  • 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

  • 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

  • See my HTML comments here for clarity: http://pastebin.com/d148b3c80

  • See my HTML comments here for clarity: http://pastebin.com/d148b3c80

  • 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

  • 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

  • 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

  • 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

    You are awesome!!! Thank you very much! That did it.

  • Jorge

    You are awesome!!! Thank you very much! That did it.

  • 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;

  • 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;

  • 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 – 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

    Great Thanks for your help!

  • LILI

    Great Thanks for your help!

  • good to see people other than me are also getting helped ๐Ÿ™‚

  • good to see people other than me are also getting helped ๐Ÿ™‚

  • 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 ?

  • 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 ?

  • 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.

  • 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.

  • Char

    I figured it out.

  • Char

    I figured it out.

  • 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

  • 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

  • Umair Jabbar

    what kind if error would I get if #twitter #oauth accesstoken as expired, of a user for my app ?

  • Umair Jabbar

    what kind if error would I get if #twitter #oauth accesstoken as expired, of a user for my app ?

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • you wrote definitely awesome article. very well and easy to understand.

    thanks
    .-= Mahmud Ahsan´s last blog ..please vote my application =-.

  • you wrote definitely awesome article. very well and easy to understand.

    thanks
    .-= Mahmud Ahsan´s last blog ..please vote my application =-.

  • Great post! Can I translate in italian and post on my blog? (with you reference!)

  • Great post! Can I translate in italian and post on my blog? (with you reference!)

  • 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?

  • 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?

  • 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.

  • 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.

  • @Mauro – sorry for the delay – yes, please feel free.

  • @Mauro – sorry for the delay – yes, please feel free.

  • @Ram – the Twitter OAuth documentation has all of the requests documented.http://apiwiki.twitter.com/Twitter-API-Documentation

  • @Ram – the Twitter OAuth documentation has all of the requests documented.http://apiwiki.twitter.com/Twitter-API-Documentation

  • 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?

  • 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?

  • 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!

  • 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!

  • Pingback: Quick and Dirty Twitter4j OAuth for Web Apps « From the left flank()

  • Pingback: My Quick and Dirty Twitter4j OAuth for Web Apps « Research Log of Web Science Students()

  • 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

  • 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

  • Mosiur Rahman Khan

    This is a great tutorial. It worked perfect to me.

    Thanks a lot.

  • Mosiur Rahman Khan

    This is a great tutorial. It worked perfect to me.

    Thanks a lot.

  • 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.
    )

    • Lalit

      Hey nice article but it just showing me an error… plz help me out…
      A PHP Error was encounteredSeverity: WarningMessage: array_merge() [function.array-merge]: Argument #2 is not an arrayFilename: twitteroauth/OAuth.phpLine Number: 301
      A PHP Error was encounteredSeverity: NoticeMessage: Array to string conversionFilename: twitteroauth/OAuth.phpLine Number: 373
      SimpleXMLElement Object ( [error] => Could not authenticate you. [request] => /account/verify_credentials.xml )

      Thanks in advance .. its too much ugrent

  • 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.
    )

  • Twitter has been up and down for a few hours. Might want to give it until tomorrow. Happens sometimes.

  • Twitter has been up and down for a few hours. Might want to give it until tomorrow. Happens sometimes.

  • 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!

  • 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!

  • 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?

  • Mike Branski

    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?

  • This is by far the *best* post I’ve seen on this subject. THANK YOU! ๐Ÿ™‚

    – Greg J

    • Priya

      abraham has explained better than you!
      dont try to take credit with single page

      • Abraham is a friend of mine, and he has known about this post since I created it. I don’t attempt to take credit for anything. There is room in this world for multiple approaches to explaining complicated things and my approach was quite different than his. Frankly, I’m not sure why you’re so butt-hurt over it. Abraham wasn’t.

  • This is by far the *best* post I’ve seen on this subject. THANK YOU! ๐Ÿ™‚

    – Greg J

  • Thanks for putting the time into this article! I like the camaraderie.

    -Steve

  • Pingback: LMP’s Twitter Hash Bot | LMP Blog()

  • Nice article…

  • Pingback: Tutorial: Java based Twitter App on Google App Engine()

  • 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.

  • 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

  • Pingback: Social Media Development » Twitter, Twitter4J und OAuth()

  • Luke, did you get this resolved? I'm having the same issue and haven't found a solution.

  • 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?

  • 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.

  • 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!

  • 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 ๐Ÿ™‚

  • H James – check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first

    Let me know if that helps ๐Ÿ™‚

  • Hi Marc – check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first

  • 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/

  • 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 ๐Ÿ™‚

  • H James – check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first

    Let me know if that helps ๐Ÿ™‚

  • Hi Marc – check out this comment by ninja:
    http://www.snipe.net/2009/07/writing-your-first

  • 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/

  • 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.

  • 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&#39;, array(), 'GET');

    it should be like this

    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml&#39;, '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.

  • Pingback: pligg.com()

  • 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?

  • Not even using PHP and this article was very helpful! Thanks!

  • Kewl App

  • Line 29 in callback.php needs to be
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml&#39;, 'GET', array());
    instead of
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml&#39;, 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.

  • Pingback: adoption curve dot net » Blog Archive » links for 2010-01-27()

  • lucarocchi

    it seems that params order in your code snippet is swapped

    $to->OAuthRequest('https://twitter.com/statuses/update.xml&#39;, 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

  • 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?

  • 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.

  • neocambell

    Wonderful. This is the best artcile I found about oAuth for twitter. Thanks a lot.

  • Pete

    helpful article, thanks, but

    you gotta fix this line:
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml&#39;, array(), 'GET');
    should be:
    $content = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml&#39;, 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 ๐Ÿ˜‰

  • Pingback: Twitter-Applikationen mit Zend_Oauth | PHP Gangsta - Der PHP Blog()

  • echo '

    <img src=”'.$user-/>profile_image_url.'” align=”left”>';
    echo '

    <img src=”'.$user->profile_image_url.'” align=”left”>'; I think, no need for a slash…

    Thanks for the article

  • Ahh yeah, thanks – WordPress tends to mangle code, so I'm sure that got stuck in there somehow that way. Thanks for the heads up ๐Ÿ™‚

  • Thank you so much for this tutorial. Really helped.

  • ultramagnus

    Hi,

    I've only been working with php for about 2 years and still learning. I'm testing outah everything and ran into some trouble. I went through all the setup steps and tried each version from the library but still can't get it to do exactly what I want, even though it should be easy.

    Here are my questions:

    To use “send a Direct Message in Twitter” $params = array('user' => 'username', 'text' => 'this is a test message');$do_dm = simplexml_load_string($to->OAuthRequest('http://twitter.com/direct_messages/new.xml&#39;, $params, 'POST'));

    Which file and what line would I add it. I tried a few different ways but would get an OAuthRequest error.

    And same thing for “To send a status update” $content = simplexml_load_string($to->OAuthRequest('https://twitter.com/statuses/update.xml&#39;, array('status' => 'Test OAuth update. #testoauth'), 'POST'));

    Which file and line would I use it?

    I've spent two days on it and “almost” had it, but now Twitter is not accepting my connection…not sure if I did something or it's on their end.

    Also does anyone have a working example or the files they used that actually works. I know looking at that request almost sounds like just give me your work, but just some help or suggestions, then I'll try again to make it work.

    Thanks.

  • ultramagnus

    Hi Everyone,

    I found it in version 0.2.0 as part of /* Some example calls */ Funny I tried it before and it didn't work, but now it does.

    This site has been THE BEST reference for this project.

    Thank You

  • James

    echo '

    <img src=”'.$user-/>profile_image_url.'” align=”left”>';
    I think ur this above LINE will Like

    echo '

    <img src=”'.$user->profile_image_url.'” align=”left”>';

  • Hi James, this has already been covered extensively in the comments.

  • It's not working for me. Token is not generating at index.php file. Help me.

  • Thanks a bunch! It helped me out.

  • Hi this is from snipet.net

  • ? Not sure what you're trying to say?

  • Chris

    How do I test this on localhost? I can get the request_link. but how do i do verify_credentials on localhost?

    Do I need an online web server to test this?

  • mattw1

    This post is awesome– thanks so much. One thing you may want to note is that the beta versions of Abrahams OAuth lib don't really work. Best to stick to 0.1.1 for now.

  • mattw1

    So low is reasonable? You get what you pay for.

  • +1 ๐Ÿ˜€

  • Yeah, this tutorial is outdated – I haven't had time to update it. I will, one of these day, I promise.

  • pawan

    where i find oauth provider code web services

  • Luis

    Hello…
    I'm trying this library and looks really cool… I have some stuff working.
    I have a noob question: How can we do a call to Twitter without authenticated before?
    For example, imagine that when I enter my application I want to show the last 5 PUBLIC tweets. For that I need to do a call to Twitter but I don't need to be authenticated.

    I looked at http method in TwitterOAuth class and maybe I can do something like:

    $content = json_decode($connection->http('https://api.twitter.com/1/statuses/public_timeline.json&#39;, 'GET'));

    But my doubt is, how should I create the $connection element? I tried like:

    $connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET);

    But nothing. Can you help me?

  • Pingback: Creating a Simple Twitter App using oAuth and PHP()

  • Thepackman22

    Hey I am getting an error on the profile image line saying unexpected /. Tried everything some please help.

  • Pingback: Creating a Simple Twitter App using oAuth and PHP | CG Stream()

  • ArnB

    Thanks so much – Im going to take a deep breath and have a go..

  • Pingback: Nerd Vittles » TweedleD Back From the Dead Using Twitter OAuth()

  • Sircolin

    “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”

    loving the directness !!!

    • Diggersworld

      Thanks for the tutorial, works great, I had to make the minor changes mentioned in other comments, but other than that everything works fine, with the newest library. I’ve looked at several Twitter OAuth tutorials and this is the best one by far.

  • Sam

    This article is great apart from one thing- i can’t get it working..

    I’ve tried the tweaks others have mentioned in the comments and I am using the files from snipe’s server (as well as trying TwitterOAuth 0.1.1 straight from GitHub)

    Help! this is the error and output I’m getting…

    Warning: array_merge() [function.array-merge]: Argument #2 is not an array in /data/www/vhosts/predict-f1.com/httpdocs/assets/php/OAuth.php on line 228
    Oops – an error has occurred.

    SimpleXMLElement Object
    (
    [request] => /account/verify_credentials.xml
    [error] => Invalid / used nonce
    )

    Thanks,
    Sam

  • Pingback: Twitter Introduces OAuth And T.Co | Empowered Online Entrepreneurs()

  • Cemojo

    Do you happen to have any examples for Ruby on Rails like this?

  • I don’t, I’m sorry.

  • Samad_bola2009

    i have a problem callback page has show a error into array feild so how can i solve this issue plz reply me soon
    Error is here
    Oops – an error has occurred.

    SimpleXMLElement Object
    (
    [error] => Could not authenticate you.
    [request] => /account/verify_credentials.xml
    )

  • Very useful post. This helped me a lot in developing my first twitter application and i would recommend it to everyone because this is more then just snippets. Great advices too. Thank you for your time to write this post. Hope there will be much more people to find it useful and i certainly will spread a word about it.

    Cheers Alison

  • Great tutorial. Do you have any examples for storing/checking authorized users in a mySQL database?

  • ahmetcicek

    Hi,

    Where should i put that code?

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

    • Ankit Kumar

      ย try:

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

  • daniel_de_darik

    perfect article!!! Thank you, really appreciate it!!!

    • Azstu

      Thanks for a geat article which got me up and running.. but now I have a dumb question… that only someone as smart as you could maybe help me with.. Im not really a coder ( any more)..but here is the deal:
      I have a chess club and I post twitter updates ( thanks to your article). However, I want the status update call to reference php variable data.. but cant seem to make this work..

      ie

      The current code is :
      tokens set etc.
      $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
      and then I send these :

      $tweet->post(‘statuses/update’, array(‘status’ => ‘some fixed text’));

      BUT I want to be able to send something like

      $Text =”Hello World”;

      $tweet->post(‘statuses/update’, array(‘status’ => ‘”.$Text.”‘));

      where is would parse and convert the string inside the $Text variable and send that..

      I have tried various syntax variances to get this to work.

      Is there a way to pass the value of a string variable in PHP code as shown?

      thanks for you or anyone willing to help..

      Azstu

  • To make it work with the latest version of OAuth replace

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

    by

    $content = $to->get(‘account/verify_credentials’);

    All the info about the user will be in $content

  • Erik

    It’s probably my “beginner stupidity”, but I’m really not getting started with this. I get stuck after being directed after the Twitter page, where Twitter says that I succesfully granted the application access, including a key. How the heck do I then get back to my application, using that key?

  • Ciabo89

    Hi
    I’ve follow all this tutorial but at the and i’ve a problem.I’ve set the URL recall of my app to callback.php file,but it makes me this error:

    Oops – an error has occurred.
    SimpleXMLElement Object
    (
    [request] => /account/verify_credentials.xml
    [error] => Could not authenticate you.
    )

    I’ve try to resolve with the Vincent Michon code in his post, but it doesen’t work.
    Any Ideas???
    Thanks
    MArco

    • Ankit Kumar

      ย Please replace the place of action and $params
      For example:

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

  • Setarehhaly

    When I wanna sign in with my IPhone I got “Could not authenticate you”
    Wath can I do??

  • Anonymous

    ย Damn good tutorial. The source code your reference has been updated, so some of the modifications you suggested are no longer necessary, but your explanation of how OAuth actually works was awesome. Thanks for saving me a few hours of blood, sweat, and tears on a saturday morning.

    • Yeah, it’s a bit old, but I’m glad to hear the OAuth overview keeps it a worthwhile article. I had never really found a good, high-level explanation before, so I’m glad people still find it useful. ๐Ÿ™‚

  • Clint

    Hey there! Great tutorial. I’m setting up my site where a user can connect twitter and facebook and have one question. Each time the page is refreshed I generate a new request token and Authorization URL for the Twitter Login… Should I be doing this or only generating one request token and Authorization URL for the users entire session and saving it? Reason I’m asking is because sometimes it works perfectly smooth, others I have to go through the connect process twice. Help would be greatly appreciated!

    Again. Great tutorial!

  • Noel

    Can the api also display the statuses of friends in Twitter if the account is protected?

  • L0garithm

    the logout function dosnt quite work. If i logout and try to login with another acc, it always sends me to the previous account page.The only way to log another acc is to close browser and reopen. Since this happens i belive there’s smth wrong with the unseting of the session superglobal.

    • L0garithm – this tutorial was written over 2 years ago. Twitter’s API has changed a bit, and Abraham’s library has changed quite a lot since then.

  • Im_cool1986

    how to log out from twitter

  • Grottum

    nice tutorial, but I just can’t get this thing working. Can you please explain where in my code to put the random Boba Fett icon. I also have problems with pasting an image into the code. Please help..:)

  • More Mukesh

    ย Nice article, Thank you very much.ย  I got followers count now.
    But I have one question, How I get all followers list like fields. I need following fields
    id, name, email etc…

    Please help

    • P Deshpande

      Twitter shares limited access of JSON file in which “email” field is absent. so we can not access email id from twitter oauth API.ย  ..(

  • Ferry

    I cant seem to get a simple tweet to display on my twitter account.

    I signed up, got the keys.. created the consumer_key and consumer_secret in a config.php as described in the tutorial.
    Next I added this in the index.php (on the bottom)

    $params = array(‘user’ => ‘myuseraccount’, ‘text’ => ‘Test Message for twitter’);simplexml_load_string($to->OAuthRequest(‘http://twitter.com/direct_messages/new.xml’, $params, ‘POST’));

    When I place this is in a IF statement it says true. (looks like it works), but my update is not showing on twitter.

    Any ideas?

  • Ankit Kumar

    Nice…ย  I like this!!!

    ย I am using

    $content = simplexml_load_string($to->OAuthRequest(‘https://twitter.com/statuses/update.xml’, array(‘status’ => ‘Test OAuth update. #testoauth’), ‘POST’));and working goodthank’s snipe!!

  • would you have a tutorial as to pull direct messages in php, still using the ouath process? i am working on an automated bot that reads data from twitter and replies automatically…

  • question: what is the process of grabbing a new request token every time your app wants to tweet on behalf of one of its clients?

  • gayan

    on OAuthRequest the method and the parameters are switched now I guess. I tried several times and it did not work. so I looked and saw the parameters are need to be switched.

  • Shawndell Harris

    please see dropbox for twitter auth files https://t.co/oxgAST3vGR also see http://ghostmediapro.com/tech/twit/ for the error

  • Selene Arzola

    Great article and well explained. Tomorrow i’ll try to use/implement all those concepts of aouth within a codeigniter website . I’ve spend days trying to figure out how Abraham twitter library’s works and now with this simple tutorial i’ve understand a little bit more. So thank you very much Snipe : )

    • So glad it was helpful!

By snipe
Snipe.Net Geeky, sweary things.

About Me

Iโ€™m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I run Grokability, Inc, and run several open source projects, including Snipe-IT Asset Management. Tweet at me @snipeyhead or read more

Get in Touch