Recently Twitter announced they are going disable basic authentication mechanism. Basic auth can be used until June 30th 2010, so there is only less then one month left (assuming you are reading this on June 2010). I admit that for a long time i neglected the OAuth Twitter authorization, it seemed complicated and time consuming in comparison basic auth.
However, when i found out they are shutting down the basic api, i had no other choice then to learn how it works. What it turned out is that with the right tools it’s pretty easy to do. Especially if you are (like me) looking to setup application that will be using only single user. For example to automatically update your status.
With basic authorization all we needed was Twitter login and password, with OAuth it’s more complicated but a lot more secure at the same time, even if your app will be hacked your Twitter credentials are still safe.
Ok let’s get started with it:
- Go to dev.twitter.com sign in with your Twitter credentials, next click “Register an application” link
- Fill the form, it’s automatically accepted so Twitter guys probably don’t check it all, but still … keep it proffesional. One important thing here is to select “Read and Write” on “Default Access type”. Click “Register Application” and you’re done
- Now you will need 4 keys to make your app work. Go to “View Your Applications” and then click “Edit details” on your newly created app. Scroll down and copy (somewhere) “Consumer Key” and “Consumer Secret”
- Next in the right sidebar click link “My access token” and copy both: “Access Token (oauth_token)” and “Access Token Secret (oauth_token_secret)”
Getting nervous? Relax, we are almost done, last thing we need is awesome Abraham Twitter OAuth library (click the link to download it). There few files in the archive, but we will need only two: twitteroauth/twitteroauth.php and twitteroauth/OAuth.php.
Twitter and PHP OAuth integration
Now let’s get straight to the actual code. The good news it’s there almost nothing to do: just include TwitterOAuth library, put keys and tokens you copied earlier into the script and you are done.
<?php require_once 'TwitterOAuth.php'; define("CONSUMER_KEY", "????"); define("CONSUMER_SECRET", "????"); define("OAUTH_TOKEN", "????"); define("OAUTH_SECRET", "????"); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET); $content = $connection->get('account/verify_credentials'); $connection->post('statuses/update', array('status' => date(DATE_RFC822)));
Pretty easy right? Keep in mind that this is solution for situation were all so called “Twitter actions” are executed by a single user. Other then that OAuth library takes advantage cURL library so you better have it enabled if you would like to Abraham’s library.
Image by factoryjoe source: http://www.flickr.com/photos/factoryjoe/3343062926/in/pool-519057@N23