Come see us

100 Brunswick Street
Glasgow G1 1TF


t: 0141 559 5840
f: 0141 559 5841
digital@framecreates.co.uk

This is the first blog post in a series of "Social Media Integration" schtuff that I have been working on lately.  What I will tackle first is the Twitter integration, which at first seemed really hard, but with a bit of perseverance is now so simple I could cry.

Twitter Applications

To start a Twitter application, firstly log into Twitter and then go to http://twitter.com/oauth where you can register a new application.  I haven't used the "User twitter for login" yet so we won't be discussing that today.  If you want your application to be able to update a user's feed, then you must set Read & Write.  If you think you will only want to read from a user's twitter account then setting Read Only makes your code more secure, i.e. you can't accidentally change things.  Twitter will now give you your Consumer Key and Consumer Secret.  Place that somewhere safe and within a config file of your application.  I don't know why they also show the three URLs as its not very helpful until you have read the API documentation or even blogs like this one (or only this one as the others are rubbish!).  The URLs are not even in order.  The order should be :

  1. Request token URL - your application requests this
  2. Authorize URL - your user clicks this URL in your application with the token you retrieved in number 1
  3. Access Token URL - your application then takes the output from number 2, calls this URL and saves the result!

So how did placing those 3 urls on the page help you?  It didn't!

Twitter Authentication

Twitter currently allows for 2 methods of authentication - plain text and OAuth.  Plain text means you send the person's username and password to Twitter each time you make a call against their account that requires authentication (Twitter has many public calls which anyone can call).  This is really insecure, if someone were listening they could get your details and hack your account.  Not fun!  So Twitter has invested some time in upgrading their API to use OAuth.  

OAuth

OAuth is all about token passing.  Your application in twitter gets an consumer key and consumer secret.  Using these details plus a few other parameters, you can create a signature that is unique.  You pass this signature along with the consumer key and the other parameters to twitter, but you do NOT send your secret.  To allow your application to update a twitter user's feed you need to do the following steps:

1.  Request from twitter an authorisation token by calling http://twitter.com/oauth/request_token with your signature and other parameters:

  1. oauth_consumer_key = { you get this from twitter }
  2. oauth_nonce = { you generate this yourself }
  3. oauth_timestamp = { you generate this yourself }
  4. oauth_signature_method = HMAC-SHA1
  5. oauth_version = 1.0 { optional }
  6. oauth_signature = { you get his by hashing up the parameters above including your secret code from twitter }

I have been using the OAuthBase code to generate all the extra parameters and do the hashing.  It works nicely and was therefore able to create a method that returns a URL to allow a user to authorise your application to be able to update their twitter feed:

string consumerKey = "xxx";
string consumerSecret = "xxx";

public string GetTwitterAuthoriseUrl()
    {
        Uri token = new Uri("http://twitter.com/oauth/request_token");
        Uri authorize = new Uri("http://twitter.com/oauth/authorize");

        oAuthBase oAuth = new oAuthBase();
        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string normalParams;
        string normalUrl;

        string sig = oAuth.GenerateSignature(token, 
                                                consumerKey, 
                                                consumerSecret, 
                                                string.Empty, // not required
                                                string.Empty, // not required
                                                "GET", 
                                                timeStamp, 
                                                nonce, 
                                                oAuthBase.SignatureTypes.HMACSHA1, 
                                                out normalUrl, 
                                                out normalParams);
        
        sig = HttpUtility.UrlEncode(sig);

        try
        {
            Helper help = new Helper();
            string output = help.CallUrl(normalUrl, normalParams + "&oauth_signature=" + sig, "GET");

            if (output.Length > 0)
            {
                string[] param = output.Split('&');
                string _token = param[0].Split('=')[1]; // we only care about the token that is passed back.                
                return (authorize + "?oauth_token=" + _token);
            }
            else
                return string.Empty;
        }
        catch (Exception)
        {

            return string.Empty;
        }                
    }

