Adventures of Twitter Integration
So, it turns out that the timing of my new blog couldn't be better. I actually have something valuable to share!
Recently, I was tasked with integrating Twitter into a website that I work on (RinkTime.com). I initially thought it would be a piece of cake because there's always another developer out there who has shared code for a similar concept. Imagine my surprise (and ultimately, frustration) when there wasn't any example or even good documentation to learn from.
Well, I finally figured it out and now I'd like to share my knowledge with the ColdFusion community.
The Goal
My goal was to integrate Twitter using ColdFusion and the OAuth protocol. Twitter has said that they want to switch over to OAuth in the future, so I want to develop my app in a way that won't be obsolete 6 months or a year down the road. Plus, I won't have to deal with the security of users' login credentials.
My first stop was the Twitter API wiki, which has a couple ColdFusion libraries for the Twitter API, but neither takes advantage of OAuth. I bet they're both great solutions, but the lack of OAuth was a deal breaker for me.
Then I found Twitter4J by Yusuke Yamamoto. It's a Java solution with OAuth support. Score!
The Authentication Process
This is where I had the most trouble. I just couldn't seem to get a straight answer on the step-by-step details for the authentication process. It's actually pretty straightforward -- if it's laid out nicely. Luckily, that's exactly what I've done here:
- Within the application, generate a Request Token and a Request Secret.
- Using Twitter's authorization URL, you send the user to Twitter's website so that the user can Allow or Deny access to your application.
- Presuming the user allows access, they are then redirected back to your application based upon the Callback URL you specify when registering with Twitter.
- Once the user is back on your site, you have to swap out the Request Tokens for Access Tokens. This is the magic step where you finally gain access to the user's Twitter account.
- Store the Access Tokens for future use however you'd like -- I store them in a database. They never expire, although they can be rejected in the future if the user chooses, so make sure you do your error checking.
- Each time you want to access the user's account, you pull out the Access Tokens and go to town.
Of course, there's a lot more that goes on behind-the-scenes, but for the scope of this write-up, that's all we really need to know.
The Solution
- Register your application with Twitter here and keep the Consumer Key & Secret values handy.
- Download Twitter4J
- Install the JAR file in ColdFusion. You'll want to place it in an existing Class Path (like "C:\ColdFusion8\lib\") or you can set up a new Class Path in "CF Admin > Server Settings > Java and JVM". Then restart CF.
- Create the Java object in your application with the Twitter values from Step 1:
<cfset Twitter = createObject("java", "twitter4j.Twitter")> <cfset Twitter.setOAuthConsumer(TwitterConsumerKey,TwitterConsumerSecret)>
- Now we start the authentication process, which is where things get fun. First, we generate our Request tokens to send to Twitter. We have to save the Request Token and Request Secret values for later use when the user is transferred back to the application. I've chosen to do so in Session variables, but this can be accomplished however you'd prefer.
<cfset RequestToken = Twitter.getOAuthRequestToken()> <cfset Session.oAuthRequestToken = RequestToken.getToken()> <cfset Session.oAuthRequestTokenSecret = RequestToken.getTokenSecret()> <cflocation url="#RequestToken.getAuthorizationURL()#" addtoken="No">
- At this point, the user is on Twitter's site and have the opportunity to Allow or Deny access.
- After Allowing access, the user is transferred back to your site and you exchange the Request Tokens for Access Tokens:
<cfset AccessToken = Twitter.getOAuthAccessToken(Session.oAuthRequestToken,Session.oAuthRequestTokenSecret)> <!--- Store the Access Tokens, via: AccessToken.getToken() and AccessToken.getTokenSecret() --->
- Now, with Access Tokens in hand, you have full access to the account.
Update: The Authorization process (4-7 above) is only required once per user in order to obtain the user's unique Access Tokens. Only Step 9 needs to be executed each time you want to access the account.
- Finally, to use your new powers, you only have to instantiate the Twitter object, load up a users Access Tokens, and then have fun with all of the methods Twitter4J offers.
<cfset Twitter = createObject("java", "twitter4j.Twitter")> <cfset Twitter.setOAuthConsumer(TwitterConsumerKey,TwitterConsumerSecret)> <cfset Twitter.setOAuthAccessToken(StoredAccessToken,StoredAccessSecret)> <cfset Twitter.updateStatus("My first custom Twitter update! Thanks @RobOBrien!")>
Obviously, this only scratches the surface of what you can do with Twitter4J and how you implement the authorization process. What I've explained is a bare bones solution. I've actually wrapped it up in some CFCs and integrated it into my larger application, but that's up to your own situation and techniques.
I hope that this will help prevent the frustration that I had to endure to get this working. If you have any questions, let me know, but I can't promise any true support on this. I'm just sharing the knowledge.
Many thanks to Yusuke for all the work he's put into this library.
Have fun!
Has this solution saved you time?
I'm a firm believer in sharing knowledge for the sake of helping someone else. No strings attached. However, we all have bills to pay and hosting to maintain. If you feel like this post has saved you even an hour of development time, would you consider donating that hour to me?
@jibu That’s good to hear! Hopefully it’s a quick fix for those who need it.
UPDATE: I just spent the last few hours upgrading one of my projects to Twitter4J 2.2.3. It’s quite different, but not all that difficult to understand once you get your head around it. Look for an updated blog post soon! (That’s my public announcement to light a fire under my butt and get the post done quickly.)
Hi Rob,
I have done exactly the same but after the log-in to twitter it redirects to my page but my session gets expired can you suggest something why it is happening or what could be the reason. I checked with fiddler the redirection is taking place but the session expires. Only one thing I found that the URL redirection takes place using Http:// but our site use Https://, is that the reason why session expires?
Rob,
Did you figure it out with 2.2.3? My app which following your instructions worked excellent for a year is now broken. Swapped out twitter4j versions but now get an error on the setOAuthConsumer step…
Hi Rob, I posted a question on Stack Overflow here and they pointed me to your blog, which actually I’d already read. But, now that I’m here again, I wonder if you have any ideas. Basically, I’m trying to use jQuery/ajax to open up a Twitter authorisation page and get the user’s access tokens in return. However, with oAuth, you have to provide a callbackURL.
This is what I have so far:
$.getJSON(cfcRoot + "/twitter.cfc?method=getRequestURL&returnformat=json, {"user_id":user_id}, function(res,code) {
openWindow(res); //pops up twitter auth window
// here I want to get the auth access tokens for saving to db
});
Any ideas would be greatly appreciated. I’m thinking along the lines of opening the auth window in an iframe with jQuery, then getting the results I need, but not sure.
Paul