Facebook Integration

Share, login and invite friends without Unity Facebook SDK

Bundled inside the Gamedonia SDK you will find a Facebook plugin that will allow you to perform all the operations that are specified at the Facebook Graph API. This plugin is meant as a complement to the Gamedonia SDK, simply use it if you need it.

Setup

Depending on the platform, the setup process can vary a bit. We will start explaining the common part of the setup for all SDKs.

Common setup

First, we need to create a new project at the Facebook Developers portal. Currently, the default option for creating a new app on the Facebook portal is a wizard, but you can skip this by clicking in the Advanced Setup option and you'll get a Facebook App ID with a blank app (no platform selected yet).

Click the Settings option in your Facebook app left sidebar and click on the + Add Platform button. You should add your desired mobile platforms (right now our plugin supports iOS and Android).

The information you need to fill for each platform is explained by client technology in the Specific setup section that follows next on this page.

Finally, you have to initialize the Facebook plugin with a single line of code. In your initial game scene in the Awake() method add:

void Awake() {

FacebookBinding.Init("<your-facebook-app-id>");

}

Remember to set your Facebook app as available to the general public once your're done developing and testing with your designated test users.

If you don't do that, an external user won't be able to connect to your Facebook app.

Specific setup

Find out what information you have to fill depending on the client technology:

Plugin Interface

The Facebook SDK shows the following interface for operating with Facebook and its Graph API.

Init

It's the function used to initialize the Facebook SDK. Calling this function is mandatory before doing any other calls to any other function. If the Facebook plugin is not initialized all the other calls will fail.

public static void Init(string appID, string urlSchemeSuffix = "", bool frictionless = true)
			public function init(appID:String, urlSchemeSuffix:String=null, frictionless:Boolean = false) : void
	

Parameters

  • appID - Mandatory. The Facebook App ID that you can get from the Facebook Developers portal.
  • urlSchemeSuffix - Optional. Allows you to specify a custom url scheme. iOS supports the URL scheme protocol to handle requests between apps (something that is needed between your app and the Facebook official app).
  • frictionless - Optional. Frictionless requests allow players to send requests to specific friends from the app without having to click a pop-up confirmation each time.

IsSessionOpen

Returns a boolean value indicating whether we have a current valid Facebook session or not. Do not confuse this with the Gamedonia session, you need both sessions open.

public static bool IsSessionOpen()
			public function isSessionOpen() : Boolean
	

Parameters

No parameters needed.

GetAccessToken

Returns a string with the current access token associated to the Facebook session on the device. You'll need this value to start a session on Gamedonia using Facebook credentials.

public static string GetAccessToken()
			// accessToken is a class attribute
			accessToken : String
	

Parameters

No parameters needed.

isFacebookTokenValid

Checks whether the specified access token is valid or not.

public static void isFacebookTokenValid(string accessToken, Action callback)

Parameters

  • accessToken - String type. The Facebook access token you want to check.
  • callback
    • success - Bool type. Indicates whether the operation worked correctly.

OpenSessionWithReadPermissions

Starts a Facebook session with the specified read permissions. Remember that Facebook doesn't recommend you to ask for read and write permissions on the first call to open a session.

public static void OpenSessionWithReadPermissions(string [] permissions, Action<bool,bool,string> callback = null, bool allowUI = true)
			public function OpenSessionWithReadPermissions(permissions:Array, callback:Function=null, allowUI:Boolean = true) : void
	

Parameters

  • permissions - Mandatory. A list of Facebook permissions that we are requesting to the user to grant to our game. More details in the official Permissions with Facebook Login guide.
  • callback - Optional. The function that will be called as the result of the Open session operation. The callback takes 3 parameters:
    • success - Bool type. Indicates whether the operation worked correctly.
    • userCancelled - Bool type. Indicates whether the user cancelled the Facebook login process intentionally.
    • message - String type. Detailed error message when the success parameter is false.
  • allowUI - Optional. Indicates whether the plugin can show the Facebook login dialog in full screen.

OpenSessionWithPublishPermissions

Starts a Facebook session with the specified publish permissions. Remember that Facebook doesn't recommend you to ask for read and write permissions on the first call to open a session. The recommendation is to start by asking the user for read permissions, and in case that some publish operation is needed, reauthorize the user with publish permissions afterwards. That's because the process of granting publish permissions in Facebook requires more steps that the user has to accept.

public static void OpenSessionWithPublishPermissions(string [] permissions, Action<bool,bool,string> callback = null)
	public function OpenSessionWithPublishPermissions(permissions:Array, callback:Function=null) : void
	

