Facebook API version 2 Project Setup Walkthrough
Update: The AS3 Facebook API is now under Adobe’s Umbrella! I have spent many many hours on this pet project of mine and I am now very happy to relinquish control to some very talented programmers on the Adobe team. I will still be involved in the API community and will be consulting with Adobe about the features and future of the API so I’m not going anywhere. But the API is going to be much much strong because of this transition.
If you’re looking for instructions on getting started then the Facebook Page on Adobe’s Developer Connection is going to be a MUCH more educational source than this post. It’s just a few weeks old and already out of date. :P There have been some architectural changes to the API since this tutorial was released (all for the better!) so make sure to pay attention!
I have created a second HOWTO post for the Facebook AS3 API that I have built. The first was has been out-dated for a while and quite a few changes have happened to the API lately. This post shows the essentials of getting a project setup with the API as well as how to connect and make a couple of calls. It is very basic but if there is some part of the process that is hanging you up (or you just don’t know where to begin) then hopefully this guide will help.
If you want additional help then you may find the three examples in the SVN repository helpful. (Flash, Flex, Air) If you have more questions then the Google Group setup for this project would be a much better place to post your questions then on this blog.
Step 1: Getting the API and Setting up a Project
There are a number of ways that you can get the API code. If you already know how you’re going to do that then you can jump right into Step 2. This step is a bit on the “elementary” side so if you don’t read it I won’t feel bad.
The easiest way to get started is to simply download the .swc file (the latest is right on the project’s homepage) and put it into your library path (in FlexBuilder 3 the default is your /libs folder). This method certainly isn’t bad and updating isn’t very hard; just download the new .swc file any time there is a version change.
Another way is to check out the API code directly into your project. This isn’t always the “cleanest” way to do things but it definitely has advantages such as enabling you to debug and change the API code right in your project. The examples for the API use this method. Setting this scenario up is outside of the scope of this walkthrough but if you become familiar with svn:external then you should be able to figure out how.
The last method is the way I suggest you use the API if you are using FlexBuilder to develop; especially if you’re interested in seeing how the API works or helping out with it. Check out the Facebook AS3 API as a library project; the project settings and properties are checked into the SVN repository so it should be a breeze. This will allow you to see (and modify) the API code. It doesn’t muddy up your project with the API. And it allows you to easily update the code directly from the repository with a simple SVN update.
If you’re NOT using FlexBuilder to develop (for instance, the Flash IDE) then you probably want to use the .swc. Or if you’re using something crazy like JEdit then I’m sure you can figure out what you need to do.
The tutorial assumes that you have subclipse installed in Eclipse/FlexBuilder. There are other tools of course, but I prefer this one. To start just add the API project SVN location (http://facebook-actionscript-api.googlecode.com/svn) to your list of repositories.

Once added you’ll see the three examples in the /examples folder and the /trunk with the base AS3 API project files. Right-click on /trunk and click “Checkout . . .”. Just click “Finish” and the project will be checked out into your workspace.
Now we need to create a new project that is going to USE this library project. Create a new Flex project. The reg’ler ol’ settings will work fine. Once the project is created right click on the project and click “Properties . . .”. Go to the “Flex Build Path” option and click “Add Project . . .” and add the fbAs3Api project.

Now your project is ready to use the Facebook AS3 API!
Step 2: Creating a Facebook Project
The first step here (if you haven’t already) is to install the Developer application into your Facebook profile. Once done navigate to that developer page and click the “Set Up New Application” button. On the first “Basic” tab take note of the API Key and Secret.

Back at your eclipse project copy and rename the /html/api_key_secret.xml.template from the fbAs3Api project to your projects /html-template/api_key_secret.xml Copy and paste your API Key and Secret values into this XML file. Keep this file safe. It has your secret in it. Don’t upload this file to any server or share that secret with anyone.

On your Facebook page you need to set your Callback URL. This is the html (or PHP or whatever) page that has the content for your application. Even if you’re JUST using the desktop app to get started you should still set this to something.
Also on the Facebook application settings page you need to go to the “Advanced” tab to set the Application Type to “Desktop”. Otherwise you won’t be able to run this from within FlexBuilder. (Don’t worry, you’ll also be able to run your application online without changing that setting).
Step 3: Getting a local connection to Facebook Servers.
It’s much easier to debug your Facebook application from within the FlexBuilder environment. Otherwise you have to compile the application, upload it, run and test it. In order for us to do that we will run our application as a “Desktop” application. When the app is running online we need it to run as a “Web” application. To handle running the application as both types (as well as to load our api_key_secret.xml file and some other handy things) we will use the appropriate SessionUtil. In this Flex example we will use the FacebookFlexSessionUtil class.
First we create a Flex Session Util and grab our instance of the Facebook object from that. (Note that there are three different session utils; Flex, Air and Flash. They all do essentially the same thing but just a little differently attempting to best leverage the benefits of each platform.)
// VARIABLES //////////
private var sessionUtil:FacebookFlexSessionUtil;
private var fBook:Facebook;
// CONSTRUCTION //////////
private function init():void
{
//create an instance of the session util
sessionUtil = new FacebookFlexSessionUtil();
//grab the instace of the facebook object
//from our session util
fBook = sessionUtil.facebook;
…
</pre–>
We want to know when the facebook object has connected and is ready to rock and roll so we‘ll add a listener.
<pre lang="actionscript">fBook.addEventListener(FacebookActionEvent.CONNECT, onConnected);
If you’re doing this in Flash then you’ll also have to handle the Desktop validation. The Flex and Air Session Utils handle this automatically. If you need to see how you can handle this yourself then check out the Flash Example for ideas.
Now all we have to do is to tell the Session Util to connect. It will automatically figure our which connection to use and will fire up the appropriate FacebookSession. If it is a desktop session (which it will be right now) then it will load the api_key_secret.xml.
When it is connected our onConnected method gets fired and we’ll be ready to go!
sessionUtil.connect();
}
private function onConnected(e:FacebookActionEvent):void
{
trace("we are ready to go right?!");
}
Give it a run and you should see a few screens that look like this:



and a trace that says:
“we are ready to go right?!”
If you checked the “keep me logged in” button on the login page you shouldn’t have to log in from your development environment again. The session information is saved (as a Local Object) and handled by the Session Util.
Step 4: Logging
If you want to see what’s going on with the API then you need to hook into the logging framework. I’ve rolled my own logging framework that is Flash friendly. (Feel free to use it on other projects if you want to.)
Just add:
You could save that logger instance and do some cool stuff with it (See the Flex Example for one idea). But just instantiating it is enough to get the logs to show up in your trace window. Which is something at least.
Step 5: Making a call
So now we need to get something from Facebook.
I’ve created a list component with an id of “friendList”. I want to get a list of my friends IDs and put them there.
<mx:List x=”21″ y=”25″ id=”friendList” labelField=”uid” />
Back in my onConnected method I’m going to create a call and post it to the Facebook servers.
{
var call:GetFriends = new GetFriends();
call.addCallback(onGotFriends);
fBook.post(call);
}
private function onGotFriends(call:GetFriends):void
{
friendList.dataProvider = call.friends;
}
The “callback” that is used here is very similar to a listener but instead of an event object being passed to the function, the actual object is passed. You don’t have to worry about removing listeners and such when your call is complete. You could still listen for the Event.COMPLETE event to be dispatched from the call if you want.
The second param of the Facebook.post() method is a callback function so you could even shorten that further like this:
{
fBook.post(new GetFriends(), onGotFriends);
}
When the app runs you should see a list of all your friends IDs in the list. Yay! I have friends!
Step 6: Custom Calls
Not every possible call that you can make to Facebook has been coded into the AS3 API. Eventually I hope they are, but for now only the most important (to me) are available. Sometimes, too, the API doesn’t allow you to do everything that a call should allow you to do. This is where custom calls come in. While it would be great if you wrote a new class to handle everything (and sent it in to be added to the API) sometimes you just need a quick and dirty call. As an example we are going to call the getFriends method using a generic FacebookCall.
We’ll use information from the API documentation wiki. This page talks about our friends.get command.
The code is going to change to look like this:
{
var call:FacebookCall = new FacebookCall();
call.method = "friends.get";
//I’m just hard coding a friend’s UID here
//but it should give you the idea
call.setRequestArgument("uid", 216292);
call.addCallback(onGotFriends);
fBook.post(call);
}
private function onGotFriends(call:FacebookCall):void
{
friendList.dataProvider = call.result;
}
Step 7: Getting it online
Now you have this rocking app that lets a user see just how popular they are by showing them a list of all of their friend’s UIDs. How do you get this puppy in a Facebook Canvas page? For all of these methods that follow you’ll have to set your application’s callback page to the page on your server (this is on the Basic tab). Remember also to set the Render Method on the Canvas tab to either FBML or iFrame. Also on the Canvas tab you need to set the Canvas Page URL value. For instance if you set it to myApp then the URL to run your app on Facebook’s server is going to be http://apps.facebook.com/myApp/ You can’t browse directly to your hosted file (fbml OR iframe). You gotta to through Facebook. There are other ways to run things straight from your website (including auto-redirection to your canvas page) but this walkthrough doesn’t cover that.
FBML
The easiest way to get things running is to use FBML. This is more limiting as far as what you can do with your .swf (compared to using an iFrame) but it’s simple and if you’re doing other kinds of development that leverages FBML (not a bad thing to do) then this will be the way you’ll want to go.
On your server just create a file to host your FBML (for instance myApp.php, supposing you might want to do some other PHP magic on the page while you’re there). In that file will be an fb:swf tag that looks something like:
<fb:swf swfsrc=”http://pbking.com/projects/example/example.swf” width=”100%” height=”100%”/>
The swfsrc property MUST be an absolute URL to your application .swf that you are hosting. But that’s all you really have to have in the file. (You CAN have a lot more of course.) When the Facebook servers render the HTML based on your FBML then the necessary flashVars will automatically be pushed to the .swf and it will be ready to run! No need to set anything else. The application will be using the “Web” session.
iFrame JSBridge
You can use the Facebook JavaScript API as a bridge between Flash and the Facebook servers. This used to be the only secure way to go. (Secure meaning that your secret isn’t compiled into your .swf). But the Web session is also secure now too. This method is a little slower than communicating directly with the servers and is harder to setup (and keep working . . . this method has been unfortunately brittle). But sometimes it may be useful.
Connecting your application in this way isn’t what I recommend but there is a template available to help you get started. This template shows what flashVar values need to be passed into your application .swf to get it to connect via the JSBridge (as well as how to get the JSAPI working in the first place). In addition to the .html file to host your .swf (and the swfobject library to load it) you will also have to place a copy of the xd_receiver.htm file somewhere on your site. The JavaScript API wiki page has more details on how to get that to work.
iFrame Web Session
This is the method I like best and the one I recommend for most scenarios. It’s similar in setup to the JSBridge setup (you should still start with the Web Session Template and you still need to use the swfobject library) but you don’t need to worry about the xd_receiver.htm file or the JSAPI changing.
When Facebook’s servers fetch your html file it will pass to it a bunch of properties that will be very helpful to our application .swf. If you look at the template you’ll see that there are a few lines of JavaScript that pull the values from the URL’s GET string. It then packages all of those values up and sends them to your .swf. The .swf will then know (based on these values) to fire up a web session and start talking. One of the values passed is your API_KEY so you won’t even have to pass that into the .swf or compile it in or anything.
Step 8: Profit
Now that you have your kick-ass application online you’re ready to start making money. Or at least become famous. Or maybe cause the ladies to notice you more.
This is a VERY simple example of what you can do with the Facebook AS3 API. The sky is the limit on what you can build. If you’ve built something awesome then please drop me a line; I would love to hear about it. If you’re looking for more help then check out the Groups Page. I try to pay attention (when I can).
hey,
everything works except step 7. My project crashed because he can’t set the best connection type. Is it possible four you to make a walktrough (in detail) how to set everyting from step 7?
What more information are you looking for Domien? What method are you trying to use? (fbml, iFrame). For both methods you simply need to host your .swf file and .html file somewhere and point facebook to your html file. The iFrame examples point to templates where the only thing you should have to change is the name of the .swf that you are loading. In the iFrame examples you also have to host the swfobject.js library as it is what actually loads the .swf into your .html page.
Actually, There may be a little problem about iframe_jsbridge_example.html file. At line 24
var flashVars = {
as_app_name: “flashContent”;
};
It just has one more “;”, remove it and then OK.
Indeed you are correct Raven; thank you for pointing that out. I have changed the file. Hopefully it will work for more people now!
Great API and very easy to follow. Are you going to setup any more tutorials how to use other features? Such as sending invites to your application.
tanks, very usefull.
And simple , i use your api as soon as possible.
Great job !
Hi,
i have dowloaded facebook_as3_api_v0.9.2.zip and when run it in flash
CS3. i am getting following error:
1046: Type was not found or was not a compile-time constant:
TextField. import com.pbking.facebook.data.users.FacebookUser;
I wasted hours to find the solution.
Plz plz can anyone guide me on this.
Thanks very usefull.
Hi There,
The API is a fantastic library but I have some questions regarding the custom calls. I’m trying to figure out how to run the promoteSession method and can’t seem to get it working.
Do you happen to have an example of this?
Christian
Thank you very much your Api ROCKS!!
i have just some problems using the Photos.Upload
sadly it don’t work, tried both under FBML or IFRAME
please any help?
Very well done. This appears to be the only legitimate “getting started” guide available right now. For this reason, I think it might be advantageous to get the out-dated quick start guides removed from the GoogleCode location where the repository is being held.
Anyway, you’re timing on this is impeccable. Expect to see some publicity around Q309, possibly sooner. Feel free to contact me directly for more details.
Cheers!
-Dan
The facebook api connetcion doesn’t seem to work anymore from today!
it seems the facebook class can’t get the UID correctly
it keep getting NULL
maybe facebook changed something?
Problem: I always get that nusty: “Click OK to open the install page.”
For the first time i’m redirected to the facebook login and then “Aloww it” pages.
But after that i see the same message and i’m redirected to my callback URL.
And the strangest thing is that the same happens with you example app hosted on facebook.
Why is it always sessionless or smth?
Please advise.
I’ve some problems I can figure out.
[SWF] facebook_test.swf – 1.071.128 bytes after decompression
Error: could not determind facebook connection type
at com.pbking.facebook.util::FacebookFlexSessionUtil/connect()[C:\media\eclipse\fbAs3Api\src\com\pbking\facebook\util\FacebookFlexSessionUtil.as:105]
at facebook_test/init()[C:\Documents and Settings\lstrambi\My Documents\Flex Builder 3\facebook_test\src\facebook_test.mxml:19]
at facebook_test/___facebook_test_WindowedApplication1_creationComplete()[C:\Documents and Settings\lstrambi\My Documents\Flex Builder 3\facebook_test\src\facebook_test.mxml:2]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:9298]
at mx.core::UIComponent/set initialized()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:1169]
at mx.managers::LayoutManager/doPhasedInstantiation()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\managers\LayoutManager.as:718]
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.core::UIComponent/callLaterDispatcher2()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8628]
at mx.core::UIComponent/callLaterDispatcher()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:8568]
flashvars:
could not determind facebook connection type
??
Does anyone know a work around for the Loader class!?
If you try to load a users Photo (using the relative path given by the API) it won’t let you. This is using Flash by the way, it may work in Flex.
Hi; i want to upload photo from my as3 aplication to a album on facebook, and i can’t do the “UploadPhoto.as” work… Can’t you help me please?
Well, I’m trying to use IFrame Web Session using your javascript template which passes all the fb parameters…
And I get everything into the flash correctly.
flashvars:
fb_sig_profile_update_time = 1237456611
fb_sig_user = BLABLA
fb_sig_expires = 1237820400
fb_sig_added = 1
fb_sig_app_id = 59532835548
fb_sig = BLABLA
fb_sig_session_key = BLABLA
fb_sig_in_iframe = 1
fb_sig_api_key = BLABLA
fb_sig_time = 1237814154.0298
fb_sig_in_new_facebook = 1
fb_sig_locale = en_US
However, when I call GetUserInfo or any other…
determined a not-installed web application
> > > calling method [direct]: facebook.users.getInfo
+fields = name
+uids = BLABLA
< < < received facebook reply [direct]:
{“error_code”:104,”error_msg”:”Incorrect signature”,”request_args”:[{"key":"fields","value":"name"},{"key":"uids","value":"BLABLA"},{"key":"call_id","value":"12378147593570"},{"key":"v","value":"1.0"},{"key":"api_key","value":"BLABLA"},{"key":"format","value":"JSON"},{"key":"method","value":"facebook.users.getInfo"}]}
error making call: 104|Incorrect signature
How can I get rid of this incorrect signature error?
I compared the signature I recieve from flashVars with the one I gather from facebook PHP api , they are same! :(
Hi, I really need to get out of this problem, because I don’t understand…..I’m using the method “startWidgetSession” but using the session secret passed when i use the fbml:swf tag. But then when I get connected my app returns me the error 104 “Incorrect signature”?? Why??
And when I use the secret key parameter in the startWidgetSession function, everything goes nice!…and theres no problem….
Great! Thanks a lot…
I have got a question…
Is there a way I can create a facebook app that doesn’t require a separate login windows? Thank you very much.
It seems that both the FacebookFlexSessionUtil and the FacebookFlashSessionUtil are gone in the latest 3.1 version of the API. All I’m really trying to do is quite simple. I have a user UID (on it’s own not anything else) and I want to get that users photos and name.
Any ideas?
How to send a message to my wall in facebook?
The link to the web template is broken… could you setup a new one?
Thanks a lot for this resource, is a really nice step by step article, simple and clear!
There is only FacebookSessionUtil class now, which is at:
http://code.google.com/p/facebook-actionscript-api/source/browse/trunk/source/actionscript/com/facebook/utils/
hi,
the example above is done in flex….is it possible to do all this in flash?