2

I'm developing an app that has the feature to get an OTP, and I've used firebase OTP feature (Authenticate with Firebase on Android using a Phone Number) but unfortunately some-time I'm facing issue like I'm not getting otp from firebase also its not giving any errors at same time. I don't know what was the mistake i did.Need help to solve this issue also I've tried some samples its working properly but when i try to integrate in my project firebase is not sending otp.I want post mobile number to firestore with users current country code for ex(+91,+888).

This what I've tried in my project so far:

package com.example.NewActivity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.aayushchaubey.meetdax.R;
import com.example.activity.HomeActivity;
import com.example.activity.PhoneNumberLogin;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthSettings;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;


public class LoginWithMobileNumber extends AppCompatActivity {

    EditText phoneNo_Edt;
    Button loginBtn;
    FirebaseAuth firebaseAuth;
    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
    private static final String TAG = "FirebasePhoneNumAuth";

    PhoneAuthProvider.ForceResendingToken mResendToken;
    String mVerificationId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mobileno_verification);

        phoneNo_Edt=(EditText)findViewById(R.id.phoneNoEdt);
        loginBtn=(Button)findViewById(R.id.phoneNoLoginBtn);
        phoneNo_Edt.setSingleLine();
        firebaseAuth= FirebaseAuth.getInstance();

        addOnClickListener();

        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential) {
                // This callback will be invoked in two situations:
                // 1 - Instant verification. In some cases the phone number can be instantly
                //     verified without needing to send or enter a verification code.
                // 2 - Auto-retrieval. On some devices Google Play services can automatically
                //     detect the incoming verification SMS and perform verification without
                //     user action.
                Log.d(TAG, "onVerificationCompleted:" + credential);

                signInWithPhoneAuthCredential(credential);
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                // This callback is invoked in an invalid request for verification is made,
                // for instance if the the phone number format is not valid.
                Log.w(TAG, "onVerificationFailed", e);

                if (e instanceof FirebaseAuthInvalidCredentialsException) {
                    // Invalid request
                    // ...
                } else if (e instanceof FirebaseTooManyRequestsException) {
                    // The SMS quota for the project has been exceeded
                    // ...
                }

                // Show a message and update the UI
                // ...
            }

            @Override
            public void onCodeSent(String verificationId,
                                   PhoneAuthProvider.ForceResendingToken token) {
                // The SMS verification code has been sent to the provided phone number, we
                // now need to ask the user to enter the code and then construct a credential
                // by combining the code with a verification ID.
                Log.d(TAG, "onCodeSent:" + verificationId);

                // Save verification ID and resending token so we can use them later
                mVerificationId = verificationId;
                mResendToken = token;

                // ...
            }
        };


    }

    private void addOnClickListener() {

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendSms();
            }
        });
    }

    public void sendSms(){
        String phoneNumber=phoneNo_Edt.getText().toString();
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                this,               // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks

    }

    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        firebaseAuth.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 = task.getResult().getUser();

                            if(mVerificationId!=null){
                                Intent intent = new Intent(getApplicationContext(), VerifyOtp.class);
                                intent.putExtra("verificationcode",mVerificationId);
                                startActivity(intent);                            }

                            // ...
                        } 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
                            }
                        }
                    }
                });
    }
}
Manish Karena
  • 724
  • 6
  • 29
Deepa
  • 43
  • 1
  • 8

2 Answers2

4

I am using Firebase OTP verification in my application and after spending a week solving different scenarios I understood followings. May be it will help in your case as well.

Consider following scenario.

  1. When you call PhoneAuthProvider.getInstance().verifyPhoneNumber(), most of the times Firebase will send OTP and our code will receive onCodeSent callback. After that, if device recieves OTP, sdk will call onVerificationCompleted or onCodeAutoRetrievalTimeOut according to the timeout value you passed in the parameters.

  2. (May be this could be your case) Sometimes when you call PhoneAuthProvider.getInstance().verifyPhoneNumber(), sdk will call onCodeSent method but device does not receive any OTP. And meanwhile, sdk will auto verify phone number and call onVerificationCompleted directly without sending any OTP.

So you should cosider above scenario and decide accordingly.

I am still not sure if this answer will satisfy your scenario or not but it will surely help you to understand things better.

Dhaval
  • 2,724
  • 2
  • 24
  • 33
0

Use following code:

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
    @Override
    public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
        String code = phoneAuthCredential.getSmsCode();

        // In case OTP is received
        if (code != null) {
            otpTxt.setText(code);
            verifyCode(code);
        } else {
        // In case OTP is not received
            signInWithCredentials(phoneAuthCredential);
        }
    }
Sandeep
  • 455
  • 4
  • 26