Как интегрировать Google reCAPTCHA версии 3 на стороне клиента и на стороне сервера (php). следующий код используется для отображения recaptcha, но он не работает хорошо. Как сделать эту интеграцию.
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js?render=6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD'></script>
</head>
<body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD', {
action: 'action_name'
});
});
</script>
<form action="verify.php" method="post">
<input type="text" name="name" placeholder="Your name" required>
<input type="email" name="email" placeholder="Your email address" required>
<textarea name="message" placeholder="Type your message here...." required></textarea>
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js?render=6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD'></script>
</head>
<body>
<script>
// when form is submit
$('form').submit(function() {
// we stoped it
event.preventDefault();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD', {action: 'create_comment'}).then(function(token) {
// add token to form
$('form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('form').prepend('<input type="hidden" name="action" value="create_comment">');
// submit form now
$('form').unbind('submit').submit();
});;
});
});
</script>
<form action="verify.php" method="post">
<input type="text" name="name" placeholder="Your name" required >
<input type="email" name="email" placeholder="Your email address" required>
<textarea name="message" placeholder="Type your message here...." required></textarea>
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
PHP
$token = $_POST['token'];
$secret = 'ur secret';
$action = $_POST['action'];
// now you need do a POST requst to google recaptcha server.
// url: https://www.google.com/recaptcha/api/siteverify.
// with data secret:$secret and response:$token
На этом этапе в коде вам нужно будет отправить запрос в ReCAPTCHA, чтобы проверить токен, как описано здесь: https://www.google.com/recaptcha/api/siteverify. Ответом будет объект json с полем «успех» (true / false) и «действие» для сравнения (==) и оценки (число от 0.0 до 1.0)
https://developers.google.com/recaptcha/docs/v3#api-response.
Вы также можете указать имя действия для каждого запроса (create_post, update_post, create_comment …)
Попробуй это.
<script>
grecaptcha.ready(function() {
grecaptcha.execute('<site-secret>', {action: 'MyForm'})
.then(function(token) {
console.log(token)
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
<form action="verify.php" method="post">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="text" name="name" placeholder="Your name" required >
<input type="email" name="email" placeholder="Your email address" required>
<input type="submit" name="submit" value="SUBMIT" >
</form>
Вот пример рабочего кода с демо.
HTML-код стороны
<html>
<head>
<title>Google recapcha v3 demo - Codeforgeek</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=put your site key here"></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="form.php" method="post" >
<input type="email" name="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
</form>
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stoped it
event.preventDefault();
var email = $('#email').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{email: email, comment: comment, 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>
Код PHP
<?php
$email;$comment;$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$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'));
}
?>
Работает нормально.
Демо-версия: https://demo.codeforgeek.com/recaptcha-v3/
руководство: https://codeforgeek.com/2019/02/google-recaptcha-v3-tutorial/