Posterous theme by Cory Watilo

Bit.ly URL Shortening in ColdFusion

I'm working on a referral program for TeamworkPM and as part of this we are going to provide a link for our resellers to post on Twitter with a shortened URL that contains a link to our main website along with a "ref" code.

I've google around and found an excellent library for creating Bit.ly URLs with ColdFusion by Matt Gifford.

It was a breeze to use, I just created a free account with Bit.ly, grabbed my API key and I was generating shortened URLs.

Now the only thing I've done to make the process more efficient for our TeamworkPM site is to cache the result of the shortened URL in memcached:

 

<cffunction name="shortenURL" returntype="string">

<cfargument name="url" required="Yes">

<cfset var bitlyAPIUsername = "teamworkpm">

<cfset var bitlyAPIKey = "---- you key here ---">

<!--- Retrieve from Mem cache --->

<cfset var memCacheKey = "shortURL#Hash( ARGUMENTS.url )#">

<cfset var memCacheLookup = APPLICATION.twutil.teamworkPMCache.getInstallationCache( key="#memCacheKey#" )>

<cfif memCacheLookup.cacheIsOK>

<cfreturn memCacheLookup.value>

</cfif>

 

<cfset objBitly = createObject( "component", "cfcs.utility.com.coldfumonkeh.bitly.bitly" ).init(

username = bitlyAPIUsername,

apikey = bitlyAPIKey,

parse = true

)>

<cfset bitLyResponse = objBitly.shorten( longURL = ARGUMENTS.url )>

<cfif structKeyExists( bitLyResponse.response, "status_code" ) AND bitLyResponse.response.status_code.XmlText IS "200"

AND structKeyExists( bitLyResponse.response, "data" )

AND structKeyExists( bitLyResponse.response.data, "url" )>

 

<!--- Store value in memcache --->

<cfset APPLICATION.twutil.teamworkPMCache.setInstallationCache( key=memCacheKey, value=bitLyResponse.response.data.url.XmlText )>

 

<cfreturn bitLyResponse.response.data.url.XmlText>

</cfif>

<cfreturn "">

</cffunction>

 

Thanks Matt. Now back to the referral scheme... hoping to be done version 1 today.