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:

  • 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.

Attention: The following concerns products or services (each a “Third Party Product”) that are not developed, owned, or operated by Unity. This information might not be up-to-date or complete, and is provided to you for your information and convenience only. Your access and use of any Third Party Product is governed solely by the terms and conditions of such Third Party Product. Unity makes no express or implied representations or warranties regarding such Third Party Products, and will not be responsible or liable, directly or indirectly, for any actual or alleged damage or loss arising from your use thereof (including damage or loss arising from any content, advertising, products or other materials on or available from the provider of any Third Party Products).

Set up a Facebook account sign-in

  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.

Unity Authentication supports Limited Login. This is the default on iOS unless your app is compliant with Apple's App Tracking Transparency (ATT) privacy protection framework, and the player has consented. If you are building for iOS devices, please take note of the section below on handling Limited Login.

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.

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 MonoBehaviour
    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 token)
{
    try
    {
        await AuthenticationService.Instance.SignInWithFacebookAsync(token);
        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 Player section.

async Task LinkWithFacebookAsync(string token)
{
    try
    {
        await AuthenticationService.Instance.LinkWithFacebookAsync(token);
        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 token)
{
    try
    {
        await  AuthenticationService.Instance.SignInWithFacebookAsync(token);
        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()
{
   try
   {
       await AuthenticationService.Instance.UnlinkFacebookAsync();
       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);
   }
}

Handle Facebook Limited Login on iOS devices

iOS 14 and later requires publishers to obtain permission to track the user's device across applications. This device setting is called App Tracking Transparency, or ATT. Please see Apple's documentation for more details. Without explicit consent, the Facebook SDK will default to the Facebook Limited Login flow. This provides a slightly different token, but it can still be used by Unity Authentication to associate a player.

To help with this integration, Unity provides an optional iOS support package which supports requesting consent and querying the consent status. It can be found in the Unity editor Package Manager as com.unity.ads.ios-support. For more details please refer to the package documentation and the App Tracking Transparency compliance page from the Unity Ads documentation.

On login if consent has been granted, then the global AccessToken instance should be used as normal for the call to Unity Autentication. But if the player has not explicitly consented, then you will need to use the AuthenticationToken from the callback result instead. Both AccessToken and AuthenticationToken may appear to be available at all times, but if the wrong one is used then the Unity Authentication service will not be able to verify the token and will return an error.

The following snippet is equivalent to the login examples above, except that it uses the iOS support package to request consent from the player, and uses the ATT status to select the appropriate token for signing in with Unity Authentication.

using System;
using UnityEngine;
using Unity.Services.Core;
using Unity.Services.Authentication;

// Other needed dependencies, including the iOS support package
using Facebook.Unity;
using Unity.Advertisement.IosSupport;

public class FacebookExampleScriptWithIosAttHandling : MonoBehaviour
{
    async void Awake()
    {
        // This will prompt the player to consent to tracking when the app is first launched.
        // Only include this line here if it is not otherwise requested already.
        ATTrackingStatusBinding.RequestAuthorizationTracking();

        // Initialize Unity services
        await UnityServices.InitializeAsync();
        Debug.Log($"Unity services initialization: {UnityServices.State}");

        if (!FB.IsInitialized)
        {
            // Initialize the Facebook SDK
            FB.Init(FbInitCallback, OnHideUnity);
        }
        else
        {
            // Already initialized, signal an activation App Event
            FB.ActivateApp();
        }
    }

    void FbInitCallback()
    {
        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)
    {
        // Pause or resume the game depending on focus
        Time.timeScale = isGameShown ? 1 : 0;
    }

    // Call this from a button or similar
    public void LoginWithAttHandling()
    {
        FB.LogInWithReadPermissions(null, result =>
        {
            if (FB.IsLoggedIn)
            {
                // Check ATT status to determine which token to use.
                // The states include AUTHORIZED, RESTRICTED, NOT_DETERMINED, and DENIED.
                if (ATTrackingStatusBinding.GetAuthorizationTrackingStatus() ==
                    ATTrackingStatusBinding.AuthorizationTrackingStatus.AUTHORIZED)
                {
                    Debug.Log("[Facebook Login] Using standard access token");
                    SignInWithFacebookAsync(AccessToken.CurrentAccessToken.TokenString);
                }
                else
                {
                    Debug.Log("[Facebook Login] Using Limited Login authentication token");
                    SignInWithFacebookAsync(result.AuthenticationToken.TokenString);
                }
            }
            else
            {
                Debug.Log("[Facebook Login] User cancelled login from within Facebook flow");
            }
        });
    }

    async void SignInWithFacebookAsync(string token)
    {
        try
        {
            await AuthenticationService.Instance.SignInWithFacebookAsync(token);
            Debug.Log("Unity SignIn is successful.");
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
        }
    }
}