Firebase not sending OTP - android

I had registered a user in firebase using Firebase phone number authentication.For testing that functionality again, I deleted the user account from Firebase console. Now, i am trying to register that number again, its directly going to the onVerificationCompleted() callback without sending the OTP.But the user account is not shown in Firebase console.
Please help.
Code given below. Also please note that its sending OTP to the new numbers .But not sending OTP to the number which i deleted from firebase console.I want to register that particular number again.
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private boolean mVerificationInProgress = false;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private static final String KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress";
private static final String TAG = "PhoneAuthActivity";
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private EditText mPhoneNumberField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
onRestoreInstanceState(savedInstanceState);
}
mPhoneNumberField=(EditText)findViewById(R.id.phone_number);
mAuth = FirebaseAuth.getInstance();
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);
Toast.makeText(getApplication(),"Verification completed",Toast.LENGTH_SHORT).show();
// [START_EXCLUDE silent]
mVerificationInProgress = false;
Log.d(TAG,"CREDENTIAL"+credential);
// Intent intent=new
Intent(getBaseContext(),VerificationActivity.class);
// intent.putExtra("VERIFICATION_ID",mVerificationId);
// startActivity(intent);
}
#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);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
// [START_EXCLUDE]
mPhoneNumberField.setError("Invalid phone number.");
// [END_EXCLUDE]
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
// [START_EXCLUDE]
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
Snackbar.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
}
#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;
Intent intent=new Intent(getBaseContext(),VerificationActivity.class);
intent.putExtra("VERIFICATION_ID",mVerificationId);
startActivity(intent);
}
};
}
public void verifyDevice(View v){
String phno=mPhoneNumberField.getText().toString();
startPhoneNumberVerification(phno);
}
private void startPhoneNumberVerification(String phoneNumber) {
// [START start_phone_auth]
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
// [END start_phone_auth]
mVerificationInProgress = true;
}
#Override
public void onStart() {
super.onStart();
if (mVerificationInProgress) {
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
}
// [END_EXCLUDE]
}
// [END on_start_check_user]
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_VERIFY_IN_PROGRESS, mVerificationInProgress);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mVerificationInProgress = savedInstanceState.getBoolean(KEY_VERIFY_IN_PROGRESS);
}
Looking forward to some help.

Try to signout of your app or simply clear data or reinstall, it's possible there is a little glitch somewhere within the app.
If the above instruction doesn't work, then the cause is a little deeper. Since the authentication worked the first time, it's most likely a network carrier issue; this happens mostly in cases where a phone number was ported from one network provider to another at some point. You can try experimenting with phone numbers of a different network carrier. Sadly, there is no exact workaround for this problem yet. Whichever case, you can send your complaints to Firebase support. There'd definitely be some help there.

As per my experience, Firebase creates a refresh token & a firebase user ID token after login, firebase user ID token expires every hour whereas refresh token is long-lived.
this firebase user ID token resides in user device & refresh token is maintained on firebase servers.
In your case after deleting user account refresh token must have expired by firebase but user ID token on your device must not have expired and that's why it automatically calls onVerificationCompleted()
You can read about managing sessions & tokens here

Worked for me .
Sometimes Google is unable to verify the request coming from you app.
In order to solve it. Generate your app's signing report and get your SHA-1 or SHA-256 fingerprints.
Go to your firebase project setting and update those fingerprints.
How to add fingerprint

Hope this answer helps you.
I have copied my files onto another laptop and tried debugging my project. I have faced the same problem and later realized that I have not updated my SHA-1 and SHA-256 fingerprints of my new laptop on firebase.
Make sure that your SHA-1 and SHA-256 fingerprints are up-to-date

Related

Firebase database listener not working after Firebase PhoneAuth Signout

