Google đã ra mắt reCAPTCHA v3 để ngăn chặn các bot spam mà không có bất kỳ sự tương tác nào của người dùng. reCAPTCHA v3 trả lại cho chúng tôi các thư rác để thực hiện các tác vụ khác nhau trong ứng dụng web của bạn.

Bài hướng dẫn này, tôi sẽ hướng dẫn cho bạn cách tích hợp Google reCAPTCHA v3 vào trang web của bạn.

Demo | Download

Đầu tiền bạn đăng ký tại Google reCAPTCHA để nhận Secret Key cho trang web của bạn.

Đăng nhập vào tài khoản Google của bạn và tạo ứng dụng bằng cách điền vào biểu mẫu.

Chọn reCAPTCHA v3 .

Sau khi gửi, Google sẽ cung cấp cho bạn hai thông tin sau.

Chèn đoạn code sau để tích hợp Google reCAPTCHA vào website của bạn

<script src="https://www.google.com/recaptcha/api.js?render=put_your_site_key_here"></script>

Google reCAPTCHA v3 đã được chèn thành công vào website của bạn

Bạn cần xử lý phản hồi captcha của google trong mã JavaScript của mình.

<script src="https://www.google.com/recaptcha/api.js?render=put_your_site_key_here"></script>
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('put your site key here', {action: 'homepage'}).then(function(token) {
        // pass the token to the backend script for verification
      });
  });
</script>

Sau đây là đoạn code HTML hoàn chỉnh về cách thức sử dụng Google reCAPTCHA v3

<!DOCTYPE html>
<html>
<head>
<title>Coming soon - Ly Minh Hoang</title>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="application/x-javascript">
	addEventListener("load", function() { 
		setTimeout(hideURLbar, 0); 
	}, false);
	function hideURLbar(){ 
		window.scrollTo(0,1);
	}
</script>
<link href="https://lyminhhoang.com/layout/css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href='https://fonts.googleapis.com/css?family=Philosopher:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text/css'>
<script src="https://www.google.com/recaptcha/api.js?render=put_your_site_key_here"></script>
</head>

<body>
	
	<div class="main">
		<h1>Coming Soon</h1>
		<div class="main-row">
			<p></p>
			<div class="w3ls-img"> 
				<img src="layout/images/logo.png" width="64px" alt=""/>
			</div>	
			<div class="agileits-timer"> 
				 <div class="clock">
					<div class="column days">
						<div class="timer" id="days"></div>
						<div class="text">DAYS</div>
					</div>
					<div class="timer days">:</div>
					<div class="column">
						<div class="timer" id="hours"></div>
						<div class="text">HOURS</div>
					</div>
					<div class="timer">:</div>
					<div class="column">
						<div class="timer" id="minutes"></div>
						<div class="text">MINUTES</div>
					</div>
					<div class="timer">:</div>
					<div class="column">
						<div class="timer" id="seconds"></div>
						<div class="text">SECONDS</div>
					</div>
				</div>	
			</div>
			<div class="wthree-sub">
				<form id="contact_form" action="#" method="post">
					<input type="email" id="email" name="Search" placeholder="Enter your Email..." required="">
					<button type="submit" class="btn btn-default" aria-label="Left Align">
						<img src="layout/images/i2.png" alt=""/>
					</button>
				</form>  
			</div>	
		</div>
		<!-- copyright -->
		<div class="copyright">
			<p> © 2017 Coming Soon.</p>
		</div>
		<!-- //copyright -->
	</div>	
	<script  src="https://lyminhhoang.com/layout/js/jquery-1.12.3.min.js"></script>
	<script type="text/javascript" src="https://lyminhhoang.com/layout/js/moment.js"></script>
	<script type="text/javascript" src="https://lyminhhoang.com/layout/js/moment-timezone-with-data.js"></script>
	<script type="text/javascript" src="https://lyminhhoang.com/layout/js/timer.js"></script>
	
	<script src="https://www.google.com/recaptcha/api.js?render=put_your_site_key_here"></script>
	<script>
		$('#contact_form').submit(function() {
			event.preventDefault();
			var email = $('#email').val();
			grecaptcha.ready(function() {
				grecaptcha.execute('put_your_site_key_here', {action:'contact_form'}).then(function(token) {
					
					$('#contact_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
					
					$.post("contact.php",{email: email, token: token}, function(result) {
                            
							console.log(result);

                            if(result.success) {
                                    alert('Thanks for posting comment.')
                            } else {
                                    alert('You are spammer ! Get the @$%K out.')
                            }
                    });
				
			  });
			});
		});
	</script>
	
</body>
</html>

Trang web của bạn sẽ hiển thị như sau:

Khi website của bạn hiển thị như trên, bạn đã tích hợp thành công Google reCAPTCHA v3

<?php
	$email;$captcha;
	$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
	$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
  
	if(!$captcha){
		echo '<h2>Please check the the captcha form.</h2>';
		exit;
	}
	$secretKey = "-----put your secret here------";
	$ip = $_SERVER['REMOTE_ADDR'];
	// post request to server
	$url = 'https://www.google.com/recaptcha/api/siteverify';
	$data = array('secret' => $secretKey, 'response' => $captcha);
	$options = array(
		'http' => array(
			'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
			'method'  => 'POST',
			'content' => http_build_query($data)
		)
	);
	$context  = stream_context_create($options);
	$response = file_get_contents($url, false, $context);
	$responseKeys = json_decode($response,true);
	header('Content-type: application/json');
	if($responseKeys["success"]) {
		echo json_encode(array('success' => 'true'));
	} else {
		echo json_encode(array('success' => 'false'));
  }
?>

Chúc các bạn thành công!

  • Jquery, PHP
  • November 8, 2019
  • 0 comment
  • 108 views

Recent posts

iPhone 16 Pro Max lộ giá bán

iPhone 16 Pro Max lộ giá bán

Dự kiến giá của iPhone 16 Pro Max sẽ tăng thêm 100 USD (khoảng 2,5 triệu đồng) với bất kỳ […]

Người dùng sắp được chuyển ảnh dễ dàng từ Google Photos sang Apple iCloud

Người dùng sắp được chuyển ảnh dễ dàng từ Google Photos sang Apple iCloud

Trong một phần của sáng kiến Chuyển tải Dữ liệu (Data Transfer Initiative – DTI), người dùng sẽ có thể […]

iOS 18 giúp ‘Trung tâm điều khiển’ trên iPhone đổi mới hoàn toàn

iOS 18 giúp ‘Trung tâm điều khiển’ trên iPhone đổi mới hoàn toàn

Apple sẽ thiết kế lại hoàn toàn khu vực Trung tâm điều khiển trên iPhone trong bản cập nhật iOS […]

iPhone 16 Pro sẽ sử dụng màn hình ‘xịn nhất’ của Samsung

iPhone 16 Pro sẽ sử dụng màn hình ‘xịn nhất’ của Samsung

iPhone 16 Pro và 16 Pro Max được dự đoán là những mẫu điện thoại đầu tiên trang bị tấm […]

Cách đọc tin nhắn trên Zalo mà người gửi không biết

Cách đọc tin nhắn trên Zalo mà người gửi không biết

Nếu là người thường xuyên sử dụng Zalo để nhắn tin hay gọi điện, nhưng lại muốn “ẩn danh” và […]

© 2021 Tạp Chí CNTT. Mr Hoang