Facebook

Minimum SDK version: 2.0.0

This article guides you through the following scenarios in setting up authentication for players in your game with a Facebook account:

Note: The code example below assumes you already have the player's Facebook Access Token.

  • Set up a Facebook account sign-in
  • Sign in a returning user or create new user.
  • Updating a user from an anonymous sign-in to a platform sign-in via a Facebook account.

To provide a Facebook sign-in option for the players in your game, create an app in the Facebook Developer Portal and install Facebook's Unity SDK to sign in the user and get the access token.

Set up a Facebook account sign-in

These steps assume you have set up a Facebook App.

  1. Set up and install the Facebook SDK following Facebook’s getting started documentation.

  2. Add Facebook as an Id Provider for Unity Authentication:

    1. In the Unity Editor menu, go to Edit > Project Settings…, then select Services > Authentication from the navigation menu.
    2. Set ID Providers to Facebook, then click Add.
    3. Enter the app ID (found in step 1) in the App ID text field.
    4. Enter the app secret in the App Secret text field, then click Save.
  3. Implement the Facebook login using this sample code.

    Note: The Unity Authentication SDK doesn't currently support express login tokens.

Note: The Facebook SDK doesn't work with Unity 2021.1 in play mode, as tracked in this Github issue. As a workaround, build a new Facebook.Unity.dll using this pull request.

We currently support the ‘Consumer’ and ‘Business’ app types.

The referenced package is not developed, owned, or operated by Unity. Please refer to our best practices for working with non-Unity packages.

using System.Collections.Generic;
using UnityEngine;

// Other needed dependencies
using Facebook.Unity;

public class FacebookExampleScript : MonoBehaviour
{
    public string Token;
    public string Error;

    // Awake function from Unity's MonoBehavior
    void Awake()
    {
        if (!FB.IsInitialized)
        {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        }
        else
        {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
    }

    void InitCallback()
    {
        if (FB.IsInitialized)
        {
            // Signal an app activation App Event
            FB.ActivateApp();
            // Continue with Facebook SDK
        }
        else
        {
            Debug.Log("Failed to Initialize the Facebook SDK");
        }
    }

    void OnHideUnity(bool isGameShown)
    {
        if (!isGameShown)
        {
            // Pause the game - we will need to hide
            Time.timeScale = 0;
        }
        else
        {
            // Resume the game - we're getting focus again
            Time.timeScale = 1;
        }
    }

    public void Login()
    {
        // Define the permissions
        var perms = new List<string>() { "public_profile", "email" };

        FB.LogInWithReadPermissions(perms, result =>
        {
            if (FB.IsLoggedIn)
            {
                Token = AccessToken.CurrentAccessToken.TokenString;
                Debug.Log($"Facebook Login token: {Token}");
            }
            else
            {
                Error = "User cancelled login";
                Debug.Log("[Facebook Login] User cancelled login");
            }
        });
    }
}

Sign in a returning player or create new player

You can use the SignInWithFacebookAsync method to either:

  • Create a new Unity Authentication player with the Facebook credentials.
  • Sign in an existing player using the Facebook credentials.

If no Unity Authentication player in your project is associated with the credentials, SignInWithFacebookAsync creates a new player. If a Unity Authentication player in your project is associated with the credentials, SignInWithFacebookAsync signs into that player's account. This function doesn't consider the cached player, and SignInWithFacebookAsync replaces the cached player.

async Task SignInWithFacebookAsync(string accessToken)
{
    try
    {
        await AuthenticationService.Instance.SignInWithFacebookAsync(accessToken);
        Debug.Log("SignIn is successful.");
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}

Update a player from anonymous to a Facebook account

After you’ve set up anonymous authentication, if the player wants to upgrade from being anonymous to creating a Facebook account and sign in using Facebook, the game should prompt the player to trigger the Facebook login and get the access token from Facebook. Then, call the LinkWithFacebookAsync API to link the player to the Facebook Access token.

If a cached player exists on the SDK, you can link the cached player to the Facebook Account.

  1. Sign into the cached player's account using SignInAnonymouslyAsync.
  2. Link the cached player's account to the Facebook account with LinkWithFacebookAsync.

For more information about cached players, please read the Sign In a Cached User section.

async Task LinkWithFacebookAsync(string accessToken)
{
    try
    {
        await AuthenticationService.Instance.LinkWithFacebookAsync(accessToken);
        Debug.Log("Link is successful.");
    }
    catch (AuthenticationException ex) when (ex.ErrorCode == AuthenticationErrorCodes.AccountAlreadyLinked)
    {
        // Prompt the player with an error message.
        Debug.LogError("This user is already linked with another account. Log in instead.");
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}

When the player triggers the Facebook login by signing in or by creating a new player profile, and you have received the Facebook access token, call the following API to authenticate the player.

async Task SignInWithFacebookAsync(string accessToken)
{
    try
    {
        await  AuthenticationService.Instance.SignInWithFacebookAsync(accessToken);
        Debug.Log("SignIn is successful.");
    }
    catch (AuthenticationException ex)
    {
        // Compare error code to AuthenticationErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        // Compare error code to CommonErrorCodes
        // Notify the player with the proper error message
        Debug.LogException(ex);
    }
}

Implement a Facebook sign-in authentication

When the player triggers the Facebook login to login or create a new player, and you have received the Facebook access token, call the following API to sign-in the player: SignInWithFacebookAsync(string accessToken).

Use the UnlinkFacebookAsync API so your players can unlink their Facebook account. Once unlinked, if their account isn’t linked to any additional identity, it transitions to an anonymous account.

async Task UnlinkFacebookAsync(string idToken)
{
   try
   {
       await AuthenticationService.Instance.UnlinkFacebookAsync(idToken);
       Debug.Log("Unlink is successful.");
   }
   catch (AuthenticationException ex)
   {
       // Compare error code to AuthenticationErrorCodes
       // Notify the player with the proper error message
       Debug.LogException(ex);
   }
   catch (RequestFailedException ex)
   {
       // Compare error code to CommonErrorCodes
       // Notify the player with the proper error message
       Debug.LogException(ex);
   }
}