I have made an Android application using Firebase Phone Authentication and Realtime Database.
My requirement is to first check if the user's no. is in my database or not and then send him the OTP.
My database:
My code:
rootRef= FirebaseDatabase.getInstance().getReference().child("Employees").child("mobno");
//---------------1----------------
getcodeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("abcd","get code button clicked");
if (!cugET.getText().toString().trim().isEmpty() && cugValidFlag==true) {
Log.d("abcd","entered no. is valid");
enteredcugno = cugET.getText().toString().trim();
Log.d("abcd","Entered cugno: "+enteredcugno);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("abcd","rootRef listener reached");
if(dataSnapshot.child(enteredcugno).exists()){
Log.d("abcd","cugno exists in db");
startPhoneNumberVerification(cugET.getText().toString().trim());
mVerified = false;
otpTV.setVisibility(View.VISIBLE);
otpET.setVisibility(View.VISIBLE);
otpValTV.setVisibility(View.VISIBLE);
verifycodeBtn.setVisibility(View.VISIBLE);
}
else{
Log.d("abcd","cugno doesn't exists in db");
Toast.makeText(cugLogin.this,"No such CUG No. found",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
//------------------------2--------------------
private void startPhoneNumberVerification(String phoneNumber) {
Log.d("abcd","startPhoneNumberVerification");
// [START start_phone_auth]
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+91"+phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
// [END start_phone_auth]
}
//--------------3--------------------
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 verificaiton without
// user action.
Log.d("abcd", "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("abcd", "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Log.d("abcd","verification failed cz of FirebaseAuthInvalidCredentialsException");
Toast.makeText(cugLogin.this,"Verification Failed !! Invalied verification Code",Toast.LENGTH_SHORT).show();
}
else if (e instanceof FirebaseTooManyRequestsException) {
Log.d("abcd","verification failed cz FirebaseTooManyRequestsException");
Toast.makeText(cugLogin.this,"Verification Failed !! Too many request. Try after some time. ",Toast.LENGTH_SHORT);
}
}
#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("abcd", "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
}
};
//----------------4---------------
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
Log.d("abcd","signInWithPhoneAuthCredential reached");
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("abcd", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
mVerified = true;
timer.cancel();
timerTV.setVisibility(View.INVISIBLE);
cugET.setEnabled(false);
cugTV.setVisibility(View.INVISIBLE);
cugET.setVisibility(View.INVISIBLE);
getcodeBtn.setVisibility(View.INVISIBLE);
otpTV.setVisibility(View.INVISIBLE);
otpET.setVisibility(View.INVISIBLE);
otpValTV.setVisibility(View.INVISIBLE);
verifycodeBtn.setVisibility(View.INVISIBLE);
Intent intent = new Intent(cugLogin.this,Login.class);
intent.putExtra("cugnotoLogin",enteredcugno);
startActivity(intent);
Toast.makeText(cugLogin.this,"Successfully verified",Toast.LENGTH_SHORT).show();
// ...
} else {
// Sign in failed, display a message and update the UI
Log.w("abcd", "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(cugLogin.this,"Invalid OTP ! Please enter correct OTP",Toast.LENGTH_SHORT).show();
}
}
}
});
}
The last log I see is "Entered cugno: 9876543210"
No error being shown, I am really confused how can I correct it?
If I remove the rootRef listener my code is working but I want to check the user in the database first. Also I am giving the correct path to the rootRef then why isn't it working?
EDIT
I got my code working but I am still a bit confused, I just moved my rootRef initialization in the getcodeBtn listener. But I already had it in my onStart() function so it should have been initialized there as well, if anyone knows the reason behind it please let me know.
LATEST EDIT
Now when I signed out, my code is again stuck at the rootRef listener, it isn't getting passed into it. Even after closing the app it isn't letting me in. It's the same thing happening again. It's like something got refreshed overnight and the app let me sign in and when I signed out, I am stuck again. Why is this happening?
I solved it, it wasn't the coding problem but the logic was faulty. I set the rules of the database for the authenticated users only, and was checking my database first to let the user to sign in, so when I logged out, the code went into a loop as it couldn't access the database to let the user sign in.

