Search code examples
javaandroidfirebasefirebase-authenticationone-time-password

I'm Not recieving an Otp from firebase in the Phone authentication system


I have basically created 2 Xmls. one where the user enters the phone number and then on pressing a button it goes to the OTP verification screen. But the issue here is that I am not receiving any OTP from Firebase, but after 5 sec I get a toast message that the verification failed. How could it fail if I haven't even got the message. I also tried putting another number so that I can enter the code manually. But Firebase isn't sending me the OTP.

BASIC IMPLEMENTATION --- click Forgot Password -> Ask for Mobile Num ->Verify Otp ->Reset Password->Login Page

P.S I have enabled the phone authentication in Firebase.

OtpActivity.java

public class VerifyOtp extends AppCompatActivity {

    public String NumberEnteredByUser,verificationCodeBySystem;
    Button VerifyButton;
    PinView phoneEnteredByUser;
    FirebaseAuth auth;
    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;



    

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_otp);
        getSupportActionBar().hide();

        Intent intent =getIntent();
        NumberEnteredByUser = intent.getStringExtra("phoneNo");



        VerifyButton = findViewById(R.id.btnVerify);
        phoneEnteredByUser = findViewById(R.id.EnterCode);
        auth = FirebaseAuth.getInstance();

        send_code_to_user(NumberEnteredByUser);




        VerifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkcode();
            }
        });

    }


    private void checkcode() {
        String userEnteredOtp = phoneEnteredByUser.getText().toString();
        if(userEnteredOtp.isEmpty() || userEnteredOtp.length()<6){
            Toast.makeText(this, "Wrong Otp!", Toast.LENGTH_SHORT).show();
            return;
        }
        finishEverything(userEnteredOtp);
    }

    private void finishEverything(String code) {
        phoneEnteredByUser.setText(code);
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,code);
        sign_in(credential);
    }

    private void sign_in(PhoneAuthCredential credential) {
        FirebaseAuth auth = FirebaseAuth.getInstance();
        auth.signInWithCredential(credential).addOnCompleteListener(VerifyOtp.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful())
                {
                    Toast.makeText(VerifyOtp.this, "UserSignedInSuccessfully", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getApplicationContext(),ResetPassword.class));
                }
                else {
                    Toast.makeText(VerifyOtp.this,task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void send_code_to_user(String NumberEnteredByUser ) {
        PhoneAuthOptions options =
                PhoneAuthOptions.newBuilder(auth)
                        .setPhoneNumber(NumberEnteredByUser)       // Phone number to verify
                        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                        .setActivity(this)                 // Activity (for callback binding)
                        .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

                            @Override
                            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                                Toast.makeText(VerifyOtp.this, "Verification Completed", Toast.LENGTH_SHORT).show();
                                String code = phoneAuthCredential.getSmsCode();
                                if (code != null) {
                                    finishEverything(code);
                                }
                            }

                            @Override
                            public void onVerificationFailed(FirebaseException e) {
                                Toast.makeText(VerifyOtp.this, "Verification Failed", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                                super.onCodeSent(s, forceResendingToken);
                                verificationCodeBySystem = s;
                                Toast.makeText(VerifyOtp.this, "Code sent", Toast.LENGTH_SHORT).show();
                            }
                        })          // OnVerificationStateChangedCallbacks
                        .build();
        PhoneAuthProvider.verifyPhoneNumber(options);

    }
}

Build Gradle Project

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        classpath 'com.google.gms:google-services:4.3.8'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Build Gradle App

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'


}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.mitadt.newui"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment:2.2.2'
    implementation 'androidx.navigation:navigation-ui:2.2.2'
    implementation 'com.google.firebase:firebase-firestore:23.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.google.firebase:firebase-database:19.7.0'
    implementation 'com.google.firebase:firebase-auth:19.3.2'
    implementation 'com.android.support:multidex:1.0.3'
    //OTP VIEW DEPENDENCY
    implementation 'com.chaos.view:pinview:1.4.3'
}

Kindly help me out. Thankyou!!!


Solution

  • The verification failed because you didn't enable app verification. To do so, you can follow these steps:

    1. Goto Google Cloud Console, Select your project and Enable Android Device Verification. Here is the direct link: https://console.cloud.google.com/apis/library/androidcheck.googleapis.com

    2. In Android studio, go to top right corner bar, and press "Gradle". Then Expand (your project name) > app > Tasks > android, and double click on signingReport. You will find SHA1 and SHA-256 in the run window like below: enter image description here

    3. Goto your firebase console, and open tha app. Goto Project Settings. Scroll down, you'll find Add Fingerprint where you will need to insert the both SHA1 and SHA-256 key. After inserting, you will need to download the updated google-services.json. Replace the old google-services.json in the android studio project with the new one. enter image description here

    4. Now, add the browser dependency in app-level grade because the app will need to open captcha verification page from the browser:

       implementation 'androidx.browser:browser:1.3.0' 
      
    5. Then, in Android Studio top menu Build > Clean Project and Build > Rebuild Project

    Now, you're good to go.

    Note: Your app may show a captcha verification web page