user9320363
user9320363

Reputation:

How to verify phone number using firebase authentication

I am trying to verify phone number, but it fails all time. I have Login Activity which takes mobile number. After click on login button I want OTP activity will open and user can enter OTP here and click on verify button to verify the number. But it always goes on onVerificationFailed block and shows toast Verification Fail and Invalid Number.

Login activity

public class LoginMain extends AppCompatActivity {
public FirebaseAuth mAuth;
// [END declare_auth]

public String mVerificationId;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
public PhoneAuthProvider.ForceResendingToken mResendToken;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_main);

    final EditText txtMobileno = (EditText) findViewById(R.id.txtMobileno);
    Button btnLogin = (Button) findViewById(R.id.btnLogin);

    mAuth = FirebaseAuth.getInstance();

    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
            Toast.makeText(LoginMain.this, "Verification Done" + phoneAuthCredential, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(LoginMain.this, "Verification Fail", Toast.LENGTH_LONG).show();
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                Toast.makeText(LoginMain.this, "Invalid Number", Toast.LENGTH_SHORT).show();
            } else if (e instanceof FirebaseTooManyRequestsException) {
                Toast.makeText(LoginMain.this, "Too many Request", Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            mVerificationId = s;
            mResendToken = forceResendingToken;
            Toast.makeText(LoginMain.this, "Code Sent", Toast.LENGTH_SHORT).show();
        }
    };

    txtMobileno.setText("+"+getCountrycode());

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String mobileno = txtMobileno.getText().toString();
            PhoneAuthProvider.getInstance().verifyPhoneNumber( mobileno, 60, TimeUnit.SECONDS, LoginMain.this, mCallbacks);
        }
    });
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.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 informatio
                        Toast.makeText(LoginMain.this, "Verification done", Toast.LENGTH_LONG).show();
                        FirebaseUser user = task.getResult().getUser();
                        // ...
                    } else {
                        // Sign in failed, display a message and update the UI
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid

                            Toast.makeText(LoginMain.this, "Verification failed code invalid", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
}
}

OTP activity

public class OTP extends AppCompatActivity {

public FirebaseAuth mAuth;
public String mVerificationId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp);

    mAuth = FirebaseAuth.getInstance();

    Button btnVerify = (Button) findViewById(R.id.btnVerifyOTP);
    final EditText txtOtp = (EditText) findViewById(R.id.txtOtp);
    btnVerify.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential( mVerificationId  , txtOtp.getText().toString());
            signInWithPhoneAuthCredential(credential);
        }
    });

}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.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");
                        Toast.makeText(OTP.this,"Verification done",Toast.LENGTH_LONG).show();
                        FirebaseUser user = task.getResult().getUser();
                        // ...
                    } else {
                        // Sign in failed, display a message and update the UI
                        //Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                            Toast.makeText(OTP.this,"Verification failed code invalid",Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
}
}

Error:

[FirebaseAuth: ] getGoogleApiForMethod() returned Gms

Upvotes: 0

Views: 1666

Answers (1)

Yashaswi N P
Yashaswi N P

Reputation: 933

Verification Fail or Invalid Number usually happens either when Phone number you sent is in an invalid format or you may be have missed the correct google_service.json file.

One simple format includes sending phone number with the correct country code. Please add the code and send. Hope this works.

Upvotes: 1

Related Questions