2.  When a user clicks on the URL (e.g. http://twitter.com/oauth/authorize?oauth_token=xyz) we generated above, they are sent to Twitter where they can Allow or Deny your application.  If they click on Allow, they will be sent to a your callback URL that you set in your Twitter application.  On this page you will need to extract the oauth_token from the URL and pass this back to Twitter  via http://twitter.com/oauth/access_token.  Below is the code I used:

string consumerKey = "xxx";
string consumerSecret = "xxx";

public void RetrieveAccessToken(string token, out string accessToken, out string accessSecret)
    {        
        Uri url = new Uri("http://twitter.com/oauth/access_token");

        oAuthBase oAuth = new oAuthBase();
        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string normalParams;
        string normalUrl;

        string sig = oAuth.GenerateSignature(url, 
                                                consumerKey, 
                                                consumerSecret, 
                                                string.Empty, 
                                                string.Empty, 
                                                "GET", 
                                                timeStamp, 
                                                nonce, 
                                                oAuthBase.SignatureTypes.HMACSHA1, 
                                                out normalUrl, 
                                                out normalParams);
        sig = HttpUtility.UrlEncode(sig); 
        
        Helper help = new Helper();
        string output = help.CallUrl(normalUrl, normalParams + "&oauth_signature=" + sig, "GET");

        if (output.Length > 0)
        {
            string[] param = output.Split('&');
            accessToken = param[0].Split('=')[1]; // this will be specific to a single user
            accessSecret = param[1].Split('=')[1]; // this will be specific to a single user
        }
        else
        {
            accessToken = string.Empty;
            accessSecret = string.Empty;
        }
    }

From Twitter you will get the user's access token and access secret.  Remember to save this in your database so that it's easy enough to retrieve e.g. against a user's profile.  Don't save it in Session or Cookies as you will need to retrieve them from Twitter on a regular basis, and thats a pain.  Twitter's tokens will not expire unless the user denies you application access so its safe in a database.

Great your application can now update a user's Twitter account, retrieve data and basically use the full Twitter API available.  I will hopefully be creating a full API from everything I have so far learned, adding in some .net magic.

Tweeting

So a user has authorised your application, to send a tweet is now very simple:

public bool SendTweet(string tweet, string accessToken, string accessSecret)
    {
        Uri url = new Uri("http://twitter.com/statuses/update.xml?status=" + UrlEncode(tweet));

        oAuthBase oAuth = new oAuthBase();
        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string normalParams;
        string normalUrl;

        string sig = oAuth.GenerateSignature(url,
                                                consumerKey,
                                                consumerSecret,
                                                accessToken, // this is what you retrieved from twitter previously
                                                accessSecret, // this is what you retrieved from twitter previously
                                                "POST", 
                                                timeStamp,
                                                nonce, 
                                                oAuthBase.SignatureTypes.HMACSHA1, 
                                                out normalUrl, 
                                                out normalParams);
        sig = HttpUtility.UrlEncode(sig);        
        
        try
        {
            Helper help = new Helper();
            help.CallUrl(normalUrl, normalParams + "&oauth_signature=" + sig, "POST");
            return true;
        }
        catch (Exception ex)
        {            
            return false;
        }
        
    }

The difference here is that you need to make sure you set the HttpMethod to POST instead of GET as it was in the previous 2 examples.  You will also notice that I call a method called UrlEncode - which is supplied by the oAuth code you download. You need to send your tweet through this method as the standard Server.URLEncode doesn't work as expected.  Server.URLEncode turns spaces into + and not %20 which Twitterand OAuthrequire.  Once you do that, your code and tweeting will work nicely.

So that's it for now.  Let us know what you think about it but its a lot to digest!

Bookmark and Share

Posted in: Labs

Comments

5/5/2010 7:53:09 AM
Barry Hertz
What are some good international social networking sites?
5/10/2010 12:49:42 PM
Barry Hertz
How do you find your twitter account without signing in?
6/19/2010 1:29:15 AM
online payday advance
When you discover your mission, you will feel its demand. It will fill you with enthusiasm and a burning desire to get to work on it.