将谷歌验证码集成到现有的付款表单中


Integrating google reCaptcha into an existing payment form

最近我的网站通过我的付款表单收到了很多垃圾邮件,我决定需要添加一个captcha以防止这种情况。

正在寻找一些选择,我决定选择谷歌reCaptcha。设置和使用似乎很容易,但我遇到了一些问题。

首先,我将这个script包含在表单的标题中:

<script src='https://www.google.com/recaptcha/api.js'></script>

然后,我将实际captcha本身包含在表单的底部:

<div class="g-recaptcha" data-sitekey="6LdOVv4SAAAAAJ4muJvo_vD7vsd9T9QIfkEwcO7y"></div>

当我提交表格时,我会执行以下操作:

$captcha = $_POST["g-recaptcha-response"]; //Get Captcha token
$secret_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //Get Secret key
$google_response = http_get("https://www.google.com/recaptcha/api/siteverify", array("secret"=>$secret, "response"=>$captcha), $info); //perform Get request
print_r($info);

但是什么都没有发生,实际上,曾经工作的页面只是挂起,甚至没有显示错误消息。知道我可能做错了什么吗?根据我对文档的理解,响应将是JSON,成功将是真的或假的,如果为真,我想继续付款,如果为假,则停止并返回表格。

任何帮助都非常感谢。或者,如果有人有添加验证码的替代解决方案,我愿意研究一下。

试试这个来运行谷歌新的验证码 2015:

==PHP Verification==
if(isset($_POST['submit'])){
    $userIP = $_SERVER["REMOTE_ADDR"];
    $recaptchaResponse = $_POST['g-recaptcha-response'];
    $secretKey = "SECRET_KEY";
    $request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$recaptchaResponse}&remoteip={$userIP}");
    if(!strstr($request, "true")){
        echo "NOPE (Failed Verification)";
    }
    else{
        echo "YUP (Successful Verification)";
    }
}

不要使用 file_get_contents。Google 建议使用 POST-Requests 来调用他们的 api。像上面这样的 GET 请求可能会导致多个问题:

  • 由于安全原因,可能会阻止调用 URL(allow_url_fopen)
  • 用户可能会将类似 someToken&secret=otherSitesSecret 的内容作为输入传递给您的 $_POST[g-recaptcha-response]。如果您只是将被调用的网址字符串连接起来,则会将另一个秘密传递给Google。然后,用户可以使用他们从任何站点获得的任何 recaptcha 响应来验证自己。这是一个安全问题。
  • 谷歌返回的代币可能很长。网络服务器仅支持 url 中的几千个字符。这可能会导致字符串被切断,您将收到有效输入的错误。

因此,请使用如下所示的内容

// Get resource
$curl = curl_init();
// Configure options, incl. post-variables to send.
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        'secret' => 'your_secret_code_here',
        'response' => $_POST['g-recaptcha-response']
    )
));
// Send request. Due to CURLOPT_RETURNTRANSFER, this will return reply as string.
$resp = curl_exec($curl);
// Free resources.
curl_close($curl);
// Validate response
if(strpos($resp, '"success": true') !== FALSE) {
    echo "Verified.";
} else {
    echo "Not verified.";
}

此外,验证部分在接受"已验证"的内容方面更为保守。