YouTube Icon

Code Playground.

How to integrate OTP(One Time Password) in LARAVEL form

CFG

How to integrate OTP(One Time Password) in LARAVEL form

web.php(route)

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// Route::get('/', function () {
//     return view('welcome');
// });

Route::get('/','InsertController@index');
Route::post('/submitForm','InsertController@submitForm');
Route::post('/submitotp','InsertController@submitOtp');
Route::get('/showresult','InsertController@show');

insert_form.blade.php

@extends('common/footer')
@extends('common/sidemenu')
@extends('common/header')
@section('content')
<div class="container">
  <h2>OTP Integration</h2>
  <!-- <form action="/action_page.php"> -->
  <div id="formdiv" class="show">
    <input type="hidden" id="csrf" value="{{Session::token()}}">
  <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
    </div>
    <div class="form-group ">
      <label for="Mobile">Mobiel:</label>
      <div class="input-box">
      <input type="text" class="fixedTxtInput" id="mobile" placeholder="Enter 10 digits Mobile Number" name="mobile">
      <span class="unit">+91</span>
      </div>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <!-- <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
    </div>
     -->
    <button id="submitForm" class="btn btn-primary">Submit</button>
</div> <!-- form div close  -->
    <div id="otpdiv" class ="hide">
    <div class="form-group">
      <label for="emotpail">OTP:</label>
      <input type="otp" class="form-control" id="otp" placeholder="Enter OTP" name="otp">
    </div>
    <button id="otpSubmit" class="btn btn-primary">Submit</button>
</div>
  <!-- </form> -->
</div>
<script src="js/generateOTP.js"></script>

@endsection

header.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel demo</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <!-- Style -->
    <style>
        .input-box { position: relative; }
        .unit { position: absolute; display: block; left: 5px; top: 10px; z-index: 9; }
        .fixedTxtInput { display: block; border: 1px solid #d7d6d6; background: #fff; padding: 10px 10px 10px 30px; width: 100%; }
    </style>
    </head>
    <body>
    @yield('content')
    </body>
</html>

InsertController.php (controller)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\OtpVerify;

class InsertController extends Controller
{
    public function index(){
        return view('insert_form');
    }
    public function generateOTP(){
        $otp = mt_rand(1000,9999);
        return $otp;
    }

    public function submitForm(){
        $name = request('name');
        $mobile = request('mobile');
        $email = request('email');
        $authKey =  env('AUTH_KEY',"");
        if($mobile==''){
            return json_encode(array('statusCode'=>400,'msg'=>"Mobile number not valid".$mobile));
        }
        // else if($authKey==""){
        //     return json_encode(array('statusCode'=>400,'msg'=>"sms gateway not intigrated"));
        // }
        else{
            //put in session
            $otp = $this->generateOTP();
            $message = 'you otp is '.$otp;
            //$number = '+91'.$mobile;
            //sms($number,$msg)
            // $route = "route=4";
			// 	/*Prepare you post parameters*/
			// 	$postData = array(
			// 	'authkey' => $authKey,
			// 	'mobiles' => $mobile,
			// 	'message' => $message,
			// 	'sender' => $senderId,
			// 	'route' => $route
			// 	);
			// 	/*API URL*/
			// 	$url="https://control.msg91.com/api/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);
            //     exit;
			// 	}
			// 	curl_close($ch);

           session(['name'=> $name]);
           session(['mobile'=> $mobile]);
           session(['email'=> $email]);
           session(['otp' => $otp]);
            return json_encode(array('statusCode'=>200,'msg'=>'otp sent successfully'.$otp));
        }
        
    }
    public function submitOtp(){
        $otp = trim(request('otp'));
        if($otp==''){
            return json_encode(array('statusCode'=>400,'msg'=>"otp not valid"));
        }
        else{
            $user = new OtpVerify;
            if($otp == session('otp')){
            $name = session('name');
            $mobile = session('mobile');
            $email = session('email');
            $user->save();
            session()->flush();
            json_code(array('statusCode'=>200,'msg'=>'sucess'));

            }
            else{
                return json_encode(array('statusCode'=>400,'msg'=>"otp not valid"));
            }
        }
    }
    public function show(){
        return view('home');
    }

}

OtpVerify.php (model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OtpVerify extends Model
{
    
}
generateOTP.js
$(function(){
    $("#submitForm").click(function(){
        var name=$("#name").val();
        var mobile= $("#mobile").val();
        var email = $("#email").val();
        var token = $("#csrf").val();
       $.ajax({
        url:'/submitForm',
        type:'POST',
        data:{
            _token:token,
            name:name,
            mobile:mobile,
            email:email},
        success:function(result){
            var result = JSON.parse(result);
            // alert(result);
            if(result.statusCode == 200){
                    $("#formdiv").removeClass('show');
                    $("#formdiv").addClass('hide');
                    $("#otpdiv").removeClass('hide'); 
                    $("#otpdiv").addClass('show'); 
                    }
            else{
                alert("something wrong... please try later");
            }
        }
       })
    })

    $("#otpSubmit").click(function(){
        var otp = $("#otp").val();
        otp = otp.trim();
        var token = $("#csrf").val();
        console.log("---",otp);
        $.ajax({
            type:"post",
            url:'/submitotp',
            data:{
                _token:token,
                otp:otp
            },
            success:function(otpResult){
                otpResult = JSON.parse(otpResult);
                if(otpResult.statusCode == 200){
                    location.replace("/showresult");
                }
                else{
                    alert("otp not match. Please try again");
                }
            }
        })
    })
})

home.blade.php

@extends('common/footer')
@extends('common/sidemenu')
@extends('common/header')
@section('content')
<h2> welcome to home</h2>
@endsection

 




CFG