Creation of a Flash Facebook application using AMFPHP

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

Now Yarden Refaeli from Rigel Games is sharing with us his experience in creating a Flash Facebook application using another technique.

Let’s read it:

« Hello, my name is Yarden Refaeli and I have been flash programmer for 1 year. A few weeks ago, I decided to make my first facebook flash game, Snaker. Well, I won’t lie: It was HARD. After I made it to the end, I decided to write a tutorial about the best approach to build flash-facebook game. So let’s start!

First, we need to save our meta user-data about every user in OUR database, and for this we need to use a server-side language (in this tutorial I will talk about Mysql, but every other database or server-side language is fine).

Let’s say we want to make a game that save our score at the end, and then show us the score we got, and the scores of our friends. We need to save the score for every user, with it’s unique id, which can easily access through facebook APIs. Now lets say we want to do all the server-side jobs, with PHP and not flash: we don’t want to get the user-data we need from facebook-flash API, then send it all the way to the server and store it in the database, we want ALL the facebook/database related work, done on the server-side, with PHP. You should know, that you can access simple facebook library PHP code from flash, you need to authenticate first with the facebook function “set_user” with your user’s uid, and session key, that passed via the FBML tag in the flash vars. (for some strange reason, there is NO official documentation for this function AT ALL)

Now, flash needs to communicate with the server-side (POST requests for example). We can build our own dandy classes in PHP and AS3 (as I did in the beginning), but why? We shouldn’t spend precious time on this task when we have AMFPHP!

AMFPHP is a great open-source tool that allow flash to communicate with the server-side in a few lines of code! All you need to do, is of course, write the server-side functions, and then you can call it from your SWF, with Actionscript 3.

For example, if we want to get the user’s name from the server (using PHP and Facebook PHP-Platform), we need to create the following PHP class:

facebook = new Facebook($appapikey, $appsecret);
		$this->facebook->set_user($uid, $sessionKey);
		
		$name = $facebook->api_client->users_getInfo($uid, 'name');
		$name = $name[0];
		
		return "Hi," . $name . ", how do you do?";					
	}
}

?>

And save it in the “services” directory of AMFPHP, on our server. Now all we need to do is to call this function from our Actionscript 3 code, like this:

package {
	// required for flash file and output display
	import flash.display.MovieClip;
	import fl.events.*;
	import flash.events.*;
	// required to send/recieve data over AMF
	import flash.net.NetConnection;
	import flash.net.Responder;
	
	import flash.text.TextField;
 
	public class Main extends MovieClip {
		private var gateway:String = "path/to/gateway.php";
		private var connection:NetConnection;
		private var responder:Responder;
		private var response_text:TextField;
		
		public function Main() {
			// Responder to handle data returned from AMFPHP.
			this.responder = new Responder(this.onResult);
			this.connection = new NetConnection;
			// Gateway.php url for NetConnection
			this.connection.connect(this.gateway);
			
			this.respond_text = new TextField();
			addChild(this.response_txt);
			
			// Get the auth vars from the flash vars
			var sessionKey:String = LoaderInfo(this._root.loaderInfo).parameters.fb_sig_session_key;
			var uid:String = LoaderInfo(this._root.loaderInfo).parameters.fb_sig_user;
			
			// call remote function
			this.connection.call("HiWorld.sayHi", responder, uid, sessionKey);
		}
		
		// Handle an AMF call. This method is defined by the responder. 
		private function onResult(result:Object):void {
			this.response_txt.text = String(result);
		}
	}
}

In this tutorial, we use the NetConnection class to connect flash and PHP. Actually, the NetConnect is more like the “pipe” between them, as all the data passed with it. The first parameter for the “connect” method of our connection object, is the className.function to call, the second is the responder object, and the others are the parameters for the function. When you call the remote function, you can pass as many parameters to PHP as the function require. The responder is an object with a reference to a function, (simple and stupid ;) ) that will be invoked when the request completed. When we get the data from the server, the “onResult” function called, with the result parameter. The result paramter is an object that the server returned. Our function simply cast it to string and put it in our text field.

Note: AMFPHP is also ENCRYPT the data sent (vice-versa), and automatically decrypt it as well in the other side.

This way, we can access all the data that facebook supply… Now only the skies are the real limit… This is what I’ve done in snaker (Actually, I’ve built a Highscore class in AS, that handle all the highscore and facebook related data).

This was my first tutorial ever about AMFPHP and facebook! Feel free to send me feedback to yard2010[at]gmail[dot]com! I hope you learned something new =]

All the code above most be in it’s appropriate place: PHP on compatible server, and the SWF must run only in a facebook canvas page with the fb:swf FBML tag! »

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers