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

Recent posts

Hàng siêu cao cấp, iPhone gập sẽ có giá cao ngất ngưởng

Hàng siêu cao cấp, iPhone gập sẽ có giá cao ngất ngưởng

iPhone Fold – chiếc iPhone gập được đồn đại từ lâu của Apple – có thể sẽ là một sản […]

Người dùng iPhone cần cập nhật ngay iOS 18.4.1 vì lý do bảo mật nghiêm trọng

Người dùng iPhone cần cập nhật ngay iOS 18.4.1 vì lý do bảo mật nghiêm trọng

Apple cho biết các lỗ hổng bảo mật này có khả năng đã được sử dụng trong một cuộc tấn […]

[Thủ thuật] Xóa menu “WordPress” khỏi thanh quản trị

[Thủ thuật] Xóa menu “WordPress” khỏi thanh quản trị

Bạn muốn xóa menu “WordPress” (thường có biểu tượng chữ W) khỏi thanh quản trị (wp-admin bar) và các mục […]

POCO M7 Pro mẫu smartphone 5G giá siêu rẻ của Xiaomi

POCO M7 Pro mẫu smartphone 5G giá siêu rẻ của Xiaomi

POCO M7 Pro là mẫu smartphone 5G giá siêu rẻ của Xiaomi, chỉ hơn 4 triệu đồng nhưng vẫn được […]

Hóa ra “đường link màu tím” trên Chrome không chỉ là tính năng, nó còn là lỗ hổng bảo mật 16 năm tuổi

Hóa ra “đường link màu tím” trên Chrome không chỉ là tính năng, nó còn là lỗ hổng bảo mật 16 năm tuổi

Chỉ mới đây thôi, Google phát hành bản vá cho một lỗ hổng nghiêm trọng trong trình duyệt Chrome đã […]

© 2021 Tạp Chí CNTT. Mr Hoang