Parameters

  • permissions - Mandatory. A list of Facebook permissions that we are requesting to the user to grant to our game. More details in the official Permissions with Facebook Login guide.
  • callback - Optional. The function that will be called as the result of the Open session operation. The callback takes 3 parameters:
    • success - Bool type. Indicates whether the operation worked correctly.
    • userCancelled - Bool type. Indicates whether the user cancelled the Facebook login process intentionally.
    • message - String type. Detailed error message when the success parameter is false.
  • allowUI - Optional. Indicates whether the plugin can show the Facebook login dialog in full screen.

ReauthorizeSessionWithReadPermissions

Reauthorizes a current Facebook open session with the specified read permissions. This allows you to split the process of asking for read and publish permissions to the user. This is the recommended behavior by Facebook.

public static void ReauthorizeSessionWithReadPermissions(string [] permissions, Action<bool,bool,string> callback = null)
			public function ReauthorizeSessionWithReadPermissions(permissions:Array, callback:Function=null) : void
	

Parameters

  • permissions - Mandatory. A list of Facebook permissions that we are requesting to the user to grant to our game. More details in the official Permissions with Facebook Login guide.
  • callback - Optional. The function that will be called as the result of the Open session operation. The callback takes 3 parameters:
    • success - Bool type. Indicates whether the operation worked correctly.
    • userCancelled - Bool type. Indicates whether the user cancelled the Facebook login process intentionally.
    • message - String type. Detailed error message when the success parameter is false.

ReauthorizeSessionWithPublishPermissions

Reauthorizes a current Facebook open session with the specified publish permissions. This allows you to split the process of asking for read and publish permissions to the user. This is the recommended behavior by Facebook.

public static void ReauthorizeSessionWithPublishPermissions(string [] permissions, Action<bool,bool,string> callback = null)
public function ReauthorizeSessionWithPublishPermissions(permissions:Array, callback:Function=null) : void
	

Parameters

  • permissions - Mandatory. A list of Facebook permissions that we are requesting to the user to grant to our game. More details in the official Permissions with Facebook Login guide.
  • callback - Optional. The function that will be called as the result of the Open session operation. The callback takes 3 parameters:
    • success - Bool type. Indicates whether the operation worked correctly.
    • userCancelled - Bool type. Indicates whether the user cancelled the Facebook login process intentionally.
    • message - Stringtype. Detailed error message when the success parameter is false.

CloseSessionAndClearTokenInformation

Closes the current Facebook open session and clears the access token from the cache. Use this function when you want the user to be completely logged out from Facebook. The next time the user tries to access your game with Facebook he will need to complete an extended Facebook login flow in order to acquire a new access token.

If this method is not invoked when the user re-enters your game, he probably won't notice that a Facebook session has been initiated because we still keep a valid access token, and Facebook can silently reinitiate a session without annoying the user.

public static void CloseSessionAndClearTokenInformation()
			public function CloseSessionAndClearTokenInformation() : void
		

Parameters

No parameters needed.

RequestWithGraphPath

This function is your gateway to the Facebook Graph API. The Facebook Graph API is the primary way to get data in and out of the Facebook social graph. It's a low-level HTTP-based API that you can use to query data, post new stories, upload photos, and a variety of other tasks that an app might need to do.

public static void RequestWithGraphPath(string graphPath, IDictionary parameters = null, string httpMethod = "GET", Action<IDictionary> callback = null)
			public function RequestWithGraphPath( graphPath:String, parameters:Object = null, httpMethod:String = "GET", callback:Function = null) : void
		

Parameters

  • graphPath - Mandatory. The Facebook graph path we want to invoke. More details in the official Using the Graph API guide from Facebook.
  • parameters - Optional. The parameters we want to send to the graph path. Each graph path can take different parameters so take a look at the Facebook guide for each call.
  • httpMethod - Each graph API path uses a diferent http method that must be specified in the call. If it's not specified correctly, the call will not match any endpoint of the Facebook graph API and the call will fail.
  • callback - The function that will be called as the result of the operation with the graph API. If you expect to get data back from Facebook the data will be inside the map under the key "data".

Dialog

The Facebook SDK offers a number of built-in controls and dialogs to speed up the integration process. Use this method to access the dialogs provided by Facebook.

			public static void Dialog(string method, IDictionary parameters = null, bool allowNativeUI = true, Action<IDictionary> callback = null)
			public function Dialog(method:String, parameters:Object, callback:Function = null, allowNativeUI:Boolean=true) : void
		

