Get Appointment

Blog Single

Verify Mobile Number via OTP in Laravel with Bootstrap Modal using firebase Introduction

  • Vfix Technology
  • 23 Dec 2023
  • Laravel
  • 59 Views

Introduction  

Ensuring secure user verification is paramount in any web application. In this article, we delve into a streamlined process of verifying mobile numbers via OTP in Laravel. Leveraging the power of Firebase and integrating it with Bootstrap Modal, we'll explore an efficient method to authenticate users, enhancing both security and user experience.

Why Mobile Number Verification?

Mobile number verification adds an extra layer of security to your application by confirming the user's identity. It is particularly crucial in applications that handle sensitive information or require secure user authentication.

If don'k know how to create start please check Verify Mobile Numbers via OTP in Laravel using firebase

Step1: Create the form in the bootstrap modal

<div
  class="modal fade"
  id="exampleModal"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-body">
        {{--
        <button
          type="button"
          class="btn-close float-end"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
        --}}
        <div class="row g-4 align-items-center">
          <div class="col-md-10">
            <span class="fs-5 text-dark">
              Get best quote
              <span class="text-muted"
                >and detail from "{{ $setting->bname }}" on your mobile
                quickly</span
              >
            </span>
            <form action="{{ route('enquiry.store') }}" method="POST">
              @csrf
              <div class="row g-3">
                <div class="col-md-12">
                  <div class="form-floating">
                    <input
                      type="text"
                      name="name"
                      value="{{ old('name') }}"
                      class="form-control mt-3"
                      id="name"
                      placeholder="Your Name"
                    />
                    @error('name')
                    <span class="text-danger">{{ $message }}</span>
                    @enderror
                    <label for="name">Your Name</label>
                  </div>
                </div>
                <div class="col-md-12">
                  <div class="form-floating">
                    <input
                      type="email"
                      name="email"
                      value="{{ old('email') }}"
                      class="form-control"
                      id="email"
                      placeholder="Your Email"
                    />
                    @error('email')
                    <span class="text-danger">{{ $message }}</span>
                    @enderror
                    <label for="email">Your Email</label>
                  </div>
                </div>

                <div class="mb-3" id="otp-verify">
                  {{-- <label for="">Phone number</label> --}}
                  <div
                    class="alert alert-danger"
                    id="error"
                    style="display: none"
                  ></div>

                  <div
                    class="alert alert-success alert-dismissible fade show"
                    role="alert"
                    id="successAuth"
                    style="display: none"
                  >
                    <button
                      type="button"
                      class="btn-close"
                      data-bs-dismiss="alert"
                      aria-label="Close"
                    ></button>
                  </div>
                  <div class="input-group flex-nowrap">
                    <span class="input-group-text rounded-1" id="addon-wrapping"
                      ><img
                        style="width: 20px"
                        src="{{ asset('public/assets/img/india.svg') }}"
                        alt=""
                    /></span>
                    <input
                      type="tel"
                      class="form-control py-2 rounded-1"
                      value="{{ old('phone') }}"
                      id="phone"
                      name="phone"
                      placeholder="Your phone number"
                      oninput="formatPhoneNumber(this)"
                    />
                    <br />
                  </div>
                  <span>We will contact you on this number </span>

                  {{--
                  <input
                    type="tel"
                    class="form-control"
                    name="phone"
                    placeholder="Enter your phone number"
                    id="phone"
                  />
                  --}}
                  <div id="cod">
                    <div id="otpSendNumberHide">
                      <div class="pt-3" id="recaptcha-container"></div>
                      <span
                        class="form-text text-danger"
                        id="phoneError"
                      ></span>
                      <button
                        type="button"
                        class="btn btn-primary mt-3 rounded-1"
                        id="sendOTPBtn"
                        onclick="sendOTP();"
                      >
                        Send OTP
                      </button>
                    </div>
                    <div
                      class="mt-5"
                      id="verificationForm"
                      style="display: none"
                    >
                      <h3>Add verification code</h3>
                      <div
                        class="alert alert-success"
                        id="successOtpAuth"
                        style="display: none"
                      ></div>
                      <form>
                        <div class="form-floating">
                          <input
                            type="text"
                            class="form-control"
                            id="verification"
                            placeholder="Verification code"
                            disabled
                          />
                          <label for="otp">Enter Otp</label>
                          <div id="resendTimer" style="display: none">
                            Resend OTP in <span id="countdown">60</span> seconds
                          </div>
                        </div>
                        {{--
                        <input
                          type="text"
                          id="verification"
                          class="form-control"
                          placeholder="Verification code"
                          disabled
                        />
                        --}}
                        <button
                          type="button"
                          class="btn btn-danger rounded-1 mt-3"
                          id="verifyBtn"
                          onclick="verify()"
                          disabled
                        >
                          Verify code
                        </button>
                      </form>
                    </div>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-floating">
                    <textarea
                      class="form-control"
                      name="message"
                      placeholder="Leave a message here"
                      id="message"
                      style="height: 100px"
                    >
{{ old('message') }}</textarea
                    >
                    <label for="message">Message</label>
                  </div>
                </div>

                <div class="col-12">
                  <button
                    class="btn btn-primary rounded-pill py-3 px-5"
                    type="submit"
                  >
                    Send Message
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Here we are first going to verify the phone number and then we will get all the required details form the user like name, email and requirments.

