top of page
  • Writer's picturePrithvi Kumar

Firebase Phone Authentication with OTP: Android Tutorial -

Firebase Authentication with phone number with some easy steps:

Prerequisite: Add Propject in Firebase and enable phone auth.


Step 1: Add dependecy or enable From Android Studio -- Tool>Firebase

dependencies {
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:32.1.1')

    // 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-ktx'
}

Step2:


Function to get the Otp from firebase:

fun sendVerificationCode(
    number: String,
    auth: FirebaseAuth,
    activity: Activity,
    callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks,
) {
    // on below line generating options for verification code
    Log.d("TAG", "sendVerificationCode: .....$number")
    val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(number) // Phone number to verify
        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
        .setActivity(activity) // Activity (for callback binding)
        .setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
}

--------------------------------------------------------------------------
Function to verify the Otp from firebase:👇

fun signInWithPhoneAuthCredential(
    loginSignUpViewModel: LoginSignUpViewModel,
    credential: PhoneAuthCredential,
    auth: FirebaseAuth
) {
    // on below line signing with credentials.
    auth.signInWithCredential(credential)
        .addOnCompleteListener(activity) { task ->
            // displaying toast message when
            // verification is successful
            if (task.isSuccessful) {
                Toast.makeText(context, "Verification successful..", Toast.LENGTH_SHORT).show()
                Log.d("TAG", "signInWithPhoneAuthCredential: /..../...changed")
            } else {
                // Sign in failed, display a message
                if (task.exception is FirebaseAuthInvalidCredentialsException) {
                    // The verification code
                    // entered was invalid
                    Toast.makeText(
                        context,
                        "Verification failed.." + (task.exception as FirebaseAuthInvalidCredentialsException).message,
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
}

Step 3: Calling these from Activity or Fragmens or composable functions:

lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks

callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    override fun onVerificationCompleted(p0: PhoneAuthCredential) {
        // on below line updating message
        // and displaying toast message
        message = "Verification successful"
        Toast.makeText(context, "Verification successful..", Toast.LENGTH_SHORT).show()
    }

    override fun onVerificationFailed(p0: FirebaseException) {
        // on below line displaying error as toast message.
        message = "Fail to verify user : \n" + p0.message
        Toast.makeText(context, "Verification failed..", Toast.LENGTH_SHORT).show()
    }

    override fun onCodeSent(
        verificationId: String,
        p1: PhoneAuthProvider.ForceResendingToken,
    ) {
        // this method is called when code is send
        super.onCodeSent(verificationId, p1)
        loginSignUpViewModel.verificationID = verificationId
    }
}

val mAuth: FirebaseAuth = FirebaseAuth.getInstance()
sendVerificationCode(
    "+91${binding.mobileEditText.text}", mAuth, requireActivity(), callbacks
)
AppUtility.signInWithPhoneAuthCredential(
    loginSignUpViewModel,
    credential,
    mAuth,
)

How to avoid reCAPTCHA verification:✌️


steps:1 - generate SHA1 And SHA256 from android project



💡run in gradle (signingreport) to generate.


step2- go to Firebase project settings >> Add fingerprint


step2- Go to >> Google cloud Console >> Select your project >> Enable Api Services >> Search For Google Play Integrity API >> Enable it.



step3- Go to Playconsole >> select a project >> Setup >> App Integrity






 

115 views0 comments

Recent Posts

See All

Clean Wall Pro : privacy policy

Privacy Policy MoboInfo.com built the Clean Wall Pro app as a Free app. This SERVICE is provided by MoboInfo.com at no cost and is intended for use as is. This page is used to inform visitors regardi

Guide-U :Take the right path , Privacy Policy

Privacy Policy MoboInfo Technologies built the Guide-U :Take the right path app as a Free app. This SERVICE is provided by MoboInfo Technologies at no cost and is intended for use as is. This page is

BatterX Info Privacy Policy:

Privacy Policy MoboInfo.com built the BatteryX Info as a Free app. This SERVICE is provided by MoboInfo.com at no cost and is intended for use as is. This page is used to inform visitors regarding my

bottom of page