Creating a Flash Facebook application with the Facebook Actionscript API

It’s time to see how can we build a Flash Facebook application.

What we are going to do is a Flash movie to be embedded in a Facebook application, able to interact with the user by publishing notes and stories on the wall.

The first thing we need is the official Facebook Actionscript API. This library contains all we need to create a complete Facebook Flash application.

You can download the source code at this link, but before messing with AS3, let’s create the PHP part.

I suggest you to read the Developing a Facebook Application for absolute beginners posts from 1 to 5 if you don’t know how to create a basic Facebook application.

Then, take a look at the PHP code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<style>
     <?php echo htmlentities(file_get_contents("style.css", true)); ?>
</style>
 
<script>
     function grant() {
         document.setLocation("http://apps.facebook.com/flash_demo/");
     }
</script>
 
<?php
 
require_once "facebook.php";
 
$appapikey = "xxxxxxx";
$appsecret = "yyyyyy";
 
$facebook = new Facebook($appapikey, $appsecret);
 
$user_id = $facebook->require_login();
 
$has_permission = $facebook->api_client->users_hasAppPermission("publish_stream");
 
if(!$has_permission){
 
?>
 
<div class = "allow">You won't be able to test the flash demo if you don't allow publish stream permission -
 
<fb:prompt-permission perms="publish_stream" next_fbjs="grant()"><strong>ALLOW PERMISSION</strong></fb:prompt-permission></div>
 
<?php } ?>
 
<fb:swf swfsrc="http://www.gamemummy.com/facebook/flash_demo/facebook_demo.swf" allowscriptaccess="always" bgcolor="#ffffff" flashvars="" width="500" height="400"/>

Notice at lines 1-3 the way you can import CSS style sheets. Don’t forget to use htmlentities on the imported file.

Then, at lines 5-9 I created a simple javascript function called grant that just redirects the browser to the application page. That is, basically it refreshes the page, and it will be called once the user will grant (or won’t grant) the permission to publish contents on his wall by submitting the permission form as you can see at line 30.

This is possible thanks to next_fbjs="grant()".

Another important thing in this script you should arleady know is the way I ask for publishing permission.

You can ask for permission inside the Flash movie itself but I found it easier to ask directly from Php. This way, you can even hide the Flash movie if the user does not grant permissions.

But the core of the script, the think you did not see in previous tutorials is the way I include the Flash movie at line 34 with the fb:swf tag.

You can find the official documentation at this page, and the most interesting thing is Facebook is passing some interesting parameters to the movie.

Let’s see the Actionscript now… I used the button component to create the buttons but this is not important… here it is the commented script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package {
	import flash.display.Sprite;
	import fl.controls.Button;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	// facebook rlibraries
	import com.facebook.Facebook;
	import com.facebook.utils.FacebookSessionUtil;
	import com.facebook.commands.notifications.*;
	import com.facebook.commands.stream.*;
	import com.facebook.net.FacebookCall;
 
	public class facebook_demo extends Sprite {
		var text_field:TextField = new TextField();
		var my_button:Button;
		var fbook:Facebook;
		// these are the api and secret keys you should be used to
		var api_key:String="xxxxxxxxxxxxxxx";
		var secret_key:String="yyyyyyyyyyyyyyyy";
		// starting a new facebook session
		var fb_session:FacebookSessionUtil=new FacebookSessionUtil(api_key,secret_key,loaderInfo);
		// in this object I will store all variables Facebook will pass to the movie
		var passed_vars:Object;
		// this variable will hold all facebook API calls
		var fbcall:FacebookCall;
		public function facebook_demo() {
			// just placing some buttons...
			place_buttons();
			// just creating a text field...
			create_text_field();
			// initializing the session
			fbook=fb_session.facebook;
			// this function will just print out all variables Facebook is passing to the movie
			get_vars();
		}
		// this is the core function, the one that will handle clicks on buttons and publising notes or stories according
		// to the button I am pressing
		function onclick(event:MouseEvent):void {
			// retrieving the user id (it's one of the variables passed by Facebook)
			var uid:Number=Number(passed_vars["fb_sig_user"]);
			switch (event.currentTarget.label) {
				case "Publish a note" :
					// publishing a note
					fbcall=new SendNotification([uid],"just sent a self-notification using <a href = \"http://apps.facebook.com/flash_demo/\">Facebook Flash Demo</a>","user_to_user");
					fbook.post(fbcall);
					break;
				case "Publish a story" :
					// publishing a story
					fbcall=new PublishPost("is using Facebook Flash Demo",{'href':'http://apps.facebook.com/flash_demo/','name':'Facebook Flash Demo','description':'that\'s it','caption':'this image was published by a Flash Movie','media':[{'type': 'image','src':  'http://www.gamemummy.com/facebook/flash_demo/api.jpg', 'href': 'http://apps.facebook.com/flash_demo/'}]},[{'href':'http://apps.facebook.com/flash_demo/','text':'Visit Facebook Flash Demo'}],uid.toString());
					fbook.post(fbcall);
			}
		}
		function create_text_field():void {
			addChild(text_field);
			text_field.width=500;
			text_field.height=320;
			text_field.x=10;
			text_field.y=10;
		}
		function get_vars():void {
			var varname:String;
			var varvalue:String;
			passed_vars=root.loaderInfo.parameters;
			text_field.text="DEFAULT VARS PASSED BY FACEBOOK:\n\n";
			for (varname in passed_vars) {
				varvalue=String(passed_vars[varname]);
				text_field.appendText(varname + ":\t" + varvalue + "\n");
			}
		}
		function place_buttons():void {
			var bnames:Array=new Array("Publish a note","Publish a story");
			for (var i:int=0; i<2; i++) {
				my_button=new Button();
				addChild(my_button);
				my_button.label=bnames[i];
				my_button.move(125+150*i, 350);
				my_button.addEventListener(MouseEvent.CLICK, onclick);
			}
		}
	}
}

