[英]How to implement reCaptcha v3 by Google on a newsletter form?
我遇到了reCaptcha V3的问题。 问题在于,在记录分析和简报本身的逻辑时,我正在努力与服务器进行通信。 我试图让表单通过reCaptcha,从而确认用户不是机器人,如果是,那么用户输入的字段可以记录在数据库(firebase)上。 现在我已经设置了逻辑,用于记录数据库上的用户输入并连接前端的reCaptcha,但我似乎无法弄清楚如何使用Google的reCaptcha将前端连接到后端。
我已经尝试了不同的方法来连接它,因为StackOverflow已经有一些可靠的解决方案,但没有一个对我有用,因为我正在努力理解POST方法背后的逻辑。 我是一个javascript新手。 这就是我所做的:
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6LdFL6kUAAAAAH1J3WcBt9_s4dV2Rk-3wqlwETI9', {action: 'create_user'}).then(function(token) {
// add token to form
$('#newsletterform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("captcha.php",{ firstname: firstName,
lastname: lastName,
email: email,
token: token},
function(result) {
console.log(result);
if(result.success) {
//put logic for recording user's data on database
}
而我的PHP在这里:
<?php
$firstname;$lastname;$email;$captcha;
$firstname = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastname = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$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;
} else{
$secretKey = "6LdFL6kUAAAAAEZ8e2yzKZ6J8r6G9locFg_6oFe4";
$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'));
}
}
?>
我在表单上添加了API脚本。 有任何想法吗? 干杯!
也许你可以在你的简报形式中尝试这个,不需要改变你的形式前端代码: https : //github.com/AlexStack/Google-Recaptcha-to-any-form
基本示例代码:
在Form_Field_ID之后显示Google Recaptcha v2或v3:
GoogleRecaptcha::show('SiteKey', 'Form_Field_ID');
在后端php验证它:
GoogleRecaptcha::verify('SecretKey');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.