今天都在研究 Google reCAPTCHA 這機制,相信大家都已經知道這是個反制機器人登入的好東西

依 iThome 於去年 10/30 說明的這篇文章,目前的 reCAPTCHA 已經出到了 v3,而 v3 和 v2 最大的差別就在於它不再要求使用者與網站之間的互動

而是依使用者的行為計算分數後,再讓網站管理者判斷是否要再進一步進行驗證

分享一下我的作法 ~ 首先要先到 reCAPTCHA Admin Console 建立 v3 的驗證資料,記得要勾選 v3 喔 !

建完之後會得二組金錀,一組是網站本身用的,另一組是用來和 Google 主機連線驗證使用,接下來分享我實作的程式碼

首先這是登入頁面的 index.php 程式

<html>
  <head>
    <title>Google recapcha v3</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://www.google.com/recaptcha/api.js?render=這邊填入網站本身的金錀">      
    </script>
    <script>
      grecaptcha.ready(function() {
      grecaptcha.execute('這邊填入網站本身的金錀', {action: 'homepage'}).then(function(token) {
        var recaptchaResponse = document.getElementById('recaptchaResponse');
        recaptchaResponse.value = token;
      });
  });
  </script>
  </head>
  <body>
    <h1>Google reCAPTHA Test</h1>
    <form id="testform" action="form.php" method="post" >
      <input type="email" name="email" placeholder="輸入email" size="40"><br><br>
      <input type="submit" name="submit" value="送出"><br><br>
      <input type="hidden" value="" name="recaptcha_response" id="recaptchaResponse">
    </form>
  </body>
</html>

接下來這是第二頁 form.php 程式

<?php
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '這邊填入和Google連線使用的金錀';
$recaptcha_response = $_POST['recaptcha_response'];

//Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);

//如果驗證成功,就進一步計算使用者分數,官方回饋分數為 0-1,分數愈接近 1 就是正常,低於 0.5 以下就有可能是機器人了
if($recaptcha->success==true){
   if($recaptcha->score >= 0.5) {
       echo 'Pass !';
   } else {
       echo 'Spammer';
   }  
} else {
  echo 'Connection failed';
}
?>

大概就是這樣,至於連線 Google 驗證回傳的值請再參考官網相關說明

reCAPTCHA v3

Verifying the user's response

參考資料

1. recaptcha v3 with php

2. https://gist.github.com/webeasystep/85a20c9278dc5c3763ef82848c7d0558

arrow
arrow
    全站熱搜

    Bojack 發表在 痞客邦 留言(0) 人氣()