# Facebook

> Provide a Facebook sign-in option to enable players to authenticate using their Facebook accounts in your game.

###### 最小 SDK バージョン: 2.0.0##minimum-sdk-version-200

このセクションでは、Facebook アカウントを使用してゲーム内でのプレイヤーの認証を設定する以下のシナリオについて説明します。

> **Note:**
>
> **ノート**: 以下のコード例は、プレイヤーの Facebook アクセストークンをすでに取得済みであることを前提としています。
>
> * Facebook アカウントサインインを設定する
> * 戻ってきたプレイヤーをサインインする、または新しいプレイヤーを作成する。
> * 匿名ログインから Facebook アカウントを介したプラットフォームログインへとプレイヤーを更新する。

ゲーム内のプレイヤーに Facebook サインインのオプションを提供するには、Facebook 開発者ポータルでアプリケーションを作成し、[Facebook SDK for Unity](https://developers.facebook.com/docs/unity/downloads) をインストールしてプレイヤーをサインインし、アクセストークンを取得してください。

## Facebook アカウントサインインを設定する

以下の手順では、Facebook アプリケーションを設定済みであることを前提としています。

1. [Facebook の入門ドキュメント](https://developers.facebook.com/docs/unity/gettingstarted) に従って、Facebook SDK を設定し、インストールします。

2. Facebook を Unity Authentication 用の ID プロバイダーとして追加します。

   1. Unity エディターメニューで、**Edit** (編集) > **Project Settings...** (プロジェクト設定...) を選択し、ナビゲーションメニューから **Services** (サービス) > **Authentication** を選択します。
   2. **ID Providers** (ID プロバイダー) を **Facebook** に設定し、**Add** (追加) をクリックします。
   3. App ID テキストフィールドにアプリケーション ID (ステップ 1 で確認) を入力します。
   4. **App Secret** テキストフィールドにアプリケーションシークレットを入力し、**Save** (保存) をクリックします。

3. [こちらのサンプルコードを使用](https://developers.facebook.com/docs/unity/examples#login) して Facebook サインインを実装します。

   > **Note:**
   >
   > **ノート**: Unity Authentication SDK では現在、エクスプレスサインイントークンはサポートされていません。

> **Note:**
>
> **ノート**: Facebook SDK は Unity 2021.1 の再生モードで動作しません。[こちらの GitHub の問題](https://github.com/facebook/facebook-sdk-for-unity/issues/537) で追跡されています。回避策として、[こちらの Pull requests を使用](https://github.com/facebook/facebook-sdk-for-unity/pull/539/files) して新しい Facebook.Unity.dll をビルドしてください。

> **Note:**
>
> 現時点では、"コンシューマー" および "ビジネス" アプリケーションタイプがサポートされています。

```cs
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

`SignInWithFacebookAsync` メソッドを使用して、以下のいずれかを行うことができます。

* Facebook の認証情報を使用して新しい Unity Authentication プレイヤーを作成する。
* Facebook の認証情報を使用して既存のプレイヤーをサインインする。

プロジェクト内の Unity Authentication プレイヤーが認証情報と関連付けられていない場合、`SignInWithFacebookAsync` は新しいプレイヤーを作成します。プロジェクト内の Unity Authentication プレイヤーが認証情報と関連付けられている場合、`SignInWithFacebookAsync` はそのプレイヤーのアカウントにサインインします。この関数ではキャッシュされたプレイヤーは考慮されません。`SignInWithFacebookAsync` はキャッシュされたプレイヤーを置き換えます。

```cs
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);
    }
}
```

## プレイヤーを匿名から Facebook アカウントへと更新する##update-a-player-from-anonymous-to-a-facebook-account

匿名認証を設定した後、プレイヤーが匿名からアップグレードし、Facebook アカウントを作成して Facebook を使用してサインインすることを希望する場合は、ゲームのプレイヤーにプロンプトを表示し、Facebook サインインをトリガーして Facebook からアクセストークンを取得するよう求める必要があります。その後、`LinkWithFacebookAsync` API を呼び出して、プレイヤーを Facebook アクセストークンにリンクします。

キャッシュされたプレイヤーが SDK に存在する場合は、キャッシュされたプレイヤーを Facebook アカウントにリンクできます。

1. `SignInAnonymouslyAsync` を使用して、キャッシュされたプレイヤーのアカウントにサインインします。
2. `LinkWithFacebookAsync` を使用して、キャッシュされたプレイヤーのアカウントを Facebook アカウントにリンクします。

```cs
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);
    }
}
```

プレイヤーがサインインするか新しいプレイヤープロファイルを作成して Facebook サインインをトリガーする場合、Facebook アクセストークンを受け取ったら、以下の API を呼び出してプレイヤーの認証を行います。

```cs
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);
    }
}
```

## Facebook サインイン認証を実装する##implement-a-facebook-sign-in-authentication

プレイヤーが Facebook サインインをトリガーしてサインインするか新しいプレイヤーを作成する場合、Facebook アクセストークンを受け取ったら、以下の API を呼び出してプレイヤーをサインインします: `SignInWithFacebookAsync(string accessToken)`。

## Facebook アカウントをリンク解除する##unlink-facebook-account

`UnlinkFacebookAsync` API を使用して、プレイヤーが自身の Facebook アカウントをリンク解除できるようにします。リンク解除後、そのアカウントが他のどの ID にもリンクされていない場合、そのアカウントは匿名アカウントに遷移します。

```cs
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);
   }
}
```
