Chào mừng!

Bằng cách đăng ký với chúng tôi, bạn sẽ có thể thảo luận, chia sẻ và nhắn tin riêng tư với các thành viên khác trong cộng đồng của chúng tôi.

Đăng ký ngay!
  • Chào Khách,
    Bạn cần liên hệ với admin ??? ZALO & TELEGRAM

Share Share Code Xác Thực PhoneNumber Bằng Firebase

Tham gia
9/3/19
Bài viết
31
Lượt Thích
5
Coins
1,220
Haiza, có thể bài viết này nhiều người biết rồi, nhưng hôm nay mình sẽ chia sẻ kinh nghiệm bản thân của mình cho những ai thật sự cần 1 dịch vụ xác thực SMS miễn phí.

Cấu hình xác thực số điện thoại với Firebase
Nếu bạn chưa có tài khoản Firebase, Vào https://console.firebase.google.com đăng ký một tài khoản miễn phí.

Tạo một dự án mới
Mở phần Authentication ở thanh bên trái.
Trên trang Sign-in Method, kích hoạt phương thức Phone Number sign-in.
Đảm bảo rằng tên miền của bạn được liệt kê trong phần Authorized Domains.

Bây giờ, quay trở lại màn hình tổng quan của project và click vào nó. Sau đó bấm Add Firebase to your Web app . Một popup sẽ hiển thị như sau:


Thay nó vào đoạn code dưới đây (đây là code mẫu mình làm sẳn cho các bạn luôn nhé):

File index.html
Mã:
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example SMS Firebase</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
  <script>
    var firebaseConfig = {
      apiKey: "apiKey",
      authDomain: "authDomain",
      databaseURL: "databaseURL",
      projectId: "projectId",
      storageBucket: "storageBucket",
      messagingSenderId: "messagingSenderId",
      appId: "appId",
      measurementId: "measurementId"
    };
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
  </script>
</head>

<body>

  <div class="container">
    <h2>Demo Form</h2>
    <form action="" id="dangky_f">
      <div class="form-group">
        <label for="email">Phone:</label>
        <input type="text" class="form-control" id="phone" value="+84" name="phone">
      </div>
      <div class="form-group">
        <label for="email">Xác nhận hơm phải rô bốt:</label>
        <div id="recaptcha-container"></div>
      </div>
      <button type="button" id="phoneSendAuthB" onclick="phoneSendAuth();" style="border-radius: 15px" class="btn btn-info">
        Lấy OTP
      </button>
      <hr>
      <div class="form-group">
        <label for="pwd">OTP:</label>
        <input type="text" class="form-control" id="otp" placeholder="Enter OTP" name="otp">
        <input type="hidden" class="form-control" id="token" name="token" value="">
      </div>
      <button type="button" id="codeverifyB" onclick="codeverify();" style="border-radius: 15px" class="btn btn-info">
        Xác thực
      </button>
    </form>
    <hr>
    <button type="button" id="dangkyB" style="border-radius: 15px" class="btn btn-success">
      Đăng Ký
    </button>
  </div>

</body>
<script>
  window.onload = function() {
    render();
  };

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

  function phoneSendAuth() {

    var number = $("#phone").val();
    firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function(confirmationResult) {

      window.confirmationResult = confirmationResult;
      coderesult = confirmationResult;

    }).catch(function(error) {
      swal(">.<", error.message, "error");
    });

  }

  function codeverify() {

    var code = $("#otp").val();
    document.getElementById("codeverifyB").disabled = true;
    coderesult.confirm(code).then(function(result) {
      var user = result.user;
      document.getElementById("token").value = user._lat;

    }).catch(function(error) {
      swal(">.<", error.message, "error");
    });
  }
  $(document).ready(function() {
    $("#dangkyB").click(function() {
      var data = $("#dangky_f").serializeArray();
      $.ajax({
        type: 'POST',
        url: 'login.php',
        data: data,
        dataType: 'json',
        success: function(data) {
          if (data.status == "1") {
            swal("Good job!", data.contents, "success");
          } else {
            swal(">.<", data.contents, "error");

          }
        },
        error: function(data) {
          alert("Error");
        }
      });

    });
  });
</script>

</html>
#### File login.php
Mã:
<?php


$url = "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=[API_KEY]";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
    "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{"idToken":"' . $_POST['token'] . '"}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
$checkPhone = json_decode($resp, true);
$tokenID = $checkPhone['users'][0]['localId'];
$phoneGet = $checkPhone['users'][0]['phoneNumber'];
if (empty($tokenID)) {
    $json['status'] = 0;
    $json['contents'] = "Số điện thoại không hợp lệ!";
    echo json_encode($json);
    exit;
}
if ($_POST['phone'] != $phoneGet) {
    $json['status'] = 0;
    $json['contents'] = "Số điện thoại không hợp lệ!";
    echo json_encode($json);
    exit;
}
$json['status'] = 1;
$json['contents'] = "Đăng nhập thành công!";
echo json_encode($json);
exit;
Một điều nữa. Để tránh lạm dụng, Firebase có giới hạn về số lượng tin nhắn SMS có thể được gửi đến một số điện thoại duy nhất trong một khoảng thời gian. Nếu bạn vượt quá giới hạn này, số điện thoại đó có thể bị khóa trong một thời gian. Nếu bạn gặp phải vấn đề này, hãy sử dụng các số điện thoại khác nhau để thử nghiệm, hoặc thử yêu cầu ở một thời điểm khác.

Nếu bạn có bất kỳ câu hỏi thắc mắc hãy để lại ý kiến dưới bài viết nhé. ?

