Dec
04
2010

 

Updates

Facebook requires the use of OAUTH2.0 nowadays. Some of the changes required are:

  • session is now called authResponse.
  • getSession is replaced with getAuthResponse.
  • perms is now called scope.

The zip file (as3-open-graph-example-basic.zip) linked below includes these changes (there are changes in .as, .html files and in the first frame of the example .FLA). Please keep this in mind.


This example is a beginner’s How To use the Flash Facebook API (facebook-actionscript-api), in particular in authenticating user and loading the user’s name in Flash applications. It assumes that you are already familiar with the Facebook Graph API and adding application in Facebook (you need an Application ID to make this example).

Note: This tutorial is built upon facebook-actionscript-api 1.0. Now that version 1.5 has been released, I highly recommend using it if you are just starting out. Some of the quirks in 1.0 has been removed from 1.5. Go over here to read the updated guide: /blog/using-facebook-graph-api-in-flash-as3-1-5/

 

When you set-up your application, set the application as IFrame (not FBML) application. Below is an example of the settings that I use:

 

 

Then:
1. Download the facebook-actionscript-api from: http://code.google.com/p/facebook-actionscript-api/downloads/list. I have included the version I used for this example in the ZIP file at the end of this article. (Note: This tutorial uses version 1.0 and apparently the latest version, starting from 1.5 contained some changes in the JavaScript side. I recommend using the version I use to follow the general idea. The link to the files that I use is in the bottom of this tutorial.)

2. Start up Flash IDE and create a new project (I am using CS3, but this guide should apply to CS4 and 5 too).

3. Extract the GraphAPI Source_1_0.zip into a folder. You might also want to extract GraphAPI Examples_1_0.zip somewhere because we will be using the JavaScript and html file from that example later.
Note that The GraphAPI Examples_1_0.zip contains examples for Flex Builder 4, and this guide will show you how to use the API in the Flash IDE.

3a. Much of the code is ported from the GraphAPI Examples_1_0\FacebookAPI_Sept_08_2010_samples\WebIFrameDemo\, so create a copy of this folder and I recommend saving the project that we are going to make there — for simplicity sake, again because we are going to use the pre-created JavaScript and html file from that example.

4. Add the classpath of where you extracted the GraphAPI Source_1_0.zip into the project settings.
Ie: ./GraphAPI Source_1_0/api/

5. Create a button on the screen, name it “loginButton.”

6. Create a textfield on the screen, name it “nameTextField

7. Add code to Frame 1 of the FLA (Again this code is ported from the GraphAPI Examples_1_0\FacebookAPI_Sept_08_2010_samples\WebIFrameDemo\ so you will see a lot of similarities):

First, we load up the Facebook API library:
[c]
import com.facebook.graph.Facebook;
import com.facebook.graph.data.FacebookSession;
import com.facebook.graph.net.FacebookRequest;
[/c]

Next, call Facebook.init().

[c]
// Change the APP ID with your own APP id.
Facebook.init(‘YOUR_APP_ID’, handleLogin);

function handleLogin(response:Object, fail:Object):void
{
if (response == null)
{
//resultTxt.text += ‘Error login session’;
ExternalInterface.call(‘redirect’);
return;
}
changeToLoginState();
}

[/c]

Facebook.init() passes the callback (in the second parameter) to a function named handleLogin(), which checks whether the user is already logged in or not. If the user is logged in, it will call changeToLoginState() function, which we will see later. If user is not logged in, then it will call a Javascript function named redirect(). Again, we will see this function later.

Right now, let’s hook up the loginButton to log us into Facebook first.
[c]
loginButton.addEventListener(MouseEvent.CLICK, onLoginButtonClicked);

function onLoginButtonClicked(event:MouseEvent):void
{
if (Facebook.getSession()==null ||
Facebook.getSession().uid == null)
{
Facebook.login(handleLogin);
}
else
{
Facebook.logout(handleLogout);
}
}
[/c]

If you want to request extended permissions, you can pass it as parameters to the login call. For example, below is how to request publish_stream permission:

[c]
Facebook.login(handleLogin, {perms:'publish_stream'});
[/c]

Following that, let’s add the changeToLoginState() function, like below. This code changes the button label to Logout to allow user to logout.

[c]
function changeToLoginState():void
{
//resultTxt.text += ‘Logged in’;
loginButton.label = ‘Logout’;
loadMyInfo();
}

[/c]

