My previous tutorial explains how to implement the user login / registration by collecting user name, email and password. But what if you want to sign up an user using their mobile number like WhatsApp, Viber by verifying their mobile number in order to get genuine users.

Before going further make sure that you have basic knowledge about android client-sever communication. If you are new to this, don’t worry, these articles (MySQL Spinner & PHP, MySQL – Android) gives you a good start.

As this article seems lengthy, I have divided it into two parts. In this part we’ll learn the server side part i.e building the PHP, MySQL project by integrating the SMS gateway. In the 2nd part we cover the implementation of android app.

android-sms-verification-like-whatsapp

1. How It Works

Below is the simple architecture diagram that explains the process of complete registration which involves the PHP, MySQL server and a SMS gateway.

android-sms-verification-php-mysql

1. First user mobile number will be sent to our server where new user row will be created.

2. Our server requests the SMS gateway for an sms to the mobile number with a verification code.

3. SMS gateway sends an SMS to the user device with the verification code.

4. The verification code will be sent back our server again for verification. Our server verifies it and activates the user.

2. Choosing the SMS Gateway

SMS gateways are helpful in sending an SMS to any mobile number that comes under any mobile network. Basically gateways have a contract with all the mobile networks to send the SMS to a particular mobile number. In INDIA we have lot of SMS providers, but choosing the best SMS service provider is difficult. I found Solutions Infini, SMS Gupshup, Value First and Msg91 are quite popular. But the most important thing keep in mind while choosing the provider is make sure that they do support REST API as our server needs to trigger an SMS whenever a request comes from the android app.

Unfortunately there are no free SMS gateways to test your android app. You have to contact any of the service providers seeking for a demo account or buy the SMS credits.

3. Signing up with MSG91 (API Key)

To demonstrate the tutorial, I have selected Msg91 gateway for their simplicity. Follow the below steps to get register and obtain your REST API Key. Please be aware that this gateway is for INDIAN users only. If you are not from INDIA, choose the gateway which is available in your country.

1. Signup with Msg91.

2. Buy the SMS credits by selecting the appropriate details. In the form select SMS Type as
TRANSACTIONAL ROUTE and give no.of SMS as 2500 which is minimum credits to buy. The cost would be around ₹600.

3. Proceed with the payment. Once the payment was done, you can see the SMS credits credited into your account.

4. To obtain your API key, goto the API doc and click on KEY on the top right corner. You will be shown your API Key in a popup dialog. Copy this API Key, we’re gonna need it in our PHP project.

Check the below video demonstrating buying the SMS credits on Msg91.

4. Building the PHP, MySQL REST API

Now we have the API Key needed to send the SMS. Let’s start building the PHP project needed for the android app. We are going to build a simple REST API to manage the users who signs up using the android app. At the end of this project, we should be able to build two end points needed for the user registration. One is to register user which sends an SMS with a verification code. Second endpoint is to verify the code and completes the user registration.

4.1 Installing WAMP software

Download & Install WAMP server from www.wampserver.com/en/. Once WAMP is installed, launch the program from Start ⇒ All Programs ⇒ WampServer ⇒ StartWampServer. If you are on Mac, MAMP will be useful.

You can test your server by opening the address http://localhost/ in your browser.
Also you can check phpmyadmin by opening http://localhost/phpmyadmin

4.2 Creating MySQL Database

For this project we need two tables. One is users table to store the user information and second one is sms_codes to store the user’s sms verification codes.

Below are the columns needed in each table.

android sms verification mysql database

Open http://localhost/phpmyadmin and execute below queries to create required database and tables.

Create a database named android_sms.

CREATE DATABASE android_sms;

USE android_sms;

Create required tables and relationship by executing below sql queries.

