This afternoon I’ve been wrestling with Facebook Connect for a project I’m working on. Chances are that you’ve come across it before. It’s a button on third-party sites that says something along the lines of “Login Using Facebook”, allowing you to identify yourself to them using an account you already have.
Think what you like about Facebook as a company, but I think the tools they release to developers (particularly the Login Button and Comments) are great. They lower the friction of an action by making it as easy as possible: in this case, adding a comment or becoming a member of a site. Not only do they make this easy, but things like Comments provide a familiar interface to users that encourage them to engage – and it’s becoming increasingly popular.
I could ramble on for ages, but this post is a technical one.
The downside of Facebook is that it’s massive. And it’s popular. And they keep changing their APIs and the way things hang together. The result is a large number of libraries and tutorials that are either irrelevant or out-of-date. I prefer to know how something hangs together technically, and then make it work in whatever I’m coding. So here’s how it works.
Set Up a Facebook App
First thing’s first – you’ll need to set up an app through the Facebook Developers site, which will give you an application ID and secret that you’ll need to use in order to be able to ‘talk’ to Facebook.
Putting a Login Button on Your Site
Next, you’ll need to put some Facebook Javascript onto your site:
1 2 3 4 5 6 7 8 9 10 | |
With that done, you’ll be able to use FBML to add a login button:
1
| |
Talking to Facebook
Once you’ve got that done, you’ll be able to visit that page and click the “Login” button. That’ll take the user through the steps they need to grant permission to your application to use their data. It pops up as a new window, which closes once the process is over.
Fetching Data
Once the user has granted permission, you’re all ready to talk to Facebook to get data about that user.
In this example, we’re using a method which is used as a Django view. But whatever Python web framework you’re using, it’s going to be similar. The key thing is that get_user_from_cookie searches through an array of cookies looking for the Facebook authorisation token.
Here, we’re using Facebook’s own Python SDK – it’s ace. Below, The token is used to create a new instance of the Graph API, and then we just query it for that user’s details. The bit at the end is somewhat Django-specific, but we’re just passing that array of profile data to the template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Finished
There, you’re done. You’ve got a user to grant you permission over some of their data, and you’ve managed to fetch their data in your Python application. What you do with it now is up to you – this isn’t meant to be a massively in depth tutorial, but more of a guide to get you up and running.