Firebase the Sms Code Has Expired. Please Re-send the Verification Code to Try Again.

How to Setup Firebase

You might need to use Firebase for the following reasons:

  1. Firebase authentication of users in your app via telephone number.
  2. Firebase Cloud Messaging (FCM) push notifications (erstwhile GCM).

It might look a bit scary at showtime. But don't panic and let's bank check how to practice this right step by stride.

Firebase business relationship and project registration

Follow these steps to register your Firebase account and create a Firebase projection:

  1. Register a Firebase account at Firebase console . You tin can apply your Google account to authenticate at Firebase.

  2. Click Add project

    Adding Project in Firebase

    Note: If you have a Google project registered for your mobile app, select it from the Project name dropdown menu.

    Yous tin can also edit your Project ID if you lot need. A unique ID is assigned automatically to each projection. This ID is used in publicly visible Firebase features. For case, it will be used in database URLs and in your Firebase Hosting subdomain. If yous need to utilise a specific subdomain, you can change it.

  3. Fill in the fields required (Project name, Project ID, etc.) and click Continue.

    Add a project

  4. Select data sharing for your projection and click Create project. Nosotros have chosen to let but Technical Back up access.

    Select data sharing

    So click Continue.

    Click Continue

  5. Select platform for which yous need Firebase

    Select platform

  6. Make full in the fields on Add Firebase to your Android App screen and click Register App

    Add Firebase to your Android app

Connect Firebase SDK

For Android projects Firebase has the following requirements to be added successfully:

  • Android OS 4.0 or newer
  • Google Play Services 15.0.0 or higher
  • The latest version of Android Studio

Hither is a step by step guide how to connect Firebase SDK to your Android Project:

  1. Download Google-Services.json config file

    Download config file

  2. Open up Project view in Android Studio and upload Google-Services.json file y'all take simply downloaded into the root directory of your Android app module.

    Upload config file to your project

  3. Add together Firebase SDK according to the instructions in your Firebase console

    Add Firebase SDK

  4. Add Google services plugin to your project build.gradle file

    Add Google services plugin to project

  5. Add together Google services plugin in the lesser of your module build.gradle file.

    Add Google services plugin to module

  6. Click Sync Now at the pop-up in your Android Studio

    Sync

    You are washed now.

Firebase authentication

This choice allows users in your app cosign themselves via phone number. If yous use this method for user authentication, the user receives an SMS with verification code and authenticates via that code in your app.

