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
  • 469 views

Recent posts

[WordPress] Hướng dẫn tạo Custom Action Hook trong WordPress

[WordPress] Hướng dẫn tạo Custom Action Hook trong WordPress

Tạo custom Action Hook trong WordPress là một kỹ năng rất hữu ích để tùy chỉnh và mở rộng chức […]

Cuộc chiến không hồi kết: “Trình duyệt CC” chặn quảng cáo

Cuộc chiến không hồi kết: “Trình duyệt CC” chặn quảng cáo

Người dùng internet không còn lạ lẫm gì trước những “chiêu” được “hãng Y” sử dụng, nhằm hạn chế việc […]

Windows có lỗ hổng nghiêm trọng, Microsoft biết nhưng từ chối sửa

Windows có lỗ hổng nghiêm trọng, Microsoft biết nhưng từ chối sửa

Một lỗ hổng bảo mật trên Windows có “cửa hậu” cho phép đăng nhập bằng mật khẩu cũ. Một phát […]

Apple phát hành iOS 18.5 RC: Sắp ra mắt chính thức?

Apple phát hành iOS 18.5 RC: Sắp ra mắt chính thức?

Apple phát hành phiên bản Release Candidate (RC) của iOS 18.5 và iPadOS 18.5 đến các nhà phát triển cũng như người dùng tham gia […]

Apple cập nhật ứng dụng Move to iOS, nâng cấp tốc độ truyền tải

Apple cập nhật ứng dụng Move to iOS, nâng cấp tốc độ truyền tải

Move to iOS là ứng dụng của Apple để giúp người dùng Android khi chuyển sang hệ sinh thái của Apple, cụ thể là iOS […]

© 2021 Tạp Chí CNTT. Mr Hoang