Я дважды проверил следующее:
Номер телефона, который я использую, является одним из тестовых номеров, перечисленных в консоли Firebase в разделе «Телефонные номера для тестирования».
Я используя точный формат (включая код страны и префикс «+») и регистр (прописные/строчные), как они отображаются в консоли.
Мое устройство может принимать другие SMS-сообщения.
Вот соответствующие фрагменты кода:
PhoneSignUpViewModel.kt:
Код: Выделить всё
fun onSignUpClick(activity: Activity, phoneNumber: String) {
viewModelScope.launch {
isLoading = true
// LOG: Check the number before sending to the repository
Log.d("PhoneSignUpViewModel", "Phone number being sent to signUp: $phoneNumber")
userRepository.signUp(phoneNumber) // No need to pass token here
.collect { result ->
when (result) {
is Result.Success -> {
// Update the shared state holder (verificationId and token are in result.data)
otpSharedStateHolder.otpVerificationData.value =
OtpVerificationData(
result.data.verificationId ?: "",
result.data.token
)
isLoading = false
_events.emit(Event.NavigateToOtpVerification)
}
is Result.Error -> {
showError = true
isLoading = false
}
is Result.Loading -> {
isLoading = true
}
}
}
}
}
Код: Выделить всё
override fun signUp(
phoneNumber: String,
token: PhoneAuthProvider.ForceResendingToken?
): Flow = callbackFlow {
trySend(Result.Loading)
launch {
try {
// LOG: Verify the number format received by the repository
Log.d("UserRepositoryImpl", "Phone number received in signUp: $phoneNumber")
val optionsBuilder = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
// (Unlikely to happen for phone auth)
launch {
try {
firebaseAuth.signInWithCredential(credential).await()
val user = firebaseAuth.currentUser
trySend(
Result.Success(
User(
phoneNumber = phoneNumber,
id = user?.uid
)
)
)
} catch (e: Exception) {
trySend(
Result.Error(
Exception("Sign-in failed: ${e.message}")
)
)
}
}
}
override fun onVerificationFailed(e: FirebaseException) {
Log.e(
"UserRepositoryImpl",
"onVerificationFailed: ${e.message}",
e
)
trySend(Result.Error(e))
}
override fun onCodeSent(
verificationId: String,
forceResendingToken: PhoneAuthProvider.ForceResendingToken
) {
Log.d("UserRepositoryImpl", "onCodeSent: $verificationId")
trySend(
Result.Success(
User(
phoneNumber = phoneNumber,
verificationId = verificationId,
token = forceResendingToken
)
)
)
close() // Close the callbackFlow
}
})
if (token != null) {
optionsBuilder.setForceResendingToken(token)
}
val options = optionsBuilder.build()
PhoneAuthProvider.verifyPhoneNumber(options)
} catch (e: Exception) {
trySend(Result.Error(e))
}
}
awaitClose { /* Clean up resources if needed */ }
}.catch { emit(Result.Error(it as Exception)) }
- D/PhoneSignUpViewModel: номер телефона, отправляемый для регистрации:
+16505551212< /li>
D/UserRepositoryImpl: Номер телефона, полученный при регистрации: +16505551212 - D/UserRepositoryImpl: onCodeSent: [VERIFICATION_ID]
Я внимательно следил за документацией Firebase по аутентификации номера телефона (не понимаю, что касается игровой целостности и проверки приложений). В Firebase также добавлен токен управления отладкой.
Tech Stack
- Kotlin
- Jetpack Compose
- Hilt< /p>
- Аутентификация Firebase
- Play Integrity API (сделано это, но не совсем понятно)
Подробнее здесь: https://stackoverflow.com/questions/788 ... d-on-andro
Мобильная версия