How to implement phone number Verification by OTP using Firebase in Android

How to implement phone number Verification by OTP using Firebase in Android2018-03-122018-04-12https://www.loginworks.com/wp-content/uploads/2018/05/logo-1-1.pngLoginworks Softwares Pvt. Ltd.https://www.loginworks.com/wp-content/uploads/2018/03/firebase-in-android.jpg200px200px

Introduction

Hey guys! In this tutorial, I am covering user verification by phone number by sending OTP to the mobile using Firebase authentication.

You can use Firebase Authentication to enable a user to sign in to your app by sending an SMS to user’s device which contains a one-time-password. The user then enters this OTP in your app, if the OTP matches then sign in is successful and the user can then access your app.

Firebase Authentication

Firebase is a Google product which provides backend services, SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

You may authenticate users of your app either by using Firebase UI which provides a complete user interface for sign in and authentication or you can integrate Firebase SDK manually into your app.

What you should already KNOW

To understand this tutorial you should be familiar with:

Basic knowledge of JAVA and Android.

What you should have

To make this app you should have:

The latest version of Android Studio Installed on your PC or Laptop.

A smartphone, as OTP cannot be sent to an emulator.

A Gmail ID to enable Firebase and add your project to Firebase console.

What you will learn

In this tutorial you will learn:

Setting up a new Android Studio project.

Integrating Firebase to your project.

Creating simple XML layout for your app.

Sending and verifying OTP using Firebase in Android JAVA code.

What you will do

In the process of making this app you will:

Create an app and add user interface elements such as Buttons, Edit texts, and Text views.

Add your project to Firebase console and enable phone authentication.

Implement click listeners on buttons to sign in (Generate OTP) and sign out.

Call Firebase authentication methods on the button on click events.

Retrieve user mobile number from firebase user data.

App overview

The “OTP Authentication” app will consist of two Activities MainActivity and SignedIn. MainActivity activity will have two edit texts, one for the phone number and the other for received OTP, Also it will have two buttons, one to generate OTP and other to verify OTP. If the OTP match is successful then it will open SignedIn activity via Intent. If the OTP does not match then it will pop a toast message, “Incorrect OTP”.

SignedIn activity will include a text view displaying number and a sign out button on click of which app sign-outs and go back to MainActivity activity.

Now you have to register your app by providing the app package name and SHA-1 signing certificate on below screen.

To find the App package name open AndroidManifest.xml and on the top, there is the package name

To get the SHA-1 signing certificate, click on Gradle tab on the right end of Android studio to open Gradle properties> then click on :app> android> double click on signingReport. In the Monitor pane, you will see SHA1.

Copy and paste the package name and the SHA1 signing certificate in the firebase console register page. Then, click on REGISTER APP button.

Now you have to download the google-services.json file from the download config page and paste it in app module.

After than in project pane, click on Gradle Scripts> open project level build.gradle file and add google service dependency in buildscript.

Now go back to Firebase console and click on Project Overview. In Discover Firebase section there is a card named Authentication, click on GET STARTED on Authentication card.

On the next page click on SETUP SIGN-IN METHOD and enable phone authentication, then SAVE it. At this point, we are done with the initial setup.

step3: EDIT androidmanifest.XML

Our application needs internet for sending OTP. So, for this reason, we have to, first of all, give permission to our app to use the internet. Add the following line to your AndroidManifest.xml inside manifest tag.

JAVA CODE TO SIGN-IN VIA OTP

STEP1: LINK XML BUTTONS and Edittexts TO JAVA in Main Activity

First of all, we will declare global variables for Buttons and EditTexts.

Button btnGenerateOTP, btnSignIn;
EditText etPhoneNumber, etOTP;

After then, we will create a findViews() method in MainActivity.java.
In this, we will link the Buttons and edittexts that we declare in java to buttons and edittexts in activity_main.xml. Then we will call this method in activities onCreate() method.

step2: Declare Phone number and OTP variables

Declare String type global variables to store phone number and OTP from EditTexts.

String phoneNumber, otp;

step3: Implement onCLickListener to Generate OTP button to send SMS

In the MainActivity’s onCreate() method we will set click listener to btnGenerateOTP in which we will get the text from phone number EditText and store it in phoneNumber variable. Then we will initiate the sign-in flow by passing this phone number variable to PhoneAuthProvider.getInstance().verifyPhoneNumber method to request firebase to verify the user’s phone number.

Declare another global variable for verification state change call back that we have to pass as a parameter.

Above method will send an SMS to the provided phone number. As verifyPhoneNumber() is reentrant, it will not send another SMS on button click until the original request is timed out.

step4: Handle callback functions

Next, we have to handle the result of the request initiated on button’s click. For this, we have to create a new instance of PhoneAuthProvider.OnVerificationStateChangedCallbacks().In the methods of this call back we will update the user with the result via Toast message.

Create global variables.

FirebaseAuth auth;

private String verificationCode;

Then, make a function StartFirebaseLogin() to handle the result of callbacks. Call this function in onCreate method.

After completing this step, OTP code will be sent to your device. Enter your mobile number and click generate OTP button. After that, the user will enter the OTP received via SMS and start the verification process.

step5: Implement onCLickListener to sign in button to verify OTP

Next, we will implement click listener on btnSignIn which will get the OTP from EditText and initiate the verification process. To begin with, create a PhoneAuthCredential object with the verification code and OTP as parameters. further, call SigninWithPhone() with credential as a parameter to complete sign-in.

step6: Sign in the user

Finally, this is the last step of the sign-in process. To this end, we will make SigninWithPhone() method. If the verification is successful then we will open SignedIn Activity. Otherwise, a toast message will be printed to show the error message.