在 Android 上使用 Google Play 遊戲服務進行驗證

您可以使用 Google Play 遊戲服務讓玩家登入 Android 遊戲 。如要透過 Firebase 使用 Google Play 遊戲服務登入功能, 請先使用 Google Play 遊戲簽署玩家,然後要求進行 OAuth 2.0 驗證 編寫程式碼接著,將驗證碼傳遞至 PlayGamesAuthProvider 產生 Firebase 憑證,以便透過 Firebase 進行驗證。

事前準備

設定 Android 專案

  1. 如果還沒試過 將 Firebase 新增至您的 Android 專案

  2. 模組 (應用程式層級) Gradle 檔案中 (通常為 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)、 新增 Android 版 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 管理程式庫版本管理

    此外,設定 Firebase 驗證時,您需要將 導入 Google Play 服務 SDK

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }

    使用 Firebase Android BoM 應用程式一律會使用相容的 Firebase Android 程式庫版本。

    (替代做法) 新增 Firebase 程式庫依附元件,「不使用」BoM

    如果選擇不使用 Firebase BoM,則須指定各個 Firebase 程式庫版本 都屬於依附元件行

    請注意,如果您在應用程式中使用多個 Firebase 程式庫,強烈建議您 建議使用 BoM 管理程式庫版本 相容。

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth:23.0.0")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }
    在尋找 Kotlin 專用的程式庫模組嗎?距離開始還有 2023 年 10 月 (Firebase BoM 32.5.0),Kotlin 和 Java 開發人員都能 依附於主要程式庫模組 (詳情請參閱 這項計畫的常見問題)。

設定 Firebase 專案

  1. 前往以下連結設定遊戲的 SHA-1 指紋: 「設定」頁面 也可使用 Firebase 控制台

    您可以使用 Gradle 取得簽署憑證的 SHA 雜湊 signingReport 指令:

    ./gradlew signingReport

  2. 啟用 Google Play 遊戲做為登入提供者:

    1. 找出專案的網路伺服器用戶端 ID 和用戶端密鑰。網路 伺服器用戶端 ID 會向 Google Play 識別您的 Firebase 專案 驗證伺服器

      如何找出這些值:

      1. 在「Google API 控制台」憑證頁面中,開啟 Firebase 專案。
      2. OAuth 2.0 用戶端 ID 部分中,開啟網路用戶端 (自動 Google 服務建立) 的詳細資料頁面。這個頁面會列出你的 伺服器用戶端 ID 和密鑰。
    2. 接著,在 Firebase 控制台開啟「驗證」專區。

    3. 在「Sign in method」分頁中,啟用「Play Games」登入功能 。您必須指定專案的網路伺服器 用戶端 ID 和用戶端密鑰 (可從 API 控制台取得)。

使用 Firebase 應用程式資訊設定 Play 遊戲服務

  1. Google Play 管理中心 請開啟或新建 Google Play 應用程式。

  2. 在「拓展」部分中,按一下 Play 遊戲服務 >設定和管理 >設定

  3. 按一下「是,我的遊戲已在使用 Google API」,選取您的 Firebase 然後按一下「使用」

  4. 在 Play 遊戲服務設定頁面中,按一下 新增憑證

    1. 選取「遊戲伺服器」類型。
    2. 在「OAuth 用戶端」欄位中,選取專案的網路用戶端 ID。成為 這是您啟用功能時指定的用戶端 ID 登入 Play 遊戲。
    3. 儲存變更。
  5. 在 Play 遊戲服務設定頁面中,按一下 重新新增憑證

    1. 選取「Android」類型。
    2. 在「OAuth 用戶端」欄位中,選取專案的 Android 用戶端 ID。 (如果找不到您的 Android 用戶端 ID,請確認您已設定遊戲的 Firebase 控制台中的 SHA-1 指紋)。
    3. 儲存變更。
  6. 在「測試人員」頁面中,為需要測試的使用者新增電子郵件地址 。 Play 商店。

將 Play 遊戲登入程序整合至遊戲

首先,將 Play 遊戲登入功能整合至您的應用程式。詳情請見 登入 Android 遊戲 以取得完整指示。

在整合作業中,建構 GoogleSignInOptions 物件時,請使用 DEFAULT_GAMES_SIGN_IN 設定並呼叫 requestServerAuthCode

Kotlin+KTX

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
    .requestServerAuthCode(getString(R.string.default_web_client_id))
    .build()

Java

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestServerAuthCode(getString(R.string.default_web_client_id))
        .build();

您必須將網路伺服器用戶端 ID 傳遞至 requestServerAuthCode 方法。 該 ID 是您啟用 Play 遊戲登入功能時所提供的 ID Firebase 控制台。

透過 Firebase 驗證

在應用程式中新增 Play 遊戲登入程序後,你必須設定 Firebase 玩家成功登入後可取得的 Google 帳戶憑證 Play 遊戲

  1. 首先,在登入活動的 onCreate 方法中,取得 FirebaseAuth 物件的共用例項:

Kotlin+KTX

private lateinit var auth: FirebaseAuth
// ...
// Initialize Firebase Auth
auth = Firebase.auth

Java

private FirebaseAuth mAuth;
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
  1. 初始化「活動」時,請確認玩家是否已簽署 善用 Firebase 的優勢:

Kotlin+KTX

override fun onStart() {
    super.onStart()
    // Check if user is signed in (non-null) and update UI accordingly.
    val currentUser = auth.currentUser
    updateUI(currentUser)
}

Java

@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}
If the player isn't signed in, present the player with your game's
signed-out experience, including the option to sign in.
  1. 玩家在 Play 遊戲中無訊息或互動方式登入後, 從 GoogleSignInAccount 物件取得驗證碼,以交換 Firebase 憑證,並使用 Firebase 進行 Firebase 驗證 憑證:

Kotlin+KTX

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private fun firebaseAuthWithPlayGames(acct: GoogleSignInAccount) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.id!!)

    val auth = Firebase.auth
    val credential = PlayGamesAuthProvider.getCredential(acct.serverAuthCode!!)
    auth.signInWithCredential(credential)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "signInWithCredential:success")
                val user = auth.currentUser
                updateUI(user)
            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "signInWithCredential:failure", task.exception)
                Toast.makeText(
                    baseContext,
                    "Authentication failed.",
                    Toast.LENGTH_SHORT,
                ).show()
                updateUI(null)
            }

            // ...
        }
}

Java

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());

    final FirebaseAuth auth = FirebaseAuth.getInstance();
    AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
    auth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = auth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                    // ...
                }
            });
}

如果呼叫 signInWithCredential 成功,您可以使用 getCurrentUser 方法取得使用者的帳戶資料。

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶 連結 Google Play 遊戲。這個新帳戶會儲存在您的 Firebase 專案的專用 ID,可用來識別應用程式內所有應用程式的使用者 專案。

您可以在遊戲中透過 FirebaseUser 取得使用者的 Firebase UID 物件:

Kotlin+KTX

val user = auth.currentUser
user?.let {
    val playerName = it.displayName

    // The user's Id, unique to the Firebase project.
    // Do NOT use this value to authenticate with your backend server, if you
    // have one; use FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = mAuth.getCurrentUser();
String playerName = user.getDisplayName();

// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
String uid = user.getUid();

在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以 已登入使用者在 auth 變數中的不重複使用者 ID,並使用該 ID 來 控制使用者可以存取哪些資料

如要取得使用者的 Play 遊戲玩家資訊或存取 Play 遊戲服務, 請使用 Google Play 遊戲 SDK 提供的 API。

如要將使用者登出,請呼叫 FirebaseAuth.signOut()

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();