The interesting thing of this script is the way you can send notifications (line 44) and publish posts (line 49)… I won’t talk about notifications because Facebook will deprecate this method in late November/early December 2009 , but I want you to look at the way I publish the post following the format explained at the official attachment docs.

You can test the application at this page and download the full source code, library included.

Next time, we’ll see how to add more functions.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (16 votes, average: 3.81 out of 5)
Loading ... Loading ...
If you found this post useful, please consider a small donation.
» Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.

21 Responses to “Creating a Flash Facebook application with the Facebook Actionscript API”

  1. Paul on November 4th, 2009 11:43 am

    Is’nt this a security risk when you put the secret key in the swf?

  2. Yarden Refaeli on November 4th, 2009 12:50 pm

    NEVER PUT YOUR SECRET KEY IN UR SWF, NEVER. Emenuelle, great post, I made a game for facebook, it called Snaker (http://apps.facebook.com/snaker-game). I would like to write a post in your blog about it, if you’ll like. I used PHP for the whole backend (instead of using the Actionscript library), and used AMFPHP to communicate between the flash and PHP. I’ll send you an email about it. It would be great honor to write a tutorial in your blog ;)

  3. FlashGameMaker on November 4th, 2009 4:18 pm

    Did you use Flex or the Flash IDE?

  4. Paul on November 5th, 2009 2:50 pm

    @Yarden Refaeli: Yeah thats what I thought and why I’am asking. :)
    How do you Auth the app in facebook? WIth php or with JavaScript

  5. brew on November 6th, 2009 8:02 am

    excellent!!!

    You make the best tutorials on the web.

    How about a tutorial on making a friend selector to select which friend to send a message to.

    thanks again for a really useful tutorial!

  6. Muse on November 24th, 2009 2:27 pm

    Hi all! I’m kind ned help here..I was planning to do a facebook application using flash as my Final Year Project..need help for ideas. I’m looking for small scale,complete and interactive application. Last but not least, is it a ‘must’ to use CSS and php? I’m just beginner in flash and zero knowledge in php and css but I really2 wanted to learn in this field…hope u guys can help me here..

  7. robi2216 on November 24th, 2009 7:01 pm

    Hi your tutorial is great!!!!

    I used the SendMail but I don“t worked, please if you could help me in this case

    case “Send EMail” :
    fbcall = new SendEmail([uid], ‘Hi’, ‘Facebook is excelent’, ‘Hi‘);
    fbook.post(fbcall);

    thanks

  8. Manish on December 14th, 2009 1:13 pm

    Hi nice tutorial,

    i am trying to use share element to share swf from Publish data.
    can you help me to that.

    thanks

  9. Shawn Keim on December 14th, 2009 11:40 pm

    Your tutorial is great, but your sample has the same problem I do with the posting of an item. It requires the user to approve all publications… most facebook users don’t want to do that. Do you know how to make it display the Feed Form for approval on Each post?

    Thanks in advance

  10. Markham Butler on December 16th, 2009 5:38 pm

    This is great stuff. In your tut, you say, “You can ask for permission inside the Flash movie itself but I found it easier to ask directly from Php.” Can you point me to info on how to ask permissions from within Flash?

  11. Fahim Akhter on December 19th, 2009 1:36 pm

    Finally, a decent tutorial the flash IDE. Thanks a lot for that.

    I have pretty much the same questions as everyone else.

    - First, how to authorize from within facebook.
    - Second, What about the publish this post popup , I don’t want to send messages to my users without asking them :)

    Would really appreciate the help

  12. kanyal on January 24th, 2010 12:08 pm

    Hi
    there is new tab or window open problem with this api app, how you solved it. can we test this app on desktop pc and when finished can be hosted on web. i am not talking for desktop app. i am asking about facebook web app. hope you will get idea what i want to clear
    Thanks

  13. gujarathi on March 10th, 2010 6:53 am

    Hi,
    I am facing a problem in following code. I want my application and login screen should open in same browser window. Using this code It always opens in new window. Will anybody please tell me how to achieve it?
    Again the code in if/else block in the function Init() never gets executed. It directly goes to session.login() and opens new window.

    Please help me.

    public function Init():void
    {
    session = new FacebookSessionUtil(“MY_API_KEY”,”MY_SECRET_KEY”,loaderInfo);
    session.addEventListener(FacebookEvent.CONNECT, handle_Connect);
    fbook=session.facebook;
    trace(“initial login”);
    if(loaderInfo.parameters.fb_sig_added == true)
    {
    session.verifySession();
    }
    else if(loaderInfo.parameters.fb_sig_added == false)
    {
    navigateToURL(new URLRequest(“http://www.facebook.com/login.php?api_key=” +loaderInfo.parameters.fb_sig_api_key), “_top”);
    }
    else{
    session.login();
    onConfirmLogin();
    }
    }

    public function handle_Connect(event:FacebookEvent):void
    {
    trace(“handle_Connect”);
    var call1:FacebookCall = fbook.post(new GetInfo([fbook.uid],[GetInfoFieldValues.ALL_VALUES]));
    call1.addEventListener(FacebookEvent.COMPLETE,handle_getinfoComplete);
    }
    public function onConfirmLogin():void
    {
    trace(“onConfirmLogin”);
    session.validateLogin();
    }
    public function handle_getinfoComplete(event:FacebookEvent):void
    {
    trace(“handle_getinfoComplete”);
    user=(event.data as GetInfoData).userCollection.getItemAt(0) as FacebookUser;
    if( user == null )
    {
    trace(“handle_getinfoComplete,onConfirmLogin”);
    onConfirmLogin();
    }
    else
    {
    trace(“hi”,user.first_name+” “+user.last_name);

    StartGame();
    }

    }

  14. EZ on March 13th, 2010 12:38 am

    Encountered a problem:
    My Flash movie is not loaded from my server (“Movie not loaded…”).

    Trying to debug the problem I’ve added Emanuele’s SWF to mine:

    The result:
    The SWF from http://www.gamemummy.com loads just find
    The SWF from http://www.microsheep.com does not load

    Permission problems?
    Any ideas?

    P.S
    Trying to reach this swf from the browser works just fine:
    http://www.microsheep.com/facebook_test/facebook_demo.swf

Leave a Reply




Trackbacks

  1. Websitemarketingbiz.Net- Hyprobulksms-Rahsia Jana Income mudah » Blog Archive » Creating a Flash Facebook application with the Facebook … on November 4th, 2009 6:07 pm

    [...] more here: Creating a Flash Facebook application with the Facebook … No Comments Read [...]

  2. Down the Foxhole – News Flash on November 4th, 2009 10:39 pm

    [...] Self-professed Italian geek and programmer Emanuele Feronato provides a useful tutorial on how to create a Flash applicaiton for Facebook using the Facebook ActionScript API. Read more [...]

  3. Weekly Shared Items – 10. November, 2009 | TOXIN LABS - weblog of a german design student from wuerzburg on November 10th, 2009 7:14 am

    [...] Creating a Flash Facebook application with the Facebook Actionscript API [...]

  4. Creating a Flash Facebook application with the Facebook Actionscript API – part 2 : Emanuele Feronato on November 11th, 2009 7:16 pm

    [...] time to make some considerations on the Facebook application made with the Facebook Actionscript API I blogged some days [...]

  5. ??Facebook??????????? | God is not home today on November 15th, 2009 9:08 am
  6. Emanuele Feronato on November 17th, 2009 3:30 am

    [...] Some days ago I showed you how to create a Flash Facebook application using the AS3 API. [...]

  7. MoMo-Studio Development Blog » Blog Archive » Zetta Monster Plus….Facebook? on January 22nd, 2010 9:36 am
flash games company