Usług gier Google Play możesz używać do logowania graczy w grze na Androida opartej na Firebase. Aby używać logowania w usługach gier Google Play za pomocą Firebase, najpierw zaloguj gracza w usługach gier Google Play i poproś o kod autoryzacji OAuth 2.0. Następnie przekaż kod autoryzacji do PlayGamesAuthProvider
, aby wygenerować dane logowania Firebase, których możesz użyć do uwierzytelniania w Firebase.
Zanim zaczniesz
Konfigurowanie projektu na Androida
Jeśli jeszcze tego nie zrobiono, dodaj Firebase do projektu na Androida.
W pliku Gradle modułu (na poziomie aplikacji) (zwykle
<project>/<app-module>/build.gradle.kts
lub<project>/<app-module>/build.gradle
) dodaj zależność z biblioteką Firebase Authentication na Androida. Zalecamy używanie Firebase Android BoM do kontrolowania wersji biblioteki.W ramach konfigurowania Firebase Authentication musisz też dodać do aplikacji pakiet SDK Usług Google Play.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.0.0")) // 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.3.0") }Gdy korzystamy z Firebase Android BoM, aplikacja zawsze używa zgodnych wersji bibliotek Firebase na Androida.
(Alternatywnie) Dodaj zależności biblioteki Firebase bez użycia BoM
Jeśli nie chcesz używać Firebase BoM, musisz określić każdą wersję biblioteki Firebase w wierszu zależności.
Pamiętaj, że jeśli w aplikacji używasz wielu bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia zgodność wszystkich wersji.
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:24.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.3.0") }
Konfigurowanie projektu Firebase
Ustaw odcisk SHA-1 gry na stronie Ustawienia w konsoli Firebase.
Hasz SHA certyfikatu podpisywania możesz uzyskać za pomocą polecenia gradle
signingReport
:./gradlew signingReport
Włącz Gry Google Play jako dostawcę logowania:
Znajdź identyfikator klienta serwera internetowego i tajny klucz klienta projektu. Identyfikator klienta serwera internetowego identyfikuje Twój projekt Firebase na serwerach uwierzytelniania Google Play.
Aby znaleźć te wartości:
- Otwórz projekt Firebase na stronie danych logowania w Konsoli interfejsów API Google.
- W sekcji Identyfikatory klienta OAuth 2.0 otwórz stronę szczegółów Klient internetowy (utworzony automatycznie przez usługę Google). Na tej stronie znajdziesz identyfikator i klucz tajny klienta serwera internetowego.
Następnie w Firebasekonsoli otwórz sekcję Uwierzytelnianie.
Na karcie Metoda logowania włącz dostawcę logowania Gry Play. Musisz podać identyfikator klienta serwera internetowego i tajny klucz klienta projektu, które zostały pobrane z konsoli interfejsów API.
Skonfiguruj Play Games services za pomocą informacji o aplikacji Firebase.
W Google Playkonsoli otwórz Google Playaplikację lub utwórz nową.
W sekcji Rozwój kliknij Play Games services > Konfiguracja i zarządzanie > Konfiguracja.
Kliknij Tak, w swojej grze używam już interfejsów API Google, wybierz z listy projekt Firebase i kliknij Użyj.
Na stronie konfiguracji Play Games services kliknij Dodaj dane logowania.
- Wybierz typ Serwer gier.
- W polu Klient OAuth wybierz identyfikator klienta usługi internetowej projektu. Upewnij się, że jest to ten sam identyfikator klienta, który został podany podczas włączania logowania za pomocą Play Games.
- Zapisz zmiany.
Na stronie konfiguracji Play Games services ponownie kliknij Dodaj dane logowania.
- Wybierz typ Android.
- W polu Klient OAuth wybierz identyfikator klienta Androida w projekcie. (Jeśli nie widzisz identyfikatora klienta Androida, upewnij się, że w Firebase konsoli masz ustawiony odcisk SHA-1 gry).
- Zapisz zmiany.
Na stronie Testerzy dodaj adresy e-mail użytkowników, którzy mają mieć możliwość logowania się w Twojej grze przed jej opublikowaniem w Play Store.
Integrowanie logowania przez Gry Play z grą
Najpierw zintegruj logowanie w Grach Play z aplikacją. Pełne instrukcje znajdziesz w artykule Logowanie się w Grach na Androida.
Podczas tworzenia obiektu GoogleSignInOptions
w integracji użyj konfiguracji DEFAULT_GAMES_SIGN_IN
i wywołaj requestServerAuthCode
:
Kotlin
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();
Musisz przekazać identyfikator klienta serwera internetowego do metody requestServerAuthCode
.
Jest to identyfikator podany podczas włączania logowania w Grach Play w Firebasekonsoli.
Uwierzytelnianie za pomocą Firebase
Po dodaniu do aplikacji logowania w Grach Play musisz skonfigurować Firebase, aby używać danych logowania do konta Google, które uzyskujesz, gdy gracz zaloguje się w Grach Play.
- Najpierw w metodzie
onCreate
aktywności logowania uzyskaj udostępnioną instancję obiektuFirebaseAuth
:
Kotlin
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- Podczas inicjowania aktywności sprawdź, czy gracz jest już zalogowany w Firebase:
Kotlin
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.
- Gdy gracz zaloguje się w Grach Play (cicho lub interaktywnie),
pobierz kod autoryzacji z obiektu
GoogleSignInAccount
, wymień go na dane logowania Firebase i uwierzytelnij się w Firebase za pomocą tych danych:
Kotlin
// 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); } // ... } }); }
Jeśli wywołanie signInWithCredential
się powiedzie, możesz użyć metody getCurrentUser
, aby uzyskać dane konta użytkownika.
Dalsze kroki
Gdy użytkownik zaloguje się po raz pierwszy, zostanie utworzone nowe konto użytkownika i połączone z jego identyfikatorem w Gry Play. Nowe konto jest przechowywane w projekcie Firebase i może służyć do identyfikowania użytkownika we wszystkich aplikacjach w projekcie.
W grze możesz uzyskać identyfikator UID Firebase użytkownika z FirebaseUser
obiektu:
Kotlin
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();
W regułach zabezpieczeń Bazy danych czasu rzeczywistego Firebase i Cloud Storage możesz uzyskać niepowtarzalny identyfikator użytkownika, który jest zalogowany, ze zmiennej auth
i użyć go do kontrolowania, do jakich danych użytkownik ma dostęp.
Aby uzyskać informacje o graczu w Grach Play lub dostęp do usług Gier Play, użyj interfejsów API udostępnianych przez pakiet SDK Gier Google Play.
Aby wylogować użytkownika, wywołaj funkcję FirebaseAuth.signOut()
:
Kotlin
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();