I only want to get the OTP first. Then I will create an account. But I am unable to get OTP. The phone number format is also correct. Below is my code. Is there any error in it?
I think PhoneAuthProvider.getInstance().verifyPhone() is working properly so there will no error in it.
public class second extends AppCompatActivity {
EditText phoneNumberET, OTPET;
String phoneNumber, verificationCode;
FirebaseAuth mAuth;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack;
public void submit(View view)
{
phoneNumber = phoneNumberET.getText().toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
phoneNumberET = (EditText) findViewById(R.id.phoneNumberEditText);
OTPET = (EditText) findViewById(R.id.OTPEditText);
mAuth = FirebaseAuth.getInstance();
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Log.i("complete","inside");
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCode = s;
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
};
}
}
As I know, there are some policies with Firebase Phone Authentication.
Example:
If you're trying to login with a same number several times, Firebase Authentication server will automatically block that number by thinking it as a spam number.
Try to login with several numbers in several times. (I know it's painful!)
If you're trying with just one number, you can wait for some time for your next login with that number.
There is a solution for debugging:
You can create some testing phone numbers and verification code for debugging your app with Firebase Phone Authentication. To do this:
Go to your Firebase Console
Go to Authentication
Click on Phone and you'll find Phone numbers for testing (optional)
Add your testing phone number with country code +1. And, also add your verification code for that number.
Click Add then, Save
In this way, you can easily test your app even in Emulator with Firebase Phone Authentication!
If you can not receive verification SMS with any device or any number, Please have a look at this answer to check correct implementation.
If you are facing issue sometimes, then you should try Test with whitelisted phone numbers.
Related
I have this Android code for Firebase sign in using SMS code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseApp.initializeApp(this);
userLoggedIn();
mPhoneNumber = findViewById(R.id.phoneNumber);
mCode = findViewById(R.id.code);
mSend = findViewById(R.id.send);
mAuth = FirebaseAuth.getInstance();
mSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mVerificationId != null) {
// verifyPhoneNumberWithCode(mVerificationId, mCode.getText().toString());
verifyPhoneNumberWithCode(mVerificationId, mCode.getText().toString());
} else {
startPhoneNumberVerification();
}
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:" + phoneAuthCredential);
signInWithPhoneAuthCredentials(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verificationId, forceResendingToken);
mVerificationId = verificationId;
mSend.setText("Verify Code");
}
};
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredentials(credential);;
}
private void startPhoneNumberVerification() {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(mPhoneNumber.getText().toString()) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private void signInWithPhoneAuthCredentials(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
userIsLoggedIn();
}
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
return;
}
}
The code works fine BUT after I added the following 2 sign-in methods on firebase project console, the app doesn't require new users to verify the SMS code any more - meaning, new users get signed in automatically after getting the code without punching in the code on the app.
Firebase Authentication Sign-in providers console
Google
Google sign-in is automatically configured on your connected iOS and
web apps. To set up Google sign-in for your Android apps, you need to
add the SHA1 fingerprint for each app on your Project Settings.
Email/password
Allow users to sign up using their email address and password. Our
SDKs also provide email address verification, password recovery, and
email address change primitives. Learn more
I have both SHA-1 and SHA-256 configures on my project.
Any ideas why it signs new users in automatically without verifying SMS code sent?
Instant verfication might be happening with your phone number.
I have observed that with our numbers most of times Auto-retrieval works.
I'm guessing this behavior might be happening based on service provider/country code/device or other factors.
https://firebase.google.com/docs/auth/android/phone-auth#onverificationcompletedphoneauthcredential
onVerificationCompleted(PhoneAuthCredential)
This method is called in two situations:
Instant verification: in some cases the phone number can be instantly
verified without needing to send or enter a verification code.
Auto-retrieval: on some devices, Google Play services can
automatically detect the incoming verification SMS and perform
verification without user action. (This capability might be
unavailable with some carriers.)
In either case, the user's phone number has been verified successfully, and you can use the PhoneAuthCredential object that's passed to the callback to sign in the user.
Hi I am trying to do a phone auth in android using firebase. The first time I install the app the sms comes and verification is successful but subsequently the sms does not come again. I have deleted the user from the auth in firebase and still it is not working.
Following is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
CountryCodePicker ccp;
EditText editTextPhone, editTextCode;
FirebaseAuth mAuth;
String codeSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
editTextCode = findViewById(R.id.editTextCode);
editTextPhone = findViewById(R.id.editTextPhone);
findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendVerificationCode();
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode() {
String code = editTextCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, 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()) {
//here you can open new activity
Toast.makeText(getApplicationContext(),
"Login Successfull", Toast.LENGTH_LONG).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getApplicationContext(),
"Incorrect Verification Code ", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void sendVerificationCode() {
String phone = editTextPhone.getText().toString();
if (phone.isEmpty()) {
editTextPhone.setError("Phone number is required");
editTextPhone.requestFocus();
return;
}
if (phone.length() < 6 || phone.length() > 13) {
editTextPhone.setError("Please enter a valid phone");
editTextPhone.requestFocus();
return;
}
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
Toast.makeText(MainActivity.this,
"SMS Sent, Please Wait....", Toast.LENGTH_LONG).show();
editTextCode.requestFocus();
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeSent = s;
}
};
}
EDIT
restarting the phone allows resending the sms after the 60 second timeout set in the function above. So it seems the phone is keeping something in the memory.
In my case, I have my number on
Phone numbers for testing (optional)
Removing it from there, firebase started sending SMS Code to my number. Spark Plan offer 10k phone auth per month. So that you can test and deploy your app without paying a penny.
In case someone is not getting the concept or reason of not sent sms again then please go through on my below details. I have been confused for very long time that why I didn't get sms for second time, third and so on..
First Read the original documentation:
onVerificationCompleted(PhoneAuthCredential)
This method is called in two situations:
Instant verification: in some cases the phone number can be instantly verified without needing to send or enter a verification
code.
Auto-retrieval: on some devices, Google Play services can automatically detect the incoming verification SMS and perform
verification without user action. (This capability might be
unavailable with some carriers.)
What I found:
onVerificationCompleted:
is only called when instant verification or auto-retrieval occurs.
When you try this for the first time you will get the otp code
from Google but the next time you try it, it can cause instant verification
to get active.
You can do:
So if you are debugging and having problem with not
receiving otp code from google just disable your sim card and enable it
again. This will help you in getting the otp codes from google again for
one more time until you enter your code and instant verification gets
activated again
Please note:
I don't think there is any way you can disable instant
verification as of now. But you can always optimize your code in a way it
doesn't create any problem for you and your users.
If you want to explore more then please check the thread: Click here
You must clear data for this app from phone. If not then run remove app and restart your phone will clear all data related with this app and re-run it.
In my case, I was found the next solution:
You need to update your Google Play Market to the latest version. You can do this in like this: Go to Play Market -> Click on "burger button" -> Select "Settings" in the menu -> Go to the bottom of the menu and you will find "Play Market Version" -> Click into it
Go to Phone Setting -> Go to Applications section -> Select Google Play Settings App -> Clear data\cahce -> then Select Google Play Market App -> Clear data\cahce
Reboot your device after the above steps.
Try again to send SMS to your device.
This solution will help you if you already tried to delete your user from the "White list" in the phone auth section, tried to delete phone number from a user database, and do other tries to fix this issue.
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
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
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