Recently I was given a task by my current employer (an online retailer) to find a way to track social interactions of registered members on the company's website. The goal was to reward members with discounts and other types of bonuses for liking products, tweeting about them or pinning them to their pinboards on Pinterest.com.
I knew that tracking interactions with the first two services would not pose any problems as both, Facebook and Twitter, have callback functionality available for their buttons. Facebook has FB.Event.subscribe for their Like button and Twitter has a Web Intent called "tweet" notifying you about successful tweets.
However, things turned out to be more difficult with Pinterest as it doesn't have a similar functionality (at least at the time of writing this article, December 2012).
A quick investigation showed that no one else had managed to find a decent solution to this problem either. Everything I found was either a dirty hack or a very dirty hack. Some "solutions" even suggested recreating the Pin It button manually only to be able to define the custom logic, which in my view is plain crazy!
So I realized that I had to come up with my own solution if I was to track pins. And after a bit of thinking and investigating I did! Knowing that there are developers out there trying to achieve the same goal, I decided to share it here.
As some of you may know websites like Facebook or Twitter allow you to fetch user profile images if you know id of the given users. For example, you can fetch the Facebook image for Mark Zuckerberg by going to http://graph.facebook.com/4/picture (4 is Mark's user id), however if you pay attention to the address bar you will notice that the the aforementioned URL actually redirects to http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg.
Same goes for Twitter - I could fetch my user picture by going to http://api.twitter.com/1/users/profile_image/codeaid but it actually redirects to https://si0.twimg.com/profile_images/321201130/twitter_bigger_normal.png.
In one of the projects I've been working on lately, I added a functionality for people to log in using their Facebook, Twitter and other service credentials. I am also storing URLs of their user images in the database for displaying on the comment pages. As you saw earlier it is easy to generate URLs redirecting to the correct destination, however as you can imagine it doesn't make sense to store them as they are as you would have to execute those redirects every time you access the image. Imagine if you have a page with comments and every comment has a picture - it could and would take a long time to resolve and load them all.
That lead me to writing a simple function, which takes the starting URL, follows all the redirects and returns the last effective URL for it. From examples above the last effective URL for http://graph.facebook.com/4/picture would be http://profile.ak.fbcdn.net/hprofile-ak-snc4/157340_4_3955636_q.jpg.