Twitter OAuth the easy way – simple post to twitter script

After Twitter introduced mandatory authentication with OAuth, many of the current scripts for posting content to Twitter don’t work anymore.

OAuth can be great for more advanced authentication, but for a simple post to twitter script, it seems like a little overkill.

In this post you’ll learn how to create a simple script that uses a quick and dirty version of OAuth for posting new tweets to Twitter.

How to create a simple script

Simplified, Twitter OAuth involves sending both application tokens and user tokens back and forth between your site and Twitter.

If you want to authenticate multiple users, you need a full OAuth implementation, but if you only want a script that sends tweets from your site or application, the good news is that all the authentication tokens and keys can be reused, which makes it possible to build a very simple script, as long as you just get the required tokens and keys once .

To get the required key and tokens you need to carefully follow the next steps

Step 1 – Register your application

First you need to register your application at Twitter here.

Please notice that you need to log in to Twitter at the start of the Application  registration process. The account that you’re logging in to, is naturally also the twitter account that you’re application can post tweets to.

Signup form for twitter applications

Filling in the form is pretty straightforward.

The only special requirement for our purpose is set Default Access type to “Read & write”, so your application is allowed to post tweets to twitter

Step 2 – Consumer secret and Consumer key

When your application is registered by Twitter, you also have all the required keys for your script.

You find the consumer keys here:

View Your Applications -> Edit Details

The consumer keys can be found at the last part of the page

Step 3 – Access token and Access token secret

You find the Access token and Access token secret by clicking on the “My Access token” link in the right menu.

When you have the four keys/tokens:

  • Consumer secret
  • Consumer key
  • Access token
  • Access token secret

You’re ready to proceed

Step 4 – Twitter OAuth class

To connect to twitter using OAuth we’ll be using the brilliant Abraham Twitter OAuth class. The Abraham twitter OAuth class has a lot of overhead enabling more advanced authentication than is required for this script. You only need the two files “OAuth.php”  and “twitteroauth.php”.

You can download the two files directly here.

When you have downloaded the files, and uploaded them on your server, you’re ready for the last step

Step 5 – Post to twitter script

Having the required access tokens, keys and the Twitter OAuth class, it’s a piece of cake to build a script that posts messages to twitter.

You just need to insert the required keys and the path to the twitteroauth.php file in the script below, and then you’re up and running.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
<?php
$consumerKey = '<insert your consumer key';
$consumerSecret = '<insert your consumer secret>';
$oAuthToken = '<insert your access token>';
$oAuthSecret = '<insert your token secret>';
require_once($_SERVER['DOCUMENT_ROOT'].'/<insert path to twitteroauth>/twitteroauth.php');
// create a new instance
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
//send a tweet
$tweet->post('statuses/update', array('status' => 'Hello World'));
?>

Conclusion

The process for getting this script up and running might be a little  complex, but you only have to go through the process once, and then you have a very simple to use script for sending tweets to twitter from a PHP script.

Addition:

Combining with bit.ly to shortened your link and limit your entry

function get_short_link($url) {
$bitly_login="<bit.ly login>";
$bitly_apikey="<bit.ly api key";
$api_call = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitly_login."&apiKey=".$bitly_apikey);
$bitlyinfo=json_decode(utf8_encode($api_call),true);
if ($bitlyinfo['errorCode']==0) {
return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
} else {
return false;
}
}
// reduce text to twitter format
$length = strlen($text);
$ch = 70; //if the text is above 70 characters, the message is shortened
if ($length >= $ch) {
$foo1 = (substr("$text", 0, $ch));
$foo = "$foo1...";
} else {
$foo = $text;
}

Quoted from:

tips4php.net

http://tips4php.net/2010/12/twitter-oauth-the-easy-way-simple-post-to-twitter-script/

http://bit.ly

How to Write Facebook Apps in 10 Minutes

Writing F8 apps is where it’s at right now. Everybody knows it. The userbase is huge and now we have a (free) API to. Everything is good….but the documentation.

I spent a day writing my Sudoku Facebook application yesterday. I already had the sudoku javascript widget ready to go – the time was spent wading through pages of documentation and downloading toolkits that (as it turns out) I didn’t need.

As far as I can tell, Facebook allows you to create applications that appear to the user in 2 different areas.