Step2: Add the firebase configuration

<script>
  var firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "laravel-otp-85215.firebaseapp.com",
    projectId: "laravel-otp-85215",
    storageBucket: "laravel-otp-85215.appspot.com",
    messagingSenderId: "704974148084",
    appId: "1:704974148084:web:ab74b2bb8109b76198a9a1",
    measurementId: "G-7GHBE04FNQ",
  };
  firebase.initializeApp(firebaseConfig);
</script>

Add the firebase cdn and jquery cdn 

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase.js"></script>

Step3: Add the below js code 

<script type="text/javascript">
        window.onload = function() {
            render();
        };

        function render() {
            window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
            recaptchaVerifier.render();
        }

        var countdownInterval;

        function startCountdown() {
            var countdown = 60;
            $("#resendTimer").show();
            $("#sendOTPBtn").prop("disabled", true); // Disable the main OTP send button during countdown
            $("#sendOTPBtn").addClass("display-nonee"); // Disable the Resend OTP link
            $("#recaptcha-container").addClass("display-nonee"); // Disable the captcha

            countdownInterval = setInterval(function() {
                $("#countdown").text(countdown);
                countdown--;

                if (countdown < 0) {
                    clearInterval(countdownInterval);
                    $("#resendTimer").hide();
                    $("#sendOTPBtn").prop("disabled",
                        false); // Enable the main OTP send button after countdown ends
                    $("#sendOTPBtn").removeClass("display-nonee"); // Enable the Resend OTP link
                    $("#sendOTPBtn").text("Resend OTP"); // Enable the Resend OTP link
                    $("#recaptcha-container").removeClass("display-nonee"); // Enable the captcha
                }
            }, 1000);
        }

        function sendOTP() {
            var number = $("#phone").val();
            firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function(confirmationResult) {
                window.confirmationResult = confirmationResult;
                coderesult = confirmationResult;
                console.log(coderesult);
                $("#successAuth").text("Message sent");
                $("#successAuth").show();
                $("#verificationForm").show();
                $("#verification").prop("disabled", false);
                $("#verifyBtn").prop("disabled", false);
                // Enable the resend timer
                $("#sendOTPBtn").prop("disabled", true);
                $("#resendTimer").show();
                // $("#otpSendNumberHide").hide();
                startCountdown();
            }).catch(function(error) {
                $("#error").text(error.message);
                $("#error").show();
            });
        }

        function verify() {
            var code = $("#verification").val();

            if (confirmationResult) {
                confirmationResult.confirm(code).then(function(result) {
                    var user = result.user;
                    console.log(user);
                    $("#successOtpAuth").text("Auth is successful");
                    $("#successOtpAuth").show();

                    // Clear confirmation result
                    confirmationResult = null;

                    // Hide OTP verification div
                    $("#otp-verify").hide();

                    // Show the rest of the fields
                    $('#exampleModal .modal-body label, #exampleModal .modal-body :input').show();

                    $("#phone").show(false);
                }).catch(function(error) {
                    $("#error").text(error.message);
                    $("#error").show();
                });
                // clearInterval(countdownInterval);
                // $("#resendTimer").hide();
                // $("#sendOTPBtn").prop("disabled", false);
            } else {
                // Handle the case where confirmationResult is null
                console.error("Confirmation result is null");
            }
        }
    </script>

This code is responsible for the sending of the otp on the entered phone number you cusomize the timer success message according to your requirement



+91 8447 525 204 Request Estimate