Leech nhớ để nguồn PuaruVN - V4U nhé.
 
Tham gia
22/5/21
Bài viết
925
Lượt Thích
1,010
Coins
16,633
Haiza, có thể bài viết này nhiều người biết rồi, nhưng hôm nay mình sẽ chia sẻ kinh nghiệm bản thân của mình cho những ai thật sự cần 1 dịch vụ xác thực SMS miễn phí.

Cấu hình xác thực số điện thoại với Firebase
Nếu bạn chưa có tài khoản Firebase, Vào https://console.firebase.google.com đăng ký một tài khoản miễn phí.

Tạo một dự án mới
Mở phần Authentication ở thanh bên trái.
Trên trang Sign-in Method, kích hoạt phương thức Phone Number sign-in.
Đảm bảo rằng tên miền của bạn được liệt kê trong phần Authorized Domains.

Bây giờ, quay trở lại màn hình tổng quan của project và click vào nó. Sau đó bấm Add Firebase to your Web app . Một popup sẽ hiển thị như sau:


Thay nó vào đoạn code dưới đây (đây là code mẫu mình làm sẳn cho các bạn luôn nhé):

File index.html
Mã:
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example SMS Firebase</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
  <script>
    var firebaseConfig = {
      apiKey: "apiKey",
      authDomain: "authDomain",
      databaseURL: "databaseURL",
      projectId: "projectId",
      storageBucket: "storageBucket",
      messagingSenderId: "messagingSenderId",
      appId: "appId",
      measurementId: "measurementId"
    };
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
  </script>
</head>

<body>

  <div class="container">
    <h2>Demo Form</h2>
    <form action="" id="dangky_f">
      <div class="form-group">
        <label for="email">Phone:</label>
        <input type="text" class="form-control" id="phone" value="+84" name="phone">
      </div>
      <div class="form-group">
        <label for="email">Xác nhận hơm phải rô bốt:</label>
        <div id="recaptcha-container"></div>
      </div>
      <button type="button" id="phoneSendAuthB" onclick="phoneSendAuth();" style="border-radius: 15px" class="btn btn-info">
        Lấy OTP
      </button>
      <hr>
      <div class="form-group">
        <label for="pwd">OTP:</label>
        <input type="text" class="form-control" id="otp" placeholder="Enter OTP" name="otp">
        <input type="hidden" class="form-control" id="token" name="token" value="">
      </div>
      <button type="button" id="codeverifyB" onclick="codeverify();" style="border-radius: 15px" class="btn btn-info">
        Xác thực
      </button>
    </form>
    <hr>
    <button type="button" id="dangkyB" style="border-radius: 15px" class="btn btn-success">
      Đăng Ký
    </button>
  </div>

</body>
<script>
  window.onload = function() {
    render();
  };

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

  function phoneSendAuth() {

    var number = $("#phone").val();
    firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function(confirmationResult) {

      window.confirmationResult = confirmationResult;
      coderesult = confirmationResult;

    }).catch(function(error) {
      swal(">.<", error.message, "error");
    });

  }

  function codeverify() {

    var code = $("#otp").val();
    document.getElementById("codeverifyB").disabled = true;
    coderesult.confirm(code).then(function(result) {
      var user = result.user;
      document.getElementById("token").value = user._lat;

    }).catch(function(error) {
      swal(">.<", error.message, "error");
    });
  }
  $(document).ready(function() {
    $("#dangkyB").click(function() {
      var data = $("#dangky_f").serializeArray();
      $.ajax({
        type: 'POST',
        url: 'login.php',
        data: data,
        dataType: 'json',
        success: function(data) {
          if (data.status == "1") {
            swal("Good job!", data.contents, "success");
          } else {
            swal(">.<", data.contents, "error");

          }
        },
        error: function(data) {
          alert("Error");
        }
      });

    });
  });
</script>

</html>
#### File login.php
Mã:
<?php


$url = "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=[API_KEY]";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
    "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{"idToken":"' . $_POST['token'] . '"}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
$checkPhone = json_decode($resp, true);
$tokenID = $checkPhone['users'][0]['localId'];
$phoneGet = $checkPhone['users'][0]['phoneNumber'];
if (empty($tokenID)) {
    $json['status'] = 0;
    $json['contents'] = "Số điện thoại không hợp lệ!";
    echo json_encode($json);
    exit;
}
if ($_POST['phone'] != $phoneGet) {
    $json['status'] = 0;
    $json['contents'] = "Số điện thoại không hợp lệ!";
    echo json_encode($json);
    exit;
}
$json['status'] = 1;
$json['contents'] = "Đăng nhập thành công!";
echo json_encode($json);
exit;
Một điều nữa. Để tránh lạm dụng, Firebase có giới hạn về số lượng tin nhắn SMS có thể được gửi đến một số điện thoại duy nhất trong một khoảng thời gian. Nếu bạn vượt quá giới hạn này, số điện thoại đó có thể bị khóa trong một thời gian. Nếu bạn gặp phải vấn đề này, hãy sử dụng các số điện thoại khác nhau để thử nghiệm, hoặc thử yêu cầu ở một thời điểm khác.

Nếu bạn có bất kỳ câu hỏi thắc mắc hãy để lại ý kiến dưới bài viết nhé. ?

Leech nhớ để nguồn PuaruVN - V4U nhé.
Hmm
 
Top Bottom
AdBlock Detected

We get it, advertisements are annoying!

Sure, ad-blocking software does a great job at blocking ads, but it also blocks useful features of our website. For the best site experience please disable your AdBlocker.

I've Disabled AdBlock
No Thanks