Getting error while doing mobile no verification using Firebase in android only on some mobile phones?

I am trying to do registration using firebase OTP verification,
I have two EditText fields on my registration page
(1) Enter Name
(2)Enter Phone Number
After getting Phone no. and Name and I am trying to get OTP using Firebase.
and it is working on every device but not working on the Nexus 5.
Error that I am getting
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task. com.google.android.gms.common.api.GoogleApi.zzb(com.google.android.gms.common.api.internal.zzdf)' on a null object reference
While executing PhoneAuthProvider.getInstance().verifyPhoneNumber
Here is My code
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
CallBackInitialize();
private void CallBackInitialize(){
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
mVerificationInProgress = false;
updateUI(STATE_VERIFY_SUCCESS, 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);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
//mPhoneNumberField.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",Snackbar.LENGTH_SHORT).show();
}
// Show a message and update the UI
updateUI(STATE_VERIFY_FAILED);
}
#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);
mVerificationId=verificationId;
Intent i = new Intent(RegistrationActivity.this, SignUpVerify.class);
i.putExtra("mobile", mobilenumber.getText().toString());
//i.putExtra("otp1", otp);
i.putExtra("vCode", mVerificationId);
i.putExtra("name", user_name.getText().toString());
startActivity(i);
overridePendingTransition(R.anim.righttoleft, R.anim.slide_out_left);
progressBar.setVisibility(View.GONE);
signup.setClickable(true);
// Save verification ID and resending token so we can use them later
// mVerificationId = verificationId;
//mResendToken = token;
// Update UI
updateUI(STATE_CODE_SENT);
}
};}
After getting Phone no.
private void sendSmsToGivenMobileNumber(String phonrNumber){
Log.d("Phone",phonrNumber);
FirebaseAuth.getInstance().signOut();
startPhoneNumberVerification(phonrNumber);
}
private void startPhoneNumberVerification(String phoneNumber) {
try {
mAuth = FirebaseAuth.getInstance();
PhoneAuthProvider provider = PhoneAuthProvider.getInstance(mAuth);
provider.verifyPhoneNumber(
"+91" + phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
RegistrationActivity.this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
mVerificationInProgress = true;
}catch (Exception ex) {
System.out.println("Closed : " + ex.getMessage().toString());
}
}
I have got the solution .
Problem not in code .Just problem in Google Play Services
Solution 1 :
Just update your device Google Play Service its .
or
Solution 2 :
Check your gmail_id is added in device .It should be addedd
I had been facing the same trouble. There is a little bit of error i.e. in the placement of the code.
The only thing you have to do in this code is to place the code of "mCallbacks" above the function call [ startPhoneNumberVerification() ] in onCreate().
This will run your code.

Can I use Firebase "Phone Number Authentication" feature for the phone number verification purpose?

I am actually using Firebase Google auth for signing in the user and after that, I want to take the basic details of the user into the database which also includes the mobile number of a user, so my question is can use Phone Number Authentication just to verify the mobile number of user (using OTP) and after that I can store it into database?
Thank You!
If you are already signing in a user with Google. You can link/update the phone number for that user:
https://firebase.google.com/docs/reference/js/firebase.User#updatePhoneNumber
https://firebase.google.com/docs/reference/js/firebase.User#linkWithPhoneNumber
This means the user will have 2 providers linked (phone/google.com). The user will be able to sign in with either in the future. Though if you only want to expose Google as the provider. You can just provide that in your sign in page.
You can store the user in the database too.
Because Firebase Authentication is amazing,
you can have more than one authentication "method" on an account:
In this example, the app in question, allows users to create an account using either
phone
email
Facebook link
So. On the welcome screen of the app, it says "Join SuperApp, using phone, email or Facebook link!!" and there's three buttons for those three methods.
But in fact, the way Firebase Authentication works, each user can actually have more than one of those.
The third user there has both email and phone authentication. The fourth user there has all three!
So, let's say a user creates an account with "email authentication".
Later, there will be a button that says "Also link your Facebook account!",
and another one, "Also link your phone number!"
(Note that in many cases, depending on what your startup is, you may want users to have more than one authentication method, for greater security. Or, you may just want to make it easier for them to log in.)
Incredibly, Firebase can handle all that. (Or, you can spend a year developing it by hand!)
Some points...
Yes, Firebase entirely takes care of sending the email or SMS verification codes. Completely automatic.
Note that you can't "use" the amazing email/phone verification service "for other purposes". For example, in an app we're doing there's a feature where you need to verify a purchase or something, using an SMS code. Note that that has absolutely nothing to do with the user logging-in, it's just an unrelated feature in the app which uses an SMS code. You can not (unfortunately!) use Firebase's epic SMS-system to do that. (You'd just use any of the widely available sms-code-sending services, instead.)
A huge point of confusion. Note that the email and/or phone number discussed here are stored by Firebase in the Firebase Authentication system. The image above is from the Firebase Authentication system. There is NO CONNECTION AT ALL to your data tables. So, almost every app has in the data tables something like "userData/". Sure, you may, for your convenience (or whatever) have fields in the data tables like "email" "Facebook name" or whatever. Those fields have NO CONNECTION AT ALL, in any way, to the "actual, real" Firebase Authentication system (as seen in the image above). Those are just fields you populate in your development - they could hold any value you put in there. There are many, many questions here on SO where folks confuse some value "user_email" that happens to be in the database, with the "actual, real" email or phone used by Firebase in the Firebase Authentication system.
Note that if you start off with Facebook or another social authentication. Sometimes those social media have the users email/phone/etc. But that has absolutely no connection to the actual Firebase authenticated email/phone.
If the user happens to need to change their actual authenticated email or phone, there's a function for that link
The Firebase Authentication system is so amazing that many mobile projects use Firebase purely for the convenience of the amazing Firebase Authentication system, even if they are not especially using Firebase as such.
(One detail on the email front. You'll use your own email server to send the emails. (ie, godaddy or sendmail or whatever - just whatever email server you normally use.) There's a slot on the backend of Firebase where you just type in your email server/password. Alternately, during development/testing Firebase will even send the email for you, but it only arrives slowly since it's a mass-used account being used by about a zillion Firebase-app-developers like yourself.)
Summary
Amazingly you can have more than one authentication method, it is all handled by Firebase
Note that any phone/email etc you may happen to have in your data, has absolutely No connection to the "actual" phone/email in Firebase Authentication
In the Firebase console, look on the left and go one above "Database" to see "Authentication" ! Many news developers don't realize this!
If you want to use firebase phone authentication for phone number verification only, according to me you do this but by implementing following:
First in Sign-in Method page, enable the Phone Number sign-in method and to send verification code on phone number use this
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
you will get response in mCallbacks and to initialize callback use this
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// this method executed if phone number verified you can do your stuff here if you only want to verify phone number.
// or you can also use this credentials for authenticate purpose.
}
#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.
}
#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
//and then execute your method if number entered is correct.
}
};
Don't forgot to use latest firebase dependencies like
compile 'com.google.firebase:firebase-auth:11.4.2'
Hope this will help you.
private FirebaseAuth mAuth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId = "";
PhoneAuthProvider.ForceResendingToken mResendToken;
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks()
{
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
//edtVerify.setText(phoneAuthCredential.getSmsCode());
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Log.e("Invalid Phone Number ","====>");
} else if (e instanceof FirebaseTooManyRequestsException) {
Log.e("Quota exceeded ","====>");
}
}
#Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
//SEND VERIFICATION CODE...
try {
PhoneAuthProvider.getInstance().verifyPhoneNumber(mLastEnteredPhone, 120,
TimeUnit.SECONDS,
mContext,
mCallbacks);
} catch (Exception e) {
e.printStackTrace();
}
//VERIFY CODE...
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
} catch (Exception e) {
e.printStackTrace();
}
//SIGN IN WITH PHONE...
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential)
{
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
FirebaseUser user = task.getResult().getUser();
String currentUid = user.getUid();
String currentPhone = user.getPhoneNumber();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Log.e("Invalid Code ","====>");
}
}
}
});
}
Yes you can use it with the help of following code
PhoneAuthProvider.getInstance().verifyPhoneNumber(
mobnum, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId=s;
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(),"Verification Failed"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}); // OnVerificationStateChangedCallbacksPhoneAuthActivity.java
after that you have to use the following method
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent i = new Intent(Otp_Verification_Activity.this,HomeActivity.class);
startActivity(i);
finish();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
and for more you can visitclickhere
and you watch video on youtube clickhere

