gpt4 book ai didi

php - Laravel reCaptcha 集成

转载 作者:可可西里 更新时间:2023-11-01 01:14:09 25 4
gpt4 key购买 nike

我想在我的 Laravel 项目中使用 Laravel 包实现 reCaptcha。我尝试过使用经典的 reCaptcha V2,但我想改为实现不可见的 reCaptcha。

所以我做的是这样的:

<form id="subscribeForm" class="form-inline" role="form" method="post" action="/subscribe" style="margin-bottom:70px;">
...
...
<button type="submit" class="btn btn-default">{{trans('content.input_submit')}}</button>

<div id="recaptcha" class="g-recaptcha" data-sitekey="---my---key---" data-size="invisible" data-callback="onSubmit"></div>

<script> ...callback functions... </script>
</form>

我在右侧显示了 float 的 reCaptcha 栏,但当然,因为我需要一个按钮来执行实际提交,所以我有一个类型为 submit 的按钮,并且 reCaptcha div 的回调函数都没有被触发。当我返回请求时,g-recaptcha-response 为空。

为什么不独立于回调提交?

最佳答案

这里是如何通过扩展 Validator 来正确地做到这一点,但是这个解决方案使用 google/recaptcha 包(这比使用 CURL 更优雅)。

composer require google/recaptcha "~1.1"

config/app.php 或其他自定义配置文件中为 recaptcha_secret_keyrecaptcha_site_key 创建一个新的配置值。

AppServiceProviderboot()方法中:

Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {
$recaptcha = new ReCaptcha(config('app.recaptcha_secret_key'));
$resp = $recaptcha->verify($value, request()->ip());

return $resp->isSuccess();
});

resources/lang/validation.php 添加:

'recaptcha' => 'The :attribute answer is invalid.',

此外,将此添加到同一文件内的 attributes 数组中,以使错误消息更好看:

'g-recaptcha-response' => 'reCAPTCHA',

在您想要显示 reCAPTCHA 的 View 文件中,例如contact.blade.php:

<div class="g-recaptcha" data-sitekey="{{ config('app.recaptcha_site_key') }}"></div>
<script src="https://www.google.com/recaptcha/api.js"></script>

如果你想让div不可见,添加data-size="invisible"等。

最后,将新的验证规则添加到您的 Controller :

'g-recaptcha-response' => 'recaptcha'

关于php - Laravel reCaptcha 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com