CREATE TABLE `sms_codes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `code` varchar(6) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;


CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(250) NOT NULL,
  `mobile` varchar(10) NOT NULL,
  `apikey` varchar(32) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;


ALTER TABLE `sms_codes`
  ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

4.3 Creating PHP Project

Once you are done with database setup, let’s move to php project development. You can use any IDE like Netbeans to develop this project or just the notepad++ is enough.

1. Goto the WAMP project directory i.e C:/wamp/www and create a folder named android_sms. This will be the root directory of our PHP project.

2. Inside android_sms, create a folder named include. In this folder we keep all the configuration like database credentials, Msg91 API Key etc.,

3. Create a file under include folder named Config.php and add below code. Replace the MySQL credentials and Msg91 API Key in the below code with yours.

<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
define('DB_NAME', 'android_sms');


/**
 * MSG91 configuration
 */
define('MSG91_AUTH_KEY', "88276AGwzewOEdFs559d2888");
// sender id should 6 character long
define('MSG91_SENDER_ID', 'ANHIVE');

define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>

4. Under include folder, create another php file named DbConnect.php This file handles the database connection.

<?php

/**
 * Handling database connection
 *
 * @author Ravi Tamada
 * @link URL Tutorial link
 */
class DbConnect {

    private $conn;

    function __construct() {        
    }

    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect() {
        include_once dirname(__FILE__) . '/Config.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            exit;
        }

        // returing connection resource
        return $this->conn;
    }

}

?>

5. Create another php file named DbHandler.php under include folder. This file contains the major functions to perform the read, write operations onto database.

<?php

/**
 * Class to handle all db operations
 * This class will have CRUD methods for database tables
 *
 * @author Ravi Tamada
 * @link URL Tutorial link
 */
class DbHandler {

    private $conn;

    function __construct() {
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    /* ------------- `users` table method ------------------ */

    /**
     * Creating new user
     * @param String $name User full name
     * @param String $email User login email id
     * @param String $mobile User mobile number
     * @param String $otp user verificaiton code
     */
    public function createUser($name, $email, $mobile, $otp) {
        $response = array();

        // First check if user already existed in db
        if (!$this->isUserExists($mobile)) {

            // Generating API key
            $api_key = $this->generateApiKey();

            // insert query
            $stmt = $this->conn->prepare("INSERT INTO users(name, email, mobile, apikey, status) values(?, ?, ?, ?, 0)");
            $stmt->bind_param("ssss", $name, $email, $mobile, $api_key);

            $result = $stmt->execute();

            $new_user_id = $stmt->insert_id;

            $stmt->close();

            // Check for successful insertion
            if ($result) {

                $otp_result = $this->createOtp($new_user_id, $otp);

                // User successfully inserted
                return USER_CREATED_SUCCESSFULLY;
            } else {
                // Failed to create user
                return USER_CREATE_FAILED;
            }
        } else {
            // User with same email already existed in the db
            return USER_ALREADY_EXISTED;
        }

        return $response;
    }

    public function createOtp($user_id, $otp) {

        // delete the old otp if exists
        $stmt = $this->conn->prepare("DELETE FROM sms_codes where user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();


        $stmt = $this->conn->prepare("INSERT INTO sms_codes(user_id, code, status) values(?, ?, 0)");
        $stmt->bind_param("is", $user_id, $otp);

        $result = $stmt->execute();

        $stmt->close();

        return $result;
    }
    
    /**
     * Checking for duplicate user by mobile number
     * @param String $email email to check in db
     * @return boolean
     */
    private function isUserExists($mobile) {
        $stmt = $this->conn->prepare("SELECT id from users WHERE mobile = ? and status = 1");
        $stmt->bind_param("s", $mobile);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

    public function activateUser($otp) {
        $stmt = $this->conn->prepare("SELECT u.id, u.name, u.email, u.mobile, u.apikey, u.status, u.created_at FROM users u, sms_codes WHERE sms_codes.code = ? AND sms_codes.user_id = u.id");
        $stmt->bind_param("s", $otp);

        if ($stmt->execute()) {
            // $user = $stmt->get_result()->fetch_assoc();
            $stmt->bind_result($id, $name, $email, $mobile, $apikey, $status, $created_at);
            
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                
                $stmt->fetch();
                
                // activate the user
                $this->activateUserStatus($id);
                
                $user = array();
                $user["name"] = $name;
                $user["email"] = $email;
                $user["mobile"] = $mobile;
                $user["apikey"] = $apikey;
                $user["status"] = $status;
                $user["created_at"] = $created_at;
                
                $stmt->close();
                
                return $user;
            } else {
                return NULL;
            }
        } else {
            return NULL;
        }

        return $result;
    }
    
    public function activateUserStatus($user_id){
        $stmt = $this->conn->prepare("UPDATE users set status = 1 where id = ?");
        $stmt->bind_param("i", $user_id);
        
        $stmt->execute();
        
        $stmt = $this->conn->prepare("UPDATE sms_codes set status = 1 where user_id = ?");
        $stmt->bind_param("i", $user_id);
        
        $stmt->execute();
    }

    /**
     * Generating random Unique MD5 String for user Api key
     */
    private function generateApiKey() {
        return md5(uniqid(rand(), true));
    }
}
?>

6. Now we have all the core logic ready. Let’s create an endpoint to register the user. In your project’s root directory, create a file named request_sms.php.

In below code

> First we receive the name, email and mobile number those were sent from the android device as a POST parameters.

> We create an entry in users table by calling createUser() function. Initially the user status will be 0 which indicate the user is inactive. This status will be made to 1 when the user verifies the OTP.

> Once the user row is created, we request for an SMS to the mobile number by calling sendSms() method.

> sendSms() method will make a call to Msg91 REST API to send SMS with a 6 digits OTP to the users mobile number.

Below is the sample SMS message the user will receive to their mobile. The OTP should be prefixed by : and space in the message.

Hello! Welcome to AndroidHive. Your OPT is : 228767
<?php

include './include/DbHandler.php';
$db = new DbHandler();


$response = array();

if (isset($_POST['mobile']) && $_POST['mobile'] != '') {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $mobile = $_POST['mobile'];

    $otp = rand(100000, 999999);

    $res = $db->createUser($name, $email, $mobile, $otp);

    if ($res == USER_CREATED_SUCCESSFULLY) {
        
        // send sms
        sendSms($mobile, $otp);
        
        $response["error"] = false;
        $response["message"] = "SMS request is initiated! You will be receiving it shortly.";
    } else if ($res == USER_CREATE_FAILED) {
        $response["error"] = true;
        $response["message"] = "Sorry! Error occurred in registration.";
    } else if ($res == USER_ALREADY_EXISTED) {
        $response["error"] = true;
        $response["message"] = "Mobile number already existed!";
    }
} else {
    $response["error"] = true;
    $response["message"] = "Sorry! mobile number is not valid or missing.";
}

echo json_encode($response);

function sendSms($mobile, $otp) {
    
    $otp_prefix = ':';

    //Your message to send, Add URL encoding here.
    $message = urlencode("Hello! Welcome to AndroidHive. Your OPT is '$otp_prefix $otp'");

    $response_type = 'json';

    //Define route 
    $route = "4";
    
    //Prepare you post parameters
    $postData = array(
        'authkey' => MSG91_AUTH_KEY,
        'mobiles' => $mobile,
        'message' => $message,
        'sender' => MSG91_SENDER_ID,
        'route' => $route,
        'response' => $response_type
    );

//API URL
    $url = "https://control.msg91.com/sendhttp.php";

// init the resource
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData
            //,CURLOPT_FOLLOWLOCATION => true
    ));


    //Ignore SSL certificate verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);


    //get response
    $output = curl_exec($ch);

    //Print error if any
    if (curl_errno($ch)) {
        echo 'error:' . curl_error($ch);
    }

    curl_close($ch);
}
?>

7. Now we need to create another endpoint to verify the OTP. Create a php file named verify_otp.php with below content.

In the below code

> The OTP will be received from the android device as a POST param.

> The user who matches with OTP will fetched from the users table.

> Then the user status will be set to 1 in both users and sms_codes table which makes the user active.

> The above two steps are implemented in activateUser() function.

<?php

include './include/DbHandler.php';
$db = new DbHandler();


$response = array();
$response["error"] = false;

if (isset($_POST['otp']) && $_POST['otp'] != '') {
    $otp = $_POST['otp'];


    $user = $db->activateUser($otp);

    if ($user != NULL) {

        $response["message"] = "User created successfully!";
        $response["profile"] = $user;
    } else {
        $response["message"] = "Sorry! Failed to create your account.";
    }
    
    
} else {
    $response["message"] = "Sorry! OTP is missing.";
}


echo json_encode($response);
?>

5. Testing the REST API

To test our API, install Postman chrome extension which allows you to test the endpoints by passing the parameters required.

Request SMS

URL Method Parameters Description
http://localhost/android_sms/request_sms.php POST name, email, mobile Request SMS

The below json should be produced when SMS sent successfully.

{
    "error": false,
    "message": "SMS request is initiated! You will be receiving it shortly."
}

Verifying user OTP

URL Method Parameters Description
http://localhost/android_sms/verify_otp.php POST otp verifying user verification code

When the OTP is verified successfully, the complete user profile information should be produced in the json.

{
    "error": false,
    "message": "User created successfully!",
    "profile": {
        "name": "Ravi Tamada",
        "email": "ravi@androidhive.info",
        "mobile": "0000000000",
        "apikey": "088d196bacbe6bf08657720c9d562390",
        "status": 0,
        "created_at": "2015-07-30 22:18:59"
    }
}

Watch the below video know how to use Postman to test the endpoints.

This completes the server side part. In the 2nd part we are going to learn how to create the android app by integrating the API we have just built.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Thanks very much for the great tutorial

  • Nidhin Kumar

    Hi Ravi,
    Nice Tutorial instead of using PHP,MySQL is it possible to do this using parse

  • tigani jaber

    Ravi ihave No words to describe your effort you are the best thank u

    • Thanks Tigani. This article really took lot of my effort 🙂

  • karim

    Thank you for this great tutorial,
    I Have a question about “apikey” column in users table, What is the purpose of it? because i do not see where we use it.

  • Konyan

    thank for tutorial, brother.
    How about twilo that is thrid party for sms verfied and controlled.
    if u post about twilo, i am very happy to thankful again.

    • Its been long time since I worked with Twilio. Just went through their code samples. It’s very easy.

      https://www.twilio.com/docs/api/rest/sending-sms

      • Hadi Samadbin

        I have the same problem going throw the twilio tutorial but it dident work.
        also when I test the rest api with postman I Got : The requested URL /android_sms/request_sms.php was not found on this server

  • Trey Rosius

    Works Perfectly.Thanks A lot.
    I do have a question which doesnot concern this topic.If i may…
    Do you have an idea or article which explains how to implement stickers in an android app.
    Fo example, i create stickers in photoshop and save as png and gif files.Then i put in assets folder, then i create a dialog fragment which display the stickers, so that when user selects a sticker, it gets posted in a conversation like viber.
    Is that the right way to do it?

  • Никита Чурилов

    You are AWESOME. Your tutorial always a necessary and useful. Big Happiness to you and your family

  • akhil

    Remarkable Ravi..First time compelled me to comment you…Tutorial presentation and demonstration is very Zoombalism. Keep Doing….

    • Thanks Akhil 🙂

      • akhil

        Hi Ravi

        I need one error which i am getting first time bz i am using android studio..

        BasicNetwork.performRequest: Unexpected response code 403 for http//xxx

        Plz intimate me whats wrong in and how to solve it

  • Subraya

    Ravi, U Rock! Thanks andi for all your contemporary articles on Android…

  • yajas sonu

    Ravi , nice tutorial.. i’m having a doubt please clear me .. will the same code work in eclipse

    • Yes. But don’t use the Eclipse anymore.

  • Rincon Interns

    Iam getting Volley. server error while running this code in external server.
    i changed the path in Config.java and also in Config.php

  • Very useful projects for android developer!Thanks a lot sir.

  • Azahar Sheikh

    Project working fine, but I am getting two OTP codes for one user…..

  • Umeas Karthick

    hi bro…I am doing a Project,in which i need to create a Android App…Shall u Guide me…?

  • Kunal Agrawal

    pls provide the codes codes for integrating in to registration page with email

  • Paulo Abner Aurélio Mesquita

    I use http://tokenapi.herokuapp.com/ service, but it works only with brazilian phone numbers

  • Am

    hiii ravi u r awesome bro…dont have words to praise….but man u r the best…a real programmer and i really want to make myself like u….i m also doing programing in android from last 1 and half years but i cant say myself a real programmer…dude could you guide me that how could i make myself like you “a real programmer”….pls reply…

  • Pushpender Bhandari

    awesome tutorials as always (y) keep it up…!!!

  • Okechukwu Eze

    i keep getting this error

    java.lang.RuntimeException: Unable to
    instantiate activity
    ComponentInfo{okechukwu.com.smsverificationapp/okechukwu.com.smsverificationapp.MyApplication}:
    java.lang.ClassCastException:
    okechukwu.com.smsverificationapp.MyApplication cannot be cast to
    android.app.Activity

    and even before execution, my manifest file keeps flagging the same error on

    android:name=”.app.MyApplication”

    The amazing thing is the copy i downloaded online works fine.
    I have been debugging this same issue for about 2 days and i cant seem to figure out my own app
    is flagging that message that “MyApplication is not assignable to android.app.Activity”

    can you guyz tell me what i am not doing right cos my eyez are already itching me!

  • Kalled Naggib Mitchel

    more easy cancel the step verification of sms whatsapp code, goto line, any address, i will go check this in lines of scripts for rotine, of the specific program, but i like idea, good idea, this verification like whatsapp…regards…..

    • jj

      if i give you email id will u be able to get me the password for tht plz?

  • Kalled Naggib Mitchel

    thank u for start this subject…creative, exclusive, autentic, like this, starting us any, good biggest project….i give u thanks, God bless u ! and all friends and brothers…. regards…

  • shulhan khairy

    can you make a tutorial about verification user via email?

  • devanshu

    I am not able to access the second part…can you please check? it is showing 502 Bad gateway..

  • Shubham

    Can you please provide me tutorial parse with twilio as cloud code sending OTP messages whenever new user register

  • August

    thanks for the tutorial, Ravi! but I have one question: what should I replace for MSG91_AUTH_KEY, 88276AGwzewOEdFs559d2888 and ANHIVE?

    define(‘MSG91_AUTH_KEY’, “88276AGwzewOEdFs559d2888”);
    // sender id should 6 character long
    define(‘MSG91_SENDER_ID’, ‘ANHIVE’);

    I can guess that 88…88 is the API key, MSG_SENDER_ID is my ID/email and ANHIVE is password, right? but what about MSG_AUTH_KEY? I use textlocal

  • Akhil

    Sir, i need to use an online server instead of localserver how can i achieve that….does any hosting website can be used for that?…if so please say me what to do

  • Rahul Am

    If your target is only India specific users, then do try out 2Factor – Two Factor Authentication For Web – Mobile – Apps , Which provides one step implementation for SMS OTP and is significantly faster over other solutions.

  • Rahul Am

    URL for 2Factor Auth service is ( http://2Factor.in )

  • Adam Poole

    Brilliant, thanks. Vericall offers a new technology that does this is a total different way. We recently launched a web API that initiates a Missed Call to perform a soft validation of a phone number. Additional specs for the Missed Call API and more information about the Early Adopter Program can be found -API for free authentication in the Cloud.

  • Jordani Rozon

    What the validation number? I’m getting number is not valid or missing.

    • Prathibha Nandini

      @jrozon05:disqus even I’m facing the same issue. Have you found any solution for it. @ravi8x:disqus Could you please help..?

      • Jordani Rozon

        I’ve changed to another API called Twilio, this one works very well.

        • Hadi Samadbin

          Dear Jordani, would u pls help me with Twilio config into this tutorial.what changes do I need in the code.Also when I test the Api with postman I got this :The requested URL /android_sms/request_sms.php was not found on this server….I will be very thank ful for ur helpl

      • apart from postman first of all you have to apply demo and check what is the error..because i was faced same problem then i tried the demo in my server that time its working..

    • Prathibha Nandini

      @jrozon05:disqus When I executed the files from app then it is working successfully.. With that ‘Postman’ I’m getting this error

  • Jerome

    Thank’s Ravi for this tutorial and your york! But I don’t understand why you don’t add an otp column in the user table in place of the sms_codes table? It seems to be less complex..

    • Its because some times there would be too much delay in receiving the OTP. In that case use might request for second OTP. And if he receives the first OTP, we should able to verify him. In other words we maintain all the otps user requested and verify him if he receives any one of them.

      • Jerome

        Ok, thank you for your feedback 🙂

  • Rohan

    Showing an error “Sorry! mobile number is not valid or missing.”

    • Hiskia Pasaribu

      don’t use URL parameter key. You should use form data of body tab.

      • Santosh

        Thank you. It helps lot

        • Ahana

          can you please help me from where i remove url and data from body tab i can’t understand properly ..help me for this

      • Vrushabh

        Thanks buddy it works for me!!

  • Adhiraj Singh Bais

    Hey Ravi, Thank you for your example of this kind We were working on a project which has this feature. Can u please guide us if necessary. I will be grateful to u.

  • Nijesh Narayanan

    I just don’t want email and name.
    I only want phone number…
    What to do,please help someone..

    • same here, i am also looking to capture the mobile number only, but the main problem is i dont know the coding and i am looking it to implement in a website, coders are charging too much money. 🙁

  • Thili Bu

    Thank you for awesome tutorial. Is the Msg91 works in Sri Lanka too?

    • I don’t think so. Please contact them once.

      • Rakesh Sahani

        sir help me..!!
        m getting this error..

        {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”}

        • Ahana

          hi,if you solve these error {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} so please help me solve this because i having these same error ,u also got same, so please help me to solve these ,i humble request to you please help me solve this and please reply sooner…please reply..

          • Madhav Tarkante

            I also getting {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} this error please help me

  • Nikhil Besra

    //Your message to send, Add URL encoding here.
    What is URL encoding??

  • Abhi Khatua

    sir i’m getting FATAL EXCEPTION: so please provide any suggestion

    • can you tell me actually in which line or which file you have to got the error..?

  • Android Developer

    which one is cheap and best otp sms gateway for android in india

    • i think you have to use gupshup sms

      • sameer khan

        After submitting name,email and mobile it’s not loading next page and in log cat its showing following errors

        E/SmsActivity: Posting params: {email=sravanidasari@gmail.com, name=sravs, mobile=8951074059}

        09-28 15:44:03.186 2464-3393/com.example.gangadhar.liketrue E/Volley: [99] BasicNetwork.performRequest: Unexpected response code 404 for http://192.168.1.9/android_sms/msg91/request_sms.php

        09-28 15:44:03.198 2464-2464/com.example.gangadhar.liketrue E/SmsActivity: Error: null

        09-28 15:44:05.215 2464-2660/com.example.gangadhar.liketrue E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa364e290

  • manoj kumar

    Hi bro nice tut…how to use mssql server for this purpose…

  • Naaz

    Hi, i followed ur tutorial but wen i tested the API it shows the exception “Failed to connect to MySQL” and the error is in 24 line of dbconnect.php. Any suggestions plz help!!

    • krushna

      chk ur…php connection php source code….plz check DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME….

  • sachin

    i have written all the codes right but at the execution time i am getting this {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”}.. so what to do now… i have given all the inputs at the time of execution like name , email, mobile

    • gorang agrawal

      Hey check out your php database there must be a mistake. And yes i have my own company making app for future requirements and i want members like me of fully addicted in android and ios coding.I have my 2 aps uploaded on google play store. C Programming & KKWP SBI Connect.I m not a pro but trying to make my own company.
      Visit http://www.inflamespga.com

      • sachin

        can u tell me what will be the problem exactly and which type of member do u want for ur company?

  • Android developer sh

    In my app m creating one login page to enter user mobile no., after it gets verified we move on to next page. if the no. is new, it will go to otp page and ask for otp and then to password page but if its existing no, it will directly switch to password page. the problem is after entering otp, error message is there showing: “error: No value for profile”. m not able to understand whethter its a problem in server that is php file or my code. please help me out

    • Saurabh Ojha

      hii bro have you got any solution for that problem
      i m also stuck ….with same problem

  • Hello Mr Ravi Tamada. Thanks for this great tutorial. Though i have a small issue here. I followed all the steps to setup and when test the request_sms script i get the {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} meaning there is an error. To highlight on this, Am using our companies SMS gateway service which only allows specifying parameters in XML format in order to POST the data. Could you please assist me on how i can embed the $mobile and $otp in my XML script? we are currently using these paramaters

    SENDMSG

    SMS

    How can i be able to incoporate the mobile and opt strings with this format?
    Thank you

  • Sinovuyo Lumka

    How do I use that same code but send the OTPs via email instead of via SMS? Is that possible?

  • Thank you sir.. awesome tutorial as always (y) keep it up…

  • hello sir i have one query can you help me..?
    an user is registered one time and create his account successfully but in case he log out from app and now he want to log in again in app then what we have to do for reloogin.
    Thanks in advance.

  • if want to store otp in session variable instead of database then what can i do.?
    anyone help me please.?

  • same

    Excellent Tutorial!!
    I have one issue, currently its only allow to use 10 digit number but i am using Msg91 OTP route for international numbers so how can i use mobile number with country code

  • Kavan Vadaliya

    {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} showing this error on postman pls sloved this error

    • lanoo

      The same message for me too. please guide some one…

      • Ahana

        i got same error too,please help me if u solve this error .please reply sooner

    • Madhav Tarkante

      {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”}
      i am getting same proble like if u have solved this problem please help me

  • GMAKER

    where is the tutorial

    • Rohit Kumar

      that’s something for you to do

  • JK Khant

    {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} showing this error on postman pls sloved this error

  • subash khati

    works great !! thanks. Can anybody help me with angularjs or ionic. Thank you.

    • Ahana

      hi.can you please solve this error {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”} showing this error on postman pls sloved this error..reply as soon as possible

      • Madhav Tarkante

        if u have solved this problem please help me

        • Madhav Tarkante

          Hello
          Above probelm is solved please Use GET insted Of POST For only Postman testing and when u call from android then use as it is POST

  • Neeraj Upadhyay

    Thanku soo much sir i want to add tracking application with your sms(otp) application how chould i do that please help me about

  • final

    Hi ravi you given the link for Android page is http://192.168.0.101/android_sms/msg91/request_sms.php, but in the android_sms folder, inside the android_sms folder, we are creating one folder called include in that folder config page , db page every thing, my question is http://192.168.0.101/android_sms/msg91/request_sms.php; why this msg91

    • Msg91 is the sms gateway we are using. So I named that folder as msg91. You might want to include multiple sms gateways incase of bigger apps. Thats why.

      • Immaculata Ubah

        i know this is out of line but need help with building an android quiz like app. how can i get in touch with you.

      • Madhav Tarkante

        please solve this error {“error”:true,”message”:”Sorry! mobile number is
        not valid or missing.”} showing this error on postman pls sloved this
        error..reply as soon as possible

  • Shreyansh Sharma

    Hi Ravi glad to have your assistance on previous problem.Here I am
    incorporating the sms verification app into same app and have more or
    less used your code to check once how it is working.However I am facing
    this error once i click on next button .
    I cant see how this issue is coming up because the MyApplication instance is already defined(like in your code)

    FATAL EXCEPTION: main
    java.lang.NullPointerException: Attempt to invoke virtual method ‘void
    badebaba.tscore.SMS.MyApplication.addToRequestQueue(com.android.volley.Request)’
    on a null object reference
    at badebaba.tscore.SMS.SmsActivity.requestForSMS(SmsActivity.java:253)
    at badebaba.tscore.SMS.SmsActivity.validateForm(SmsActivity.java:162)
    at badebaba.tscore.SMS.SmsActivity.onClick(SmsActivity.java:122)
    at android.view.View.performClick(View.java:4756)
    at android.view.View$PerformClick.run(View.java:19749)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

    • Madhavi Ajudiya

      hii
      shreyansh sharma this same error raise in my application. Do you have any solution

  • vardhan3814

    Thank you sir, for sharing this . I talked to Msg91 customer care, they informed they doesn’t provide REST API services. Should i buy the services from them?

  • kanika Tandel

    Awsome article.it’s very help for me .great article..thanks a lot Ravi.

    • Mritunjay Singh Khichi

      does it manage session means after login i close app and again then open i dont have to login again

  • kanika Tandel

    ..

  • Jayraj Patel

    I replaced setOnPageChangeListener with addOnPageChangeListener as the latter is deprecated but still the page does not change after the request is finished.

  • Vikrant

    Thanks Ravi, it worked..
    Am glad people like your are there.
    Thanks a lot again. 😀

    • Simran Sharma

      hi..can you help me please

  • Madhav Tarkante

    {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”}
    i am getting this type of error please help

    • Akshay Mishra

      change POST to GET in request_sms.php file

      <?php
      include './include/DbHandler.php';
      $db = new DbHandler();
      $response = array();
      if (isset($_GET['mobile']) && $_GET['mobile'] != '') {

      $name = $_GET['name'];

      $email = $_GET['email'];

      $mobile = $_GET['mobile'];

  • Mritunjay Singh Khichi

    does it manage session means after login i close app and again then open i dont have to login again, thanks…

    • Abdel

      No it doesn’t, you have to do it your self throught sharedPereferences for example.

  • Ibrahim Samad

    Hi ravi, I want to find out why we should have 1 to many relationship between the users table and sms_codes table if at the end of the day we still delete old codes that already exists?

  • Omkar Kumbhar

    Hi Ravi sir ! nice tutorial, sir OTP is send to only server database(sms table) . the problem is OTP not receive on mobile. Please help to resolve this. thnx! in advance.

    • Kumar Shivam

      same problem. did you find the solution?

  • Madhavi Ajudiya

    FATAL EXCEPTION: main
    Process: com.example.madhavi.sendotpmsg, PID: 32543
    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.example.madhavi.sendotpmsg.app.MyApplication.addToRequestQueue(com.android.volley.Request)’ on a null object reference
    at com.example.madhavi.sendotpmsg.activity.SmsActivity.requestForSMS(SmsActivity.java:217)
    at com.example.madhavi.sendotpmsg.activity.SmsActivity.validateForm(SmsActivity.java:144)
    at com.example.madhavi.sendotpmsg.activity.SmsActivity.onClick(SmsActivity.java:109)
    at android.view.View.performClick(View.java:4756)
    at android.view.View$PerformClick.run(View.java:19761)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:921)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:716)

  • aamrin

    sir when i check request sms inbpostman it show error on curl(init) err fatal err how i solve this err please help and reply soon as possible

  • Justin Poo

    Hey sir, could you share on how to do the same but with email? OTP sent to email for verification 🙂
    Thanks!!

  • Akash Pathak

    how to get OTP code default in our Edit field …?

  • Prasanth Jhon

    Super fantastic blog i lov it, great boss……, supppppppppppppppppppppppppper

  • Vrushabh

    In postman testing i am getting error:

    {“error”:true,”message”:”Sorry! mobile number is not valid or missing.”}

    what should i do

    • Vrushabh

      query solved.
      instead of using url parameters.
      use body parameters it works for me.

  • Vrushabh

    Thank you Ravi sir…
    This tutorial is very helpful for me..