Parameters

  • method - Mandatory. The API dialog method we want to invoke (Share, Feed, etc).
  • parameters - Optional. The parameters we want to send to the dialog. Each dialog can take different parameters, so take a look at the Facebook guide for each dialog.
  • allowNativeUI - It indicates whether the Facebook SDK can operate in full screen mode.
  • callback - The function that will be called as the result of the operation with the graph API. If you expect to get data back from Facebook the data will be inside the map under the key "data".

Examples

Let's take a closer look at some of the most common use cases using Facebook with Gamedonia.

Remember to initialize the Facebook plugin by calling Init mentioned above before using any of the Facebook calls in these examples.

Login with Facebook

To login a user on Gamedonia using Facebook credentials you need to follow a 2-step process:

  1. First we need to get a valid fbuid and accessToken from Facebook.
  2. Ask Gamedonia to initiate a session using those credentials.

Get Facebook credentials

To get valid Facebook credentials we need to open a session with Facebook. For example, imagine you have added a button in your login screen called Facebook Login that will start a Facebook authentication process in Gamedonia using Facebook credentials. You can open the Facebook session by doing:

// Read permission we want the user to grant us
private static string [] READ_PERMISSIONS = new string[] {"read_stream", "read_friendlists"};

// Using the Unity GUI Api we could handle the click to the Facebook Login button like this, see the Simple Login sample.
if (GUI.Button (UtilResize.ResizeGUI(new Rect (80,205, 220, 50)), "Facebook Login",fbButton)) {

    FacebookBinding.OpenSessionWithReadPermissions(READ_PERMISSIONS, OnFacebookOpenSession);

}

// Callback handler for the OpenSession call
void OnFacebookOpenSession(bool success, bool userCancelled, string message) {

    if (success) {
        // Now that we have a valid session we have an accessToken but we still need the user fbuid so we call the graph api to get it.
        FacebookBinding.RequestWithGraphPath("/me",null,"GET",OnFacebookMe);				
     } else {
        Debug.Log("Unable to open session with Facebook");
     }
}

private void OnFacebookMe(IDictionary data) {

     // Extract some needed data from the Facebook response to the Graph API
     string fbUserId = data ["id"] as string;
     string fbUserName = data ["name"] as string;
     Debug.Log ("AccessToken: " + FacebookBinding.GetAccessToken() + " fbuid: " + fbUserId);

     // Login to Gamedonia call should be here now that you have the Facebook credentials!.

}
private static var fb:Facebook;
private static const READ_PERMISSIONS:Array = ["read_stream", "read_friendlists"];

fb = Facebook.getInstance();
fb.logEnabled = true; 
fb.init(FACEBOOK_APP_ID, null, true);

protected function facebook_onClickfacebook(event:MouseEvent) : void {
	
	if ( fb.isSessionOpen ) {

		onFacebookOpenSession(true, true, null);
		
	} else {

		fb.openSessionWithReadPermissions(READ_PERMISSIONS, onFacebookOpenSession, true);
	}
}

protected function onFacebookOpenSession($success:Boolean, $userCancelled:Boolean, $error:String):void {
	if ($success) {

		fb.requestWithGraphPath("/me", null, "GET", onFacebookMe);
		
	} else {
		
		trace($error);
		trace($userCancelled);
	}
}

protected function onFacebookMe(data:Object):void {

	// Extract some needed data from the Facebook response to the Graph API
	var fb_name:String = data.name; 
	var fb_uid:String = data.id;
	var fb_access_token:String = fb.accessToken;

	trace("AccessToken: " + fb.accessToken + " fbuid: " + fbUserId);

	 // Login to Gamedonia call should be here now that you have the Facebook credentials!

}
	

Start a Gamedonia Session with Facebook Credentials

In this second step we will use the data recovered from Facebook to authenticate the user against Gamedonia. With just a few lines of code you'll be able to do it.

// We have added some more lines to this method. 
private void OnFacebookMe(IDictionary data) {

     // Extract some needed data from the Facebook response to the Graph API
     string fbUserId = data ["id"] as string;
     string fbUserName = data ["name"] as string;
     Debug.Log ("AccessToken: " + FacebookBinding.GetAccessToken() + " fbuid: " + fbUserId);

     // Setup a Dictionary with the Facebook credentials to call Gamedonia Login process. Dictionary key names are very important take care.
     Dictionary<string,object> facebookCredentials = new Dictionary<string,object> ();
     facebookCredentials.Add("fb_uid",fbUserId);
     facebookCredentials.Add("fb_access_token",FacebookBinding.GetAccessToken());
		
     // Authenticate method will do the job of registering and login the user to be able to start working with Gamedonia!
     GamedoniaUsers.Authenticate (Gamedonia.CredentialsType.FACEBOOK,facebookCredentials, OnFacebookLogin);

}

void OnFacebookLogin (bool success) {
		
    if (success) {			
        Debug.Log("Login worked!!");
        //TODO Put your login success behavior here. 

    }else {
        Debug.Log("Login failed");
    }

}
protected function onFacebookMe(data:Object):void {

	var fb_name:String = data.name; 
	var fb_uid:String = data.id;
	var fb_access_token:String = fb.accessToken;
	
	var credentials:Credentials = new Credentials();
	credentials.fb_uid = fb_uid;
	credentials.fb_access_token = fb_access_token;

	var user:GDUser = new GDUser();
	user.credentials = credentials;
	user.profile.nickname = fb_name;

	GamedoniaUsers.createUser(user, function (success:Boolean):void {

		GamedoniaUsers.loginUserWithFacebook(fb_uid, fb_access_token, onFacebookLogin);
	});
}

protected function onFacebookLogin(success:Boolean):void {
	
	if (success) {
		trace("Login worked!!");
		// TODO Put your login success behavior here.
		
	} else {
		
		trace("Login failed");
	}
}
	

Get Facebook Friends

With this call you'll get the Facebook friends of the user that also have the same app. You only need a call to the Facebook Graph API.

void GetFriendsClick() {
    FacebookBinding.RequestWithGraphPath ("/me/friends",null,"GET",OnFriends);
}

private void OnFriends(IDictionary data) {
    Debug.Log ("I have: " + (data["data"] as IList).Count +  " Facebook friends");
}
protected function GetFriendsClick() : void {

    fb.requestWithGraphPath("/me/friends", null, "GET", onFriends);
}

protected function onFriends(res:Object) : void {
	
	trace ("I have: " + res.data.length +  " Facebook friends");
}
	

Request with parameters

This is how you should call the Graph API using parameters to specify your request. For instance, if you want to obtain information from the user's profile specifying which fields you're interested in, you can do it like this:

void GetMeWithParameters() {

	IDictionary parameters = new Dictionary<string,object>();
	parameters.Add("fields","id,first_name,gender,locale,email,picture");

	FacebookBinding.RequestWithGraphPath("/me",parameters,"GET",OnFacebookMe);
}

private void OnFacebookMe(IDictionary data) {
    // Your data processing
}

Share Dialog

Here's an example on how to open the Facebook Share dialog to share scores or other information with friends.

void ShareFacebookClick() {

    IDictionary parameters = new Dictionary<string,object> ();
    parameters.Add ("app_id","<your-facebook-app-id>");
    parameters.Add ("from", "<currently-logged-in-fbuid>");
    parameters.Add ("link", "<link-to-the-shared-content>");
    FacebookBinding.Dialog ("feed", parameters, true, OnShare);

}

private void OnShare(IDictionary data) {
    // TODO probably u don't need to do anything here
}
protected function ShareFacebookClick() : void {

	var parameters:Object = new Object();

	parameters.app_id = "<your-facebook-app-id>";
	parameters.from = "<currently-logged-in-fbuid>";
	parameters.link = "<link-to-the-shared-content>";

	fb.dialog("feed", parameters, onShare, true);

}

protected function onShare(data:Object):void {
				
	// TODO probably u don't need to do anything here
}
	

App Request Dialog

This is an example on how to open the Facebook App Request dialog with the to field pre filled.

void RequestFacebookClick() {

    IDictionary parameters = new Dictionary<string,object> ();
    parameters.Add ("app_id", "<your-facebook-app-id>");
    parameters.Add ("message","Some text to show on the request");
    parameters.Add ("to","<fbuid-of-the-request-destinatary>");
    FacebookBinding.Dialog ("apprequests", parameters, true, OnRequest);

}

private void OnRequest(IDictionary data) {
    // TODO probably u don't need to do anything here
}
protected function RequestFacebookClick() : void {

	var parameters:Object = new Object();

	parameters.app_id = "<your-facebook-app-id>";
	parameters.message = "Some text to show on the request";
	parameters.to = "<fbuid-of-the-request-destinatary>";

	fb.dialog("apprequests", parameters, onRequest, true);
}

protected function onRequest(data:Object):void {
				
	// TODO probably u don't need to do anything here
}
	

Now we've covered some common usage scenarios with Facebook. Have in mind that the Facebook API is huge. The best place to explore all the possibilities it offers is the Facebook developer documentation, where all the possible usages of their API are explained. Remember, Facebook developers documentation is a good place to start.