1 – The profile. This the ‘main user page’ as far as Facebook is concerned. Here is where your main summary details are displayed and your comments wall. It would be great to have your widget displayed here, but the big limitation is that applications that use javascript are not allowed here (You must use FMBL, the facebook version of HTML). Too bad for me. What we can do is display a small ad to take the user to the Canvas page.

2 – The ‘Canvas page’. This is an entire page that your application gets to use (you can have multiple pages if you want). On these pages you can choose to display content from another website through an iframe, so that is what we’re going to do.

Ok, thats it for the overview. Start your clocks and lets get cracking.

1. Create your demo page. (2 minutes)
This is the page that the user will see on their canvas page. If you already have a page that you want to use, great. If not, then just copy this code for a guessing game.


<script type=text/javascript>
var iRandom;
function Restart()
{
iRandom = Math.floor(Math.random()*10)+1;
alert('OK, I am thinking of a number between 1 and 10');
}
function Guess()
{
var yourGuess = document.getElementById('myGuess').value;
if (yourGuess>iRandom)
	alert('Too High.');
if (yourGuess<iRandom)
	alert('Too Low.');
if (yourGuess==iRandom)
	{
	alert('Well done! You guessed it.');
	Restart();
	}
}
</script>
<div>Enter your guess between 1 and 10: <input type=text id='myGuess' name='myGuess'>
<input type='button' onClick='Guess()' value='Guess'>
<br>
<br>
<input type='button' onClick='Restart()' value='Start Again'>
<script type=text/javascript>
Restart();
</script>

It’s not going to win any awards, but it gets the job done. Save the file somewhere on your website as ‘guess.htm’. Mine is saved at http://gathadams.com/guess.htm

Ok, now log into Facebook.

2. Install the Developer Application. (1 minute)
http://developers.facebook.com/get_started.php
This allows you to create applications.

3. Create the Application. (30 seconds)
Click the ‘create application’ link
4. Fill in the Application details. (6 minutes)
There are heaps of fields you can enter, I am just going over the ones you need to get this demo working.

Application Name: Any name you want. I used ‘Guessing Game’.
Terms of Service checkbox: Check it.
Click ‘Optional Fields’.
Callback Url: This should be the root directory that your ‘guess.htm’ page is found at. You must also add a ‘/’ at the end. I used ‘http://gathadams.com/’.
Canvas Page URL: This is the most confusing part, and wasted me heaps of time. What they want you to enter is basically a directory name for your applcaition. The name must be 7 characters or more, and must be unique from other Facebook applications. I used ‘guessab’ (so you can’t). When you add ‘http://apps.facebook.com/’ to the front you have the Canvas page URL.
NOTE: If you use upper case in the Canvas Page URL, it will be converted to lower case automatically. Also, case is important, so if you use upper case in your links later on THEY WON’T WORK.
Tick ‘Use iframe’: This means that your canvas pages will use an iframe.
Application Type: Leave it at ‘website’.
Can your application be added on Facebook?: Tick ‘Yes’.
Application Description: I used ‘Cool guessing game’. If you disagree, feel free to use your own description.
Default FMBL: We will fill this out last, so leave it for the moment.
Default Profile Box Column: Tick ‘Narrow’.
Side Nav URL:OK, here is where we put a link in the side nav to the canvas page.
The full canvas page has the format:
http://apps.facebook.com/&lt; value entered in Canvas Page URL>/
So for me, the full canvas page URL is:
http://apps.facebook.com/guessab/guess.htm
Facebook maps ‘http://apps.facebook.com/guessV1/’ to your Callback URL, so what is loaded in the iframe is:
guess.htm
or
http://gathadams.com/guess.htm
Note: Notice there is no ‘/’ inserted in guess.htm, that is why you have to put it in your Callback URL.

Anyway, now we can go back to
Default FMBL: This is the text that will go on the user’s profile. Lets just put another link to our game on the Canvas page. I entered:

Lets play a <a href=’http://apps.facebook.com/guessab/guess.htm’>Guessing Game</a>

5. Add the application (30 seconds)
From within ‘My Applications’, click on ‘View About Page’ for your new application. Then click ‘Add Application’, and confirm this.

6. Done! (Lets play)

Click on the link in either the left nav panel or the main profile panel and knock yourself out.

quoted from: gathadams.com