Not Receiving code in Firebase Phone Authentication.

I'm trying to implement Firebase phone auth in my app.
I referred the firebase android documents on GitHub, but I can't get the code by SMS.
I don't know why it is happening? I'm testing it on a real device.
Also, I'm sending SMS to another one because the real device doesn't have a sim card. But I'm sure that it's not a problem. Is it right?
This is my code
void logIn(){
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 verificaiton without
// user action.
Log.d("verification", "onVerificationCompleted:" + credential);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
// [START_EXCLUDE silent]
// Update the UI and attempt sign in with the phone credential
// [END_EXCLUDE]
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("verification", "onVerificationFailed", e);
// [START_EXCLUDE silent]
mVerificationInProgress = false;
// [END_EXCLUDE]
if (e instanceof FirebaseAuthInvalidCredentialsException) {
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
// [START_EXCLUDE]
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
Snackbar.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
}
#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("verification", "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
}
};
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+79995198722", // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
mVerificationInProgress = true;
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
// [START verify_with_code]
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
// [END verify_with_code]
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("signIn", "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
} else {
// Sign in failed, display a message and update the UI
Log.w("signIn", "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
Thanks in advance!
I think your problem might be SHA-1 finger print, So you need to update the SHA-1 key in Firebase console.
Steps:
After login to Firebase console
Click on your project then you can see Overview of your project
Click on 3 dots and click Settings
Click Add Finger print (At bottom)
Paste your SHA-1 key click on Save.
Steps to SHA-1 key:
Select gradle in Android Studio from left panel
Select your App
Go to Tasks -> android -> signingReport
then you can see the Sha-1 key.
I solved my problem by running an app on a real machine(Android Device) instead of an emulator.

User Firebase Phone Auth

Is it possible to use Phone Auth just to verify a phone number? My users are already logged in with other providers. I only need to make sure that the number they have entered is valid.
You can do this using Firebase's PhoneAuthProvider which will send sms of one time code to the user phone number through which the user is verified.
The implementation is given in this documentation: Firebase phone authentication
lets say that You can't verify the phone number without creating a new user linked to this number in firebase using the manual verification
but you can unlink the phone from the user account soon after, by calling:
FirebaseAuth.getInstance().getCurrentUser().
unlink(PhoneAuthProvider.PROVIDER_ID)
.addOnCompleteListener(this);
just like:
final PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, scode);
mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseAuth.getInstance().getCurrentUser().
unlink(PhoneAuthProvider.PROVIDER_ID)
.addOnCompleteListener(this);
register_user(sname,semail,sphone,scode, spass); // this if you wanna register with a different method
}
}
});
And There is the possibility of auto verification of Google Play Services (in the new phones). When onVerificationCompleted(PhoneAuthCredential) in your PhoneAuthProvider.OnVerificationStateChangedCallbacks is called. and here the verification is completed with no need from the user to type anything and the phone will not linked to a new user account.
PhoneAuthProvider.getInstance().verifyPhoneNumber(sphone, 60, TimeUnit.SECONDS, AuthActivity.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
register_user(sname,semail,sphone,scode, spass); // this if you wanna register with a different method
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
// ...
}
});
I think that google should allow to the developers to verify the phone without creating user account that will be so helpful

Categories

Resources