Now, in a real application, you can start using other Facebook API once the user is confirmed as logged-in. For this example, to demonstrate that we are indeed logged in, I am just going to call a custom function named loadMyInfo() to get the user name.

 

And here is the loadMyInfo() function. Following the Graphi API documentation, to get your own info, you can call:
[c]

https://graph.facebook.com/me

[/c]

So that’s what we will do:
[c]

function loadMyInfo():void
{
Facebook.api(‘/me’, onMyInfoLoaded);
}

// Display my name in the text field.
function onMyInfoLoaded(response:Object,fail:Object):void
{
trace("onMyInfoLoaded "+response.name);
nameTextField.text=response.name;
}

[/c]

Above, I called the /me API and then printed the user name in the callback function. It’s as simple as that. If you are interested about how the api works, continue here, otherwise, skip to Step 8.

 

It’s nice to know that you can call most of the Graph API’s (http://developers.facebook.com/docs/api) using the Facebook.api() in this manner. Once you get a hang of the process, you should take a look into com.facebook.graph.Facebook.as that comes in the facebook-actionscript-api.

[c]
public static function api(method:String,
callback:Function = null,
params:* = null,
requestMethod:String = ‘GET’
[/c]

This is a very powerful function and you can do a lot by calling the Graph API using just this one function. If you are already familiar with the JavaScript version of the API, it’s almost effortless. Notice also that the callback parameter is a function that follows this format:
[c]
function callback(response:Object, fail:Object):void
{

}
[/c]

One question is: How do you know what is inside the response object? You can always do foreach to print each variables, or you can test most of the API from this page to see the return value in the response object :
http://developers.facebook.com/docs/reference/api/user. For instance, the /me call returned this:
[c]
{
"id": "9999999999999999999999",
"name": "Permadi Permadi",
"first_name": "Permadi",
"last_name": "Permadi",
"link": "http://www.facebook.com/profile.php?id=9999999999999999999999",
"birthday": "01/01/1990",
"gender": "male",
"timezone": -8,
"locale": "en_US",
"verified": true
}
[/c]

You can explore more examples here:

8. Now we are almost ready with the Flash movie. Publish the movie as example.swf

&nbsp

9. Create the html page to host the SWF. You can use the one exported by the FLash IDE, but you will need to change a lot of the code, so just use the template below, which is taken from GraphAPI Examples_1_0\FacebookAPI_Sept_08_2010_samples\WebIFrameDemo\.

[c]

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<!– Include support librarys first –>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<!– Include FBJSBridge to allow for SWF to Facebook communication. –>
<script type="text/javascript" src="FBJSBridge.js"></script>
<script type="text/javascript">
function embedPlayer() {
var flashvars = {};
embedSWF("example.swf", "FlashDiv", "550", "250", "9.0");
}

function init() {
embedPlayer();
}

function redirect() {
var params = window.location.toString().slice(window.location.toString().indexOf(‘?’));
top.location = ‘https://graph.facebook.com/oauth/authorize?client_id=165923983441659&scope=email,publish_stream,offline_access,read_stream&redirect_uri=http://www.permadi.com/blog/2010/12/using-facebook-open-graph-api-in-flash/’+params;
}

$(init);
</script>
</head>
<body>
<div id="fb-root">
</div>
<div id="FlashDiv">
<h1>You need at least Flash Player 9.0 to view this page.</h1><p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>
</div>
</body>
</html>
[/c]

Note:

  • The file FBJSBridge.js also comes from the GraphAPI Examples_1_0 in FacebookAPI_Sept_08_2010_samples\WebIFrameDemo\ folder.
  • Above, where you see the redirect() function, you should change the redirect_uri to the URL of where your html is located at. This redirect() function is called when user is not logged in to Facebook when entering your application.
  • Change embed.swf with the name of your SWF file if necessary.
  • Change the dimensions if necessary.
  • Alert: The params variable within the Javascript redirect() function assumes that there’s a query-string in your URL. If you are using static html or have no use for the query-string, then you should just remove all references to params. Eq:
    [c]
    function redirect() {
    				top.location = 'https://graph.facebook.com/oauth/authorize?client_id=165923983441659&scope=email,publish_stream,offline_access,read_stream&redirect_uri=http://www.permadi.com/blog/2010/12/using-facebook-open-graph-api-in-flash/';
    			}
    [/c]
    

    Alternatively, you can always append a dummy query string at the end of your url.
    So if my page is http://www.permadi.com/tutorial/as3-open-graph-example-basic/, I need to call it with
    http://www.permadi.com/tutorial/as3-open-graph-example-basic/?test, where ?test is the dummy query-string. Of course you can always alter the Javascript to handle this more elegantly. Failure to properly pass the redirect_uri will cause the app not to load after the login process.

  • The embedSWF in FBJSBridge.js is NOT the same as the one in swfobject.js, so you need to be careful not to use the same code that you use for SWFObject. In particular, the FBJSBrige.js changes the position of expressInstallSwfUrl to be the last parameter:
    [c]
    function embedSWF(path, divID, width, height, playerVersion, flashVars,
                      params, attributes, expressInstallSwfurl)
    [/c]

To test the movie, you need to run the swf from the html. You cannot use the test movie feature within Flash IDE because the movie needs to communicate with JavaScript. So you should publish the movie and test by opening the html.

For starting out, I highly recommend to upload all the published files to a server for testing the redirect() (and make sure your Facebook app base URL is set to that website folder). If you are testing locally and receive permission error, you can add your local machine to the Flash Settings to allow communication.

&nbsp

Links:

Credit to the facebook-actionscript-api to http://code.google.com/p/facebook-actionscript-api/ which comes under MIT license.

15 Responses to “Using Facebook Graph API In Flash AS3”

  1. Thanks for the tutorial, this came in very handy in helping me debug what was wrong with my set up. I think its important to note that you _have_ to use embedSWF() to encapsulate SWFObject usage or the API calls to Facebook will not work. I was still calling SWFObject directly.

  2. [...] This post was mentioned on Twitter by Hasan Hero Otuome, Omar Gonzalez . Omar Gonzalez said: Good article on getting started with #Facebook AS3 Graph API: http://bit.ly/gMVFMU [...]

  3. [...] Using Facebook Open Graph API In Flash AS3 [...]

  4. hi,
    I do everything like you , but Facebook.init doesn’t work ?
    (can not call handleLogin).
    I try Facebook.login and it work ?! why?

  5. Send me the URL of the page, and I’ll check when I have a chance.

  6. Hi,

    I get all kinds of errors when I try your test page. First I get 3 IE warning msgs, on fb_init, fb_loginStatus, and lastly on session change, then I get a Flash player error msg saying it cannot access a null property, and after all that it doesn’t work, name still equals “NAME”.

    Bit dissapointing as I was hoping to develop FB flash apps in Flash CS5 rather than FB4.

  7. Hi, What browser and OS are you using?
    The messages are intentionally there (it’s enabled in the Javascript so to allow you to see what is going on in the app).

  8. Great starting point! Thanks for sharing!

    Took me a while to track it down, but in the latest build (1.5) they’ve removed the FBJSBridge.js file. It’s now wrapped up inside the AS.

    more details:
    http://code.google.com/p/facebook-actionscript-api/issues/detail?id=223

  9. Hi,

    Thanks for the example. But I tried same at my end and it doesn’t work.. I get the window to login and allow permissions to the application, but nothing happens after that. Any idea where I might be going wrong.

  10. Rahul, The symptom you described usually means that the return_url is not set correctly in the redirect function. Review the Note section near the bottom of the post for discussion about this.

  11. Thanks for the great example.

    I have managed to get this working and the login with the basic user information request works great.

    I am having a problem however requesting additional permissions. in particular I am trying to get the user ‘birthday’

    when I try adding perms:’user_birthday’ i.e

    Facebook.login(handleLogin, {perms:’user_birthday’});

    nothing happens when I try to login. Any Ideas?

    do i need to setup something in my html that holds the flash file, or isthere something that I am missing in the AS.

    Cheers
    tim

  12. 2 minutes after asking you just managed to work it out… so simple as well…

    change ‘perms’ to ‘scope’

    so instead of

    Facebook.login(handleLogin, {perms:’user_birthday’});

    we have

    Facebook.login(handleLogin, {scope:’user_birthday’});

    hope this is some help so to someone out there…

    cheers
    tim

  13. OK….I figured out. In the browser code, the name/id of the swf object was different.

    Thanks

  14. [...] The guide is written for version 1.5 of the facebook-actionscript-api; if you are using 1.0, head over here: http://www.permadi.com/blog/2010/12/using-facebook-open-graph-api-in-flash-as3/. [...]

  15. Hey, I wrote this little tutorial to test Facebook locally from FlashBuilder after getting frustrated by not knowing what was breaking with my as3 code. It might be helpful for some.

    http://www.superurchin.com/?p=460

Leave a Reply

*