Question Detail

Integrating OTP Verification or phone number authentication in Android

5 years ago Views 1470 Visit Post Reply

How to integrate Free OTP service which will help us to verify valid mobile number?
How to login with Mobile Number Firebase?
Authenticate with Firebase with a Phone Number and get OTP to verify valid mobile number.

 


Thread Reply

Hemant Sharma

- 5 years ago

you have to use firebase Mobile Auth in android App.

Create new Project if not created for your project, Firebase Console

Setup Firebase Auth in gradle file add below depandancy 
 

implementation 'com.google.firebase:firebase-auth:16.1.0'

Enable Phone Number sign-in for your Firebase project

open the Authentication section

On the Sign-in Method tab select and enable the Phone Number sign-in method.

I hope you have setup google-services.json in your app folder.

 

Come on your Android Studio layout part
Create your VerifyMobileActivity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".VerifyMobileActivity">

    <LinearLayout
        android:id="@+id/main_layout_ID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="+91" />

            <EditText
                android:id="@+id/phone_Number_ID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:digits="0123456789"
                android:hint="Mobile"
                android:inputType="number" />
        </LinearLayout>

        <Button
            android:id="@+id/phone_Number_button_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Authenticate" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/otp_layout_ID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone">

        <EditText
            android:id="@+id/phone_otp_ID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:digits="0123456789"
            android:hint="OTP"
            android:inputType="number" />

        <Button
            android:id="@+id/verifyOTP_button_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Check OTP" />
    </LinearLayout>

    <TextView
        android:id="@+id/result_TextView_ID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Verfied Mobile Number"
        android:textSize="20dp" />
</LinearLayout>

 



import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;

import java.util.concurrent.TimeUnit;

public class VerifyMobileActivity extends AppCompatActivity {
    String TAG = "MOBILEAUTHClass";
    Activity mActivity;
    TextView result_TextView;
    LinearLayout main_layout,otp_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_verify);
        this.mActivity = VerifyMobileActivity.this;
        final EditText phone_Number = findViewById(R.id.phone_Number_ID);
        final EditText phone_otp= findViewById(R.id.phone_otp_ID);

        final Button phone_Button = findViewById(R.id.phone_Number_button_ID);
        final Button otp_Button = findViewById(R.id.verifyOTP_button_ID);
        result_TextView=findViewById(R.id.result_TextView_ID);
        main_layout=findViewById(R.id.main_layout_ID);
        otp_layout=findViewById(R.id.otp_layout_ID);
        otp_layout.setVisibility(View.GONE);
        main_layout.setVisibility(View.VISIBLE);
        result_TextView.setVisibility(View.GONE);
        mAuth = FirebaseAuth.getInstance();
        phone_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitAuth(phone_Number.getText().toString());
            }
        });
        otp_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyVerificationCode(phone_otp.getText().toString().trim());
            }
        });


    }

    void submitAuth(String phoneNumber) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                "+91" + phoneNumber,        // Phone number to verify
                120,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                mActivity,       // Activity (for callback binding)
                mCallbacks);        // OnVerificationStateChangedCallbacks
    }

    private String mFIREBASEId;
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

            //Getting the code sent by SMS
            String code = phoneAuthCredential.getSmsCode();
            Log.d("_______________", code + "");
            if (code != null) {
                Toast.makeText(mActivity, code + "", Toast.LENGTH_SHORT).show();
                verifyVerificationCode(code);
            }
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);

            otp_layout.setVisibility(View.VISIBLE);
            main_layout.setVisibility(View.GONE);
            Toast.makeText(mActivity, s + " Code Sent", Toast.LENGTH_SHORT).show();
            //storing the verification id that is sent to the user
            mFIREBASEId = s;
            Log.d("VerificationID", s);
        }
    };


    private void verifyVerificationCode(String code) {
        //creating the credential
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mFIREBASEId, code);
        Log.d("OTP HERE", code + "");
        //signing the user
        signInWithPhoneAuthCredential(credential);
    }
FirebaseAuth mAuth;
    private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(mActivity, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            otp_layout.setVisibility(View.GONE);
                            result_TextView.setVisibility(View.VISIBLE);
                        } else {
                            //verification unsuccessful.. display an error message
                            String message = "Somthing is wrong, we will fix it soon...";
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                message = "Invalid code entered...";
                            }
                            Snackbar snackbar = Snackbar.make(findViewById(R.id.parent), message, Snackbar.LENGTH_SHORT);
                            snackbar.setAction("Close", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                            snackbar.show();
                        }
                    }
                });
    }

}