# Google Play Games

> Provide a Google Play Games sign-in option to provide a frictionless authentication experience for Android players.

###### SDK 最低版本：2.1.0##minimum-sdk-version-210

本文将引导您完成以下场景，为您游戏中使用 Google Play Games 帐户的玩家设置身份验证：

**注意**：下方代码示例的前提为，您已经有玩家一次性授权码。

* 设置 Google Play Games 登录。
* 回归用户登录或创建新用户。
* 将用户从匿名登录更新为通过 Google Play Games 帐户进行平台登录。

要在您的游戏中为玩家提供 Google Play Games 登录选项，请在 Google Play Console 中创建应用，并安装 Google Play Games plugin for Unity v11.01+，以登录用户帐户，获取一次性授权码。

> **Warning:**
>
> 对于运行 v10.14 和更早版本的插件版本，请参阅关于 [Google ID 提供商](./google.md)的文章。

## 设置 Google Play Games 登录

**注意**：Google Play Games 登录仅与 Android 设备兼容。

**注意**：Google Play Games 登录由 [Google Play Games plugin for Unity v11.01](https://github.com/playgameservices/play-games-plugin-for-unity/releases/tag/v0.11.01) 和更高版本提供支持，建议您使用 Play Games Services v2 SDK。

1. 下载并导入 [Google Play Games Plugin for Unity](https://github.com/playgameservices/play-games-plugin-for-unity/tree/master/current-build)。

2. 设置您的应用以启用 Google 登录。参阅 Google 文档，了解如何[为 Google 登录配置您的游戏](https://developer.android.com/games/pgs/unity/unity-start)。

3. 将 Unity Authentication 中的 ID 提供商设置为 Google：

   1. 在 Unity 编辑器菜单中，访问 **Edit（编辑）**> **Project Settings…（项目设置…）**，然后从导航菜单中选择 **Services（服务）**> **Authentication（身份验证）**。

   2. 将 **ID Providers（ID 提供商）** 设置为 **Google Play Services（Google Play 服务）**，然后单击 **Add（添加）**。

   3. 在 **Client ID（客户端 ID）** 文本字段中输入 **Web App client ID（Web 应用客户端 ID）**。

   4. 在 **Client Secret（客户端密钥）** 文本字段中，输入 **Web App client secret（Web 应用客户端密钥）**，然后选择 **Save（保存）**。

      > **Note:**
      >
      > **注意**：您必须在插件设置对话框中设置 **Web App client ID（Web 应用客户端 ID）** 才能使用 Authentication SDK。

根据以下样本代码执行 Google Play Games 登录：

```cs
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine;

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

    void Awake()
    {
        //Initialize PlayGamesPlatform
        PlayGamesPlatform.Activate();
        LoginGooglePlayGames();
    }

    public void LoginGooglePlayGames()
    {
        PlayGamesPlatform.Instance.Authenticate((success) =>
        {
            if (success == SignInStatus.Success)
            {
                Debug.Log("Login with Google Play games successful.");

                PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
                {
                    Debug.Log("Authorization code: " + code);
                    Token = code;
// This token serves as an example to be used for SignInWithGooglePlayGames
                });
            }
            else
            {
                Error = "Failed to retrieve Google play games authorization code";
                Debug.Log("Login Unsuccessful");
            }
        });
    }
}
```

## 回归玩家登录或创建新玩家##sign-in-a-returning-player-or-create-new-player

您可以使用 `SignInWithGooglePlayGamesAsync` 方法执行以下操作之一：

* 通过 Google Play Games 凭据创建新的 Unity Authentication 玩家帐户。
* 通过 Google Play Games 凭据登录现有玩家帐户。

如果您的项目中没有与凭据关联的 Unity Authentication 玩家帐户，`SignInWithGooglePlayGamesAsync` 将创建新的玩家帐户。如果您的项目中具有与凭据关联的 Unity Authentication 玩家帐户，`SignInWithGooglePlayGamesAsync` 将登录该玩家帐户。该功能不考虑缓存的玩家帐户，`SignInWithGooglePlayGamesAsync` 会替换缓存的玩家帐户。

```cs
async Task SignInWithGooglePlayGamesAsync(string authCode)
{
    try
    {
        await AuthenticationService.Instance.SignInWithGooglePlayGamesAsync(authCode);
        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);
    }
}
```

## 将玩家帐户从匿名更新为 Google Play Games 帐户##updating-a-player-from-anonymous-to-a-google-play-games-account

在您设置完匿名身份验证后，如果玩家想从匿名升级为 Google Play Games 帐户并登录，您应在游戏中引导玩家触发 Google Play Games 登录并从 Google 获取一次性授权码。然后，调用 `LinkWithGooglePlayGamesAsync` API 以关联玩家帐户。

如果 SDK 上有缓存的玩家帐户，您可以将缓存的玩家帐户与 Google Play Games 帐户关联。

1. 通过 `SignInAnonymouslyAsync` 登录缓存玩家的帐户。
2. 通过 `LinkWithGooglePlayGamesAsync` 将缓存的玩家帐户与 Google Play Games 帐户关联。

```cs
async Task LinkWithGooglePlayGamesAsync(string authCode)
{
    try
    {
        await AuthenticationService.Instance.LinkWithGooglePlayGamesAsync(authCode);
        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);
    }
}
```

## 取消 Google Play 帐户关联##unlink-google-play-account

使用 `UnlinkGooglePlayGamesAsync` API 可以取消玩家帐户与其 Google Play Games 帐户的关联。一旦取消关联，如果玩家帐户不再关联到任何其他身份，则会转换为匿名帐户。

```cs
async Task UnlinkGooglePlayGamesAsync(string idToken)
{
   try
   {
       await AuthenticationService.Instance.UnlinkGooglePlayGamesAsync(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);
   }
}
```
