我遇到reCaptcha V3问题。问题是,在记录新闻稿本身的分析和逻辑时,我正努力与服务器进行通信。我试图让表单通过reCaptcha,从而确认用户不是bot,如果是,则可以将用户输入的字段记录在数据库(firebase)上。现在,我已经设置了逻辑,用于在数据库上记录用户输入并在前端连接reCaptcha,但似乎无法弄清楚如何使用Google的reCaptcha将前端连接到后端。 / p>
我已经尝试了不同的连接方式,因为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脚本。有任何想法吗?干杯!
答案 0 :(得分:0)
也许您可以在新闻稿表单中尝试此操作,而无需在表单前端代码中进行任何更改: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');