Documentation

Did you find this helpful?

Getting Started with Facebook & Unity

This guide shows example of PlayFab authentication using Facebook and Unity.

Requirements:

Implementation

Registering Facebook Application

Start by navigating to Facebook Developer Portal. Move your mouse over "My Apps" button (1, top right corner) and select "Add a New App" (2), as shown on the picture below:

A new application pop up will open. Enter a name for your application (1) and contact email (2). Make sure to come up with your own unique application name and email, as shown on the picture below:

Navigate to "Settings" tab (1), then to "Basic" sub-tab (2). Locate your Application ID. Copy it somewhere, we will use it later to set up the Facebook SDK:

Navigate to Facebook Access Token Tool and locate your app in the list (1). Make sure it has an assigned User Token (2). If not, request one using a button to the right. Refer to this page whenever you need fresh User Token. If auth fails during testing on PC, token expiration might be the most probable reason. Refresh the page to get a new User Token and test again.

On you application manager page, navigate to products (1) and locate "Facebook Login" entry and click "Get Started" (2):

A page with Login product settings should open. Make sure that you have Login product settings page is opened (1) and ensure Client and Web OAuth is on (2):

Setting up Facebook SDK 

Open your Unity project and select "Facebook" in the file menu (1). Then select "Edit Settings" (2).

Inspector window will show current Facebook SDK configuration. Enter your Application ID to the corresponding field, as shown on the picture below:

Simple authentication script

Create a new Game Object and rename to PlayfabFacebookAuthExample, as shown on the picture below:

Create a script called "PlayfabFacebookAuthExample.cs" (1) and add it to the game object (2) as shown on the picture below:

Inside  "PlayfabFacebookAuthExample.cs" place the following script

// Import statements introduce all the necessary classes for this example.
using Facebook.Unity;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine;
using LoginResult = PlayFab.ClientModels.LoginResult;

public class PlayfabFacebookAuthExample : MonoBehaviour
{
    // holds the latest message to be displayed on the screen
    private string _message;

    public void Start()
    {
        SetMessage("Initializing Facebook..."); // logs the given message and displays it on the screen using OnGUI method

        // This call is required before any other calls to the Facebook API. We pass in the callback to be invoked once initialization is finished
        FB.Init(OnFacebookInitialized);    
    }

    private void OnFacebookInitialized()
    {
        SetMessage("Logging into Facebook...");

        // Once Facebook SDK is initialized, if we are logged in, we log out to demonstrate the entire authentication cycle.
        if (FB.IsLoggedIn)
            FB.LogOut();

        // We invoke basic login procedure and pass in the callback to process the result
        FB.LogInWithReadPermissions(null, OnFacebookLoggedIn);
    }

    private void OnFacebookLoggedIn(ILoginResult result)
    {
        // If result has no errors, it means we have authenticated in Facebook successfully
        if (result == null || string.IsNullOrEmpty(result.Error))
        {
            SetMessage("Facebook Auth Complete! Access Token: " + AccessToken.CurrentAccessToken.TokenString + "\nLogging into PlayFab...");

            /*
             * We proceed with making a call to PlayFab API. We pass in current Facebook AccessToken and let it create 
             * and account using CreateAccount flag set to true. We also pass the callback for Success and Failure results
             */
            PlayFabClientAPI.LoginWithFacebook(new LoginWithFacebookRequest { CreateAccount = true, AccessToken = AccessToken.CurrentAccessToken.TokenString},
                OnPlayfabFacebookAuthComplete, OnPlayfabFacebookAuthFailed);
        }
        else
        {
            // If Facebook authentication failed, we stop the cycle with the message
            SetMessage("Facebook Auth Failed: " + result.Error + "\n" + result.RawResult, true);
        }
    }

    // When processing both results, we just set the message, explaining what's going on.
    private void OnPlayfabFacebookAuthComplete(LoginResult result)
    {
        SetMessage("PlayFab Facebook Auth Complete. Session ticket: " + result.SessionTicket);
    }

    private void OnPlayfabFacebookAuthFailed(PlayFabError error)
    {
        SetMessage("PlayFab Facebook Auth Failed: " + error.GenerateErrorReport(), true);
    }

    public void SetMessage(string message, bool error = false)
    {
        _message = message;
        if (error)
            Debug.LogError(_message);
        else
            Debug.Log(_message);
    }

    public void OnGUI()
    {
        var style = new GUIStyle { fontSize = 40, normal = new GUIStyleState { textColor = Color.white }, alignment = TextAnchor.MiddleCenter, wordWrap = true };
        var area = new Rect(0,0,Screen.width,Screen.height);
        GUI.Label(area, _message,style);
    }
}

Testing

Running the application in the editor

Hit the play button (1). Once Facebook is initialized and auth call is made, a Facebook auth dialog will appear in your game view. Enter the User Token (2) and hit "Send Success" button (3), as shown on the picture below:

Check the console output. It should render our debug statements, as shown on the picture below. If you see no errors, this means that authentication was succesful.

Running application on Android

Before launching the application on Android, you have to perform additional configuration steps.

First, you need to ensure you have Android platform selected and unique package ID set, as show on the picture below. Please, make sure to come up without your own unique package id:

Optionally, you need to install Open SSL and add it to the PATH enviroment variable. If it is missing, Unity will produce a harmless error during build. This error does not stop the build and does not effect the execution.

Next, in your Facebook Application Console, navigate to basic settings (1) and click "+ Add Platform" (2), as shown on the picture below:

Select Android from the list of available platforms, as shown on the picture below:

A panel with platform specific settings will appear. Fill in your package id and hit save. (Save button is hidden in the bottom right corner of the page.

Build and run the application normally on your Android Device. Application should welcome you with Facebook Sign In page. Once you sign in, watch the message on the screen changing. Finally, you should be presented with a message indicating succefull authentication in PlayFab. The entire procedure is illustrated on the picture below:

Running the application on iOS

Before launching the application on iOS, you have to perform additional configuration steps.

First, you need to ensure you have iOS platform selected and unique bundle ID set, as show on the picture below. Please, make sure to come up without your own unique package id:

Next, in your Facebook Application Console, navigate to basic settings (1) and click "+ Add Platform" (2), as shown on the picture below:

Select iOS from the list of available platforms, as shown on the picture below:

A panel with platform specific settings will appear. Fill in your bundle id and hit save. (Save button is hidden in the bottom right corner of the page.

Next, build the application as usual. Once this is done, open the project using XCode:

Click the Project to open Project settings. Verify the bundle identifier:

Make sure to select the correct device:

And select the correct Identity Team:

Finally, run the application as normal. Once started, application will allow you to log in to Facebook using web-browser. Once done, PlayFab authentication will be invoked and message will indicate the result:

Checking through PlayFab Game Manager

Open your PlayFab title game manager and navigate to dashboard. Refer to PlayStream Debugger panel to check for the latest events. You should locate Facebook authentication event as shown on the picture below:

At this point you have successfully integrated Facebook Authentication for PlayFab.



Did you find this helpful?