You need to follow these steps to add Firebase authentication to your Android projection:

  1. Add Firebase hallmark dependency to your Module build.gradle file:

    Add Firebase authentication dependency

  2. Sync your project as prompted by Android Studio:

    Sync your project

  3. Detect your app'southward SHA-ane hash - check Authenticating Your Client guide.

  4. Add your app's SHA-i hash in your Firebase console >> Project settings tab:

    Add your app's SHA-1 hash

    And then:

    Add your app's SHA-1 hash

  5. Go to Firebase console >> Authentication >> Sign-in method section:

    Enable phone authentication in Firebase

  6. Enable Phone number sign-in method:

    Enable phone authentication in Firebase

  7. Add PhoneAuthProvider.verifyPhoneNumber method to request that Firebase verify the user's phone number:

            PhoneAuthProvider.getInstance().verifyPhoneNumber(         phoneNumber,         // Phone number to verify         60,                 // Timeout duration         TimeUnit.SECONDS,    // Unit of timeout         this,               // Activity (for callback binding)         mCallbacks);        // OnVerificationStateChangedCallbacks          
            PhoneAuthProvider.getInstance().verifyPhoneNumber(     phoneNumber,      // Telephone number to verify     60,               // Timeout duration     TimeUnit.SECONDS, // Unit of timeout     this,             // Activity (for callback bounden)     mCallbacks)       // OnVerificationStateChangedCallbacks          

Annotation: verifyPhoneNumber method is reentrant: if yous phone call it multiple times, such equally in an activeness'due south onStart method, verifyPhoneNumber method volition not send a second SMS unless the original request has timed out.

Important note: As a best do please do not forget to inform your users that if they use phone sign-in, they might receive an SMS message for verification and standard rates utilise.

  1. (Optional) To resume the phone number sign in process if your app closes before the user can sign in (if the user checks SMS app, for example), after verifyPhoneNumber method is chosen, set a flag that indicates verification is in progress. Then, save the flag in your Activity's onSaveInstanceState method and restore the flag in onRestoreInstanceState. In your Activity's onStart method, check if verification is already in progress, and if it is not, telephone call verifyPhoneNumber again. Exist sure to articulate the flag when verification completes or fails. Check this guide for more than details.

  2. setLanguageCode method on your Auth example allows specifying the auth language and therefore localize SMS message sent by Firebase:

            auth.setLanguageCode("fr"); // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage();          
            auth.setLanguageCode("fr") // To employ the default app linguistic communication instead of explicitly setting it. // auth.useAppLanguage();          
  1. When y'all call PhoneAuthProvider.verifyPhoneNumber method, you must too provide an case of OnVerificationStateChangedCallbacks, which contains implementations of the callback functions that handle the results of the request:
            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 transport or enter a verification lawmaking.         // two - 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 asking 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 (east instanceof FirebaseTooManyRequestsException) {             // The SMS quota for the projection has been exceeded             // ...         }          // Show a message and update the UI         // ...     }      @Override     public void onCodeSent(Cord verificationId,                            PhoneAuthProvider.ForceResendingToken token) {         // The SMS verification code has been sent to the provided phone number, we         // at present need to ask the user to enter the lawmaking and then construct a credential         // by combining the lawmaking with a verification ID.         Log.d(TAG, "onCodeSent:" + verificationId);          // Salve verification ID and resending token so we can use them later         mVerificationId = verificationId;         mResendToken = token;          // ...     } };          
            mCallbacks = object : OnVerificationStateChangedCallbacks() {     override fun onVerificationCompleted(credential: PhoneAuthCredential) {         // This callback will be invoked in two situations:         // i - Instant verification. In some cases the telephone number can exist instantly         //     verified without needing to ship or enter a verification code.         // 2 - Auto-retrieval. On some devices Google Play services tin can automatically         //     detect the incoming verification SMS and perform verification without         //     user action.         Log.d(TAG, "onVerificationCompleted:$credential")         signInWithPhoneAuthCredential(credential)     }      override fun onVerificationFailed(east: FirebaseException) {         // This callback is invoked in an invalid request for verification is made,         // for case if the the phone number format is non valid.         Log.w(TAG, "onVerificationFailed", e)         if (due east is FirebaseAuthInvalidCredentialsException) {             // Invalid request             // ...         } else if (due east is FirebaseTooManyRequestsException) {             // The SMS quota for the project has been exceeded             // ...         }             // Prove a message and update the UI             // ...     }      override fun onCodeSent(verificationId: String,                             token: ForceResendingToken     ) {         // The SMS verification code has been sent to the provided phone number, nosotros         // at present need to ask the user to enter the code and so construct a credential         // by combining the code with a verification ID.         Log.d(TAG, "onCodeSent:$verificationId")         // Salvage verification ID and resending token so we tin use them after         mVerificationId = verificationId         mResendToken = token         // ...     } }          
  1. Create a PhoneAuthCredential object using the verification code and the verification ID that was passed to onCodeSent callback. You become a PhoneAuthCredential object when onVerificationCompleted is chosen. To create PhoneAuthCredential object, call PhoneAuthProvider.getCredential:
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);          
            val credential = PhoneAuthProvider.getCredential(verificationId, code)          
  1. Consummate the sign-in menstruation past passing the PhoneAuthCredential object to FirebaseAuth.signInWithCredential:
            private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {    mAuth.signInWithCredential(credential)             .addOnCompleteListener(this, new OnCompleteListener                                  <AuthResult                >              () {                 @Override                 public void onComplete(@NonNull Task                                  <AuthResult                >                            chore) {                     if (task.isSuccessful()) {                         // Sign in success, update UI with the signed-in user's information                         Log.d(TAG, "signInWithCredential:success");                          FirebaseUser user = chore.getResult().getUser();                         // ...                     } else {                         // Sign in failed, brandish a message and update the UI                         Log.w(TAG, "signInWithCredential:failure", task.getException());                         if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {                             // The verification code entered was invalid                         }                     }                 }             }); }          
            private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {     mAuth.signInWithCredential(credential)         .addOnCompleteListener(this) { task ->             if (chore.isSuccessful) {                 // Sign in success, update UI with the signed-in user's information                 Log.d(TAG, "signInWithCredential:success")                 val user = chore.result?.user                 // ...             } else {                 // Sign in failed, display a message and update the UI                 Log.w(TAG, "signInWithCredential:failure", chore.exception)                 if (chore.exception is FirebaseAuthInvalidCredentialsException) {                     // The verification lawmaking entered was invalid                 }             }         }     }          
  1. Get Firebase access_token after SMS lawmaking verification as follows:
            public Task                                  <GetTokenResult                >                            getIdToken (boolean forceRefresh)          
            fun getIdToken(forceRefresh: Boolean): Job                                  <GetTokenResult                >                                    

Example of the method implementation:

            FirebaseAuth.getInstance().getCurrentUser().getIdToken(forceRefresh);          
            FirebaseAuth.getInstance().currentUser?.getIdToken(forceRefresh)          
  1. Add ConnectyCube user sign in to your projection equally follows:

    i) Become your Projection ID from your Firebase console:

    Get your Project ID

    two) Pass your Firebase project_id and Firebase access_token parameters to signInUsingFirebase method:

            Cord projectId = "..."; String accessToken = "...";  ConnectycubeUsers.signInUsingFirebase(projectId, accessToken).performAsync(new EntityCallback                                  <ConnectycubeUser                >              () {     @Override     public void onSuccess(ConnectycubeUser user, Bundle args) {      }      @Override     public void onError(ResponseException mistake) {      } });          
            val projectId = "..." val accessToken = "..."  ConnectycubeUsers.signInUsingFirebase(projectId, accessToken)     .performAsync(object : EntityCallback                                  <ConnectycubeUser                >                            {         override fun onSuccess(user: ConnectycubeUser, args: Packet?) {          }          override fun onError(error: ResponseException) {          }     })          
  1. Endeavor running a examination. In one case your user is logged in successfully, you volition find him/her in your Dashboard >> Your App >> Users department.

    User logged in

So now you know how to employ Firebase features in your ConnectyCube apps. If yous take any difficulties - please let u.s. know via support aqueduct

foleyeatinke.blogspot.com

Source: https://developers.connectycube.com/android/firebase-setup-guide

0 Response to "Firebase the Sms Code Has Expired. Please Re-send the Verification Code to Try Again."

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel