如果您想使用第一个选项,您只需在表单中包含一个提交按钮,您将在 POST 字段的“g-recaptcha-response”键中收到 reCaptcha 令牌(例如:$_POST[' g-recaptcha-response'],如果您使用的是 php)。
<script src="https://www.google.com/recaptcha/api.js"></script>
<form method="post" action="login" id="loginForm">
<label for="password">Password:</label>
<input type="password" name="password" value="">
<!--Recaptcha button-->
<button class="g-recaptcha"
data-sitekey="#your_site_key"
data-callback='onSubmit'
data-action='submit'>Submit</button>
</form>
<script>
function onSubmit(token)
{
document.getElementById("loginForm").submit();
}
</script>
然后,像使用第二个选项一样验证将其提交到“https://www.google.com/recaptcha/api/siteverify”的令牌。
如果你在 php 上,从表单的 action 属性登录页面,应该是这样的:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query([
"secret"=>"#yourSecretKey"
, "response"=>$_POST['g-recaptcha-response']
, "remoteip"=>$_SERVER['REMOTE_ADDR']
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$recaptcha = json_decode(curl_exec($ch), true);
/** $recaptcha:
Array
(
[success] => 1 // or 0
[challenge_ts] => 2022-07-16T12:34:38Z
[hostname] => host // hostname
[score] => 0.9 // 0.0 to 1.0
[action] => submit // data-action attribute from reCaptcha button
)
*/
if ($recaptcha["score"] >= 0.5 && $recaptcha["action"] === 'submit')
{
// action on success
} else {
// action on false
}
?>
关于使用哪一个,我不知道如何回答……但我想这两个选项的工作方式相似,所以选择一个更容易实现的选项。