Feb
19
2011

 

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 linked below has these changes (there are changes in .as and .html side and in the first frame of the example .FLA). Please keep this in mind.


This article 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.

This guide assumes that you are already familiar with the Facebook Graph API and how to create application in Facebook (you need an Application ID to make this example). If not, head over to: http://developers.facebook.com/docs/guides/canvas/

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/.

If you want to jump to the example, go here: /tutorial/as3-open-graph-example-basic-1.5/index.html?test. To download the code for the example, go to the bottom of this page, under Links section.

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, follow these steps to set-up your first project in Flash IDE:

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.5.)

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_5.zip into a folder.   For now, I suggest just extracting it into the same folder as your FLA

4. Add the classpath of where you extracted the GraphAPI Source_1_0.zip into the project settings.
Ie: ./GraphAPI Source_1_5/api/ in my folder configuration below: 

5. Extract GraphAPI Examples_1_5.zip somewhere because we will be using the JavaScript and html file from that example later.  Note that The GraphAPI Examples_1_5.zip contains examples for Flex Builder 4, and this guide will show you how to use the API in the Flash IDE.

6. From the GraphAPI Examples_150.zip in FacebookAPI_Dec_06_2010_samples\WebIFrameDemo, create a copy of the index.php (you can rename it to index.html if you are not using php).

Now that we’re done with the set up and copying stuff, let’s go into the Flash movie editor:

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

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

9. Add code to Frame 1 of the FLA (this code is ported from the  GraphAPI Examples_150.zip, FacebookAPI_Dec_06_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, replace the APP_ID with yours, then call Facebook.init().

[c]
//Place your application id here
const APP_ID:String = "130838916986740";
//Initilize the Facebook library
Facebook.init(APP_ID, handleLogin);
function handleLogin(response:Object, fail:Object):void
{
	trace("handleLogin");
	if (Facebook.getSession().accessToken)
		changeToLoginState();
}
[/c]

Facebook.init() will check if the user is already logged in.  If user is not already logged in, it will call prompt the user to login (this process is already handled for you).  After the user is logged in, it then it checks whether the user has authorized/installed the application and shows the application install/permission dialog (this process is already handled for you).

Facebook.init() passes the callback (in the second parameter) to a function named handleLogin().  So, after those two process, the handleLogin function in the ActionScript side is called — even if the user refused to login.

Now, if user chose not to log-in, we are giving him/her another chance to login by displaying a Login button.  The process is slightly different when user clicks the Login button.  Now, we’re calling Facebook.login function (which opens as popup).  If you want to, you replace this to use in-same-window login as described here: /blog/2011/02/facebook-authenticationlogin-process-in-popup-or-not/, but don’t worry about this now.

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
{
	trace("onLoginButtonClicked");
	// We check the accessToken to make sure user is logged in
	if (Facebook.getSession() && Facebook.getSession().accessToken==null)
	{
		Facebook.login(handleLogin, {perms:'publish_stream'});
	}
	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]

Update

Facebook requires the use of OAUTH2.0 nowadays. Some of the changes required is that perms is now called scope.


Following that, let’s add the changeToLoginState() function, like below. This code is called when user has logged in.  In this basic-example, we are just changing the button label to say Logout to allow user to logout.

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

[/c]

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.  Yes, 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]

The fail object contains some error informations. If for some reason the api call failed, you should always check the error message to help pinpoint where the problem is, such so:

[c]
function myCallback(response:Object, fail:Object):void
{
	if (fail && fail.error)
	{
		trace("error.message="+fail.error.message);
		trace("error.type="+fail.error.type);
	}
}
[/c]

Another question is: How do I 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]

Bookmark the Facebook documentation at:http://developers.facebook.com/docs/reference/api/, you will refer to it a lot.

You can explore more examples here:

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

11. 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_150.zip in FacebookAPI_Dec_06_2010_samples\WebIFrameDemo\index.php, which you copied in Step 6 above (if you are not using php, just rename it to index.html since there’s nothing that requires PHP in this example).

[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>
    
    <script type="text/javascript">
        var APP_ID = "130838916986740";			
        var REDIRECT_URI = "http://www.permadi.com/tutorial/as3-open-graph-example-basic-1.5/index.html";	
        var PERMS = "publish_stream"; //comma separated list of extended permissions
        
        function init() 
        {				
            FB.init({appId:APP_ID, status: true, cookie: true});
            FB.getLoginStatus(handleLoginStatus);
        }
        
        function handleLoginStatus(response) 
        {
            if (response.authResponse && response.status=="connected") 
            { 
                //Show the SWF
                $('#ConnectDemo').append('<h1>You need at least Flash Player 9.0 to view this page.</h1>');					
                swfobject.embedSWF("Facebook-Open-Graph-Example-1.5.swf", 
                    "ConnectDemo", "550", "250", "9.0", null, null, null, {name:"ConnectDemo"});
                
            } 
            else 
            { 
                var params = window.location.toString().slice(window.location.toString().indexOf('?'));										
                top.location = 'https://graph.facebook.com/oauth/authorize?client_id='
                    +APP_ID
                    +'&scope='+PERMS
                    +'&redirect_uri=' + REDIRECT_URI 
                    + params;                                
            }
        }
        $(init);
    </script>
</head>
<body>
    <div id="fb-root"></div>
    <div id="ConnectDemo"></div>
</body>
</html>
[/c]

Notes

  • The REDIRECT_URI tells Facebook where to go back to after the user logs into Facebook from your application. You need to set this to your own url. See the picture below. The REDIRECT_URI should be either the Canvas Page, the Canvas URL, or to some url within your Site URL.
    For staring out, I recommend just setting the Canvas URL to be the exact same as the REDIRECT_URI, and make sure the Canvas URL is within the Site URL (ie: if your Site URL is http://www.example.com/example1/, you should make sure the Canvas URL is nested within /example1/ folder.
  • Change APP_ID to yours.
  • Set PERMS to be the same as the one you use in Facebook.init in the Action Script side (Step 7).
  • Change embed.swf with the name of your SWF file if necessary.
  • Change the swf dimensions if necessary.
  • Alert: The params variable within the Javascript handleLoginStatus() 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 (do NOT remove the whole line, just the + params part).

    Eq:

    [c]
    top.location = 'https://graph.facebook.com/oauth/authorize?client_id='+APP_ID+
      '&scope='+PERMS+
      '&redirect_uri=' + REDIRECT_URI;
     [/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-1.5/, I need to call it with
    http://www.permadi.com/tutorial/as3-open-graph-example-basic-1.5/?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_uriwill cause the app not to load after the login process.

  • 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 Site URL and Canvas URL are 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. If you got a blank page after login, make sure your REDIRECT_URI is set correctly and also check the note about params above.

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 linked below has these changes (there are changes in .as and .html side and in the first frame of the example .FLA).

Links

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

26 Responses to “Using Facebook Graph API In Flash AS3 (1.5)”

  1. Hi,

    great tut, thank you for it. But it is not working in opera browser. Could you please fix it ?

  2. Hi Prednizon, here’s a post about the Opera issue:

    http://www.permadi.com/blog/2011/02/facebook-graph-api-in-opera/

  3. I did that thing with channel and also I have added this code after FB.init :
    FB.XD._transport=”postmessage”;
    FB.XD.PostMessage.init();

    I found it here http://stackoverflow.com/questions/4627293/login-to-facebook-connect-using-javascript-sdk-freezes-in-opera

    It seems that it works in opera only partly. I mean when Im not logged in it prompts me to log, so it seems that script in html is working. But flash part is not working. Flash cant connect to FB and display name of logged user. I think this Facebook.init(APP_ID, handleLogin); is not working in flash. In other browsers it works.

    Thank you for help

  4. Hi Prednizon,
    Try this example in Opera.
    http://www.permadi.com/tutorial/as3-open-graph-example-basic-1.5/opera.html?test

    I tested it with Windows Opera and it worked for me (make sure to allow popup windows).

    After your response, I added more explanation on the bottom of the article about what exactly need to be changed:
    http://www.permadi.com/blog/2011/02/facebook-graph-api-in-opera/

  5. Consider that the imports are correct and that this is my code:

    public function LoadFB() {
    Facebook.init(“158033120926253″, FBLoginHandler);
    }

    public function FBLoginHandler(success:Object, fail:Object):void {
    trace(“logged in”);
    }

    The SWF never seems to get to that trace regardless of what I do. It doesn’t seem like init is doing anything. What gives?

  6. Is it possible to access the Facebook API while developing in the FLASH IDE?

    Otherwise I have to upload it every time and test it onine :)

  7. Are you using Opera by chance? If so, see here for how to handle it: http://www.permadi.com/blog/2011/02/facebook-graph-api-in-opera/.

    Otherwise, make sure you have replaced all the APP_IDs (in the SWF as well as in the html).

  8. [...] See also: Browsing Images From Local Computer To Post To Photo Album [...]

  9. Thanks for this great tutorial! I have been all over the internet and this was the first tutorial that actually worked with the Graph API in AS3. You rock!

  10. Hi…my page keeps on coming up blank and I don’t know how to fix it. Could you please kindly take a look at my codes?

    I apologies if it’s very simple, I’m very new to this but very keen to work on this. Hope this will help other newbies trying out this tutorial.

    HTML:

    var APP_ID = "XXX";
    var REDIRECT_URI = "http://muudles.com/testing/index.html";
    var PERMS = "publish_stream"; //comma separated list of extended permissions

    function init() {
    FB.init({appId:APP_ID, status: true, cookie: true});
    FB.getLoginStatus(handleLoginStatus);
    }

    function handleLoginStatus(response) {
    if (response.session) { //Show the SWF
    $('#ConnectDemo').append('You need at least Flash Player 9.0 to view this page.');
    swfobject.embedSWF("demo.swf?", "ConnectDemo", "550", "250", "9.0", null, null, null, {name:"ConnectDemo"});
    } else { //ask the user to login
    var params = window.location.toString().slice(window.location.toString().indexOf('?'));
    //top.location = 'https://graph.facebook.com/oauth/authorize?client_id='+APP_ID+'&scope='+PERMS+'&redirect_uri=' + REDIRECT_URI + params;
    }
    }
    $(init);

  11. muudles,
    Why did you remove this line (in your html)?

    //top.location = ‘https://graph.facebook.com/oauth/authorize?client_id=’+APP_ID+’&scope=’+PERMS+’&redirect_uri=’ + REDIRECT_URI + params;

    Without this line, you won’t get the prompt to login to Facebook.

  12. Hi permadi,

    I must have misinterpreted what you meant in your notes regarding that line. I’ve uncommented that line out now, but still no luck.

  13. Hi muudles,
    I am getting this error on your page:

    {
    “error”: {
    “type”: “OAuthException”,
    “message”: “Invalid redirect_uri: Given URL is not allowed by the Application configuration.”
    }
    }

    Set the REDIRECT_URL to be the same as Canvas URL in your Facebook Application settings (see the picture under the Notes section above)

  14. muddles,
    Send a screen of your app settings.

  15. Great tutorial!
    Also check out this post for dealing with common problems in facebook login and init:
    http://blog.flexwiz.net/facebook-as3-api-blues/

  16. If you have a web-server running on your local machine, you can change your hosts setting — set 127.0.0.1 to your server name. Then you can test locally without having to upload every time.

    Windows: http://www.ezlan.net/host.html
    Mac: http://decoding.wordpress.com/2009/04/06/how-to-edit-the-hosts-file-in-mac-os-x-leopard/

  17. Thank you so much for this guide, it was very helpful for me!

  18. if you are having trouble with
    Facebook.init(APP_ID, handleLogin);
    it might be because of the way you put your swf in your html

    try using this one

    You need at least Flash Player 9.0 to view this page.

    swfobject.embedSWF(“yourswf.swf”, “flashContent”, “640″, “480″, “9.0″, null, null, null, {name:”flashContent”});

    it worked for me! :)

  19. [...] http://www.permadi.com/blog/2011/02/using-facebook-graph-api-in-flash-as3-1-5/ [...]

  20. Hi,

    Great set of tutorials! But the example is not working for me…

    http://permadi.com/tutorial/as3-open-graph-example-basic-1.5/index.html?test

    Is it the same for other people?

  21. Hi Jay,
    The example app has been fixed.
    http://www.permadi.com/tutorial/as3-open-graph-example-basic-1.5/
    Thanks for the heads up. It was erroneously updated during a recent update to handle OAUTH 2.

  22. Hi,

    Excellent :)
    but I think the source files may have the same issues also. Can’t be sure though.

  23. Hi there, first off great articles and tutorial. Much appreciated.

    I am having an issue with my authentication in the HTML page though. It seems that whenever I try to access the page, and I am not logged in to FB, I am taken over to facebook to login as normal, but AFTER I log in to facebook, I am redirected back to the page with a giant hash on the end of my redirect url.

    ie. “http://myurl.com/index.html?code=AQBSk_w_gASxiOhV3ptFcCqf1o88Vnwk3Fk2ur3MgALm–o5X-q25L-JSz1_kgCz4yrHybUVy6hP3FZy83FUEMmOXqXrMHeXpkZog7Xrja0qwp_NOc1hL2wBal3MzJi8B6B68BWR2sXJ3AgHGrXl_WFub8w5OZUGFFnTa_h4Hw2Twipz-n9DtSMKo27VS1gfiz0#_=_”

    When I am taken back to my app the html page just goes into the crazy loop where it continually loads the flash into the page. and crashes my browser.

    Any help or insight you may have would be greatly appreciated!
    Thanks in advance

  24. Send me the link to the page and I’ll see what I can find.

  25. You can download a zip file at:[hidden]

    Feel free to email me with any thoughts you might have… I am totally stumped!

    Also thanks so much for the awesome site and tutorials. Dunno what I would do without you!

  26. Hi Cam,

    Change your html to just this (below). Your FacebookLoginForm inside Flash already took care of handling the login:









Leave a Reply

*