php - Laravel reCaptcha 集成

标签 php laravel recaptcha

我想在我的 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/

相关文章:

Laravel 5.3 - 如何在查询生成器中设置 fetchmode?

javascript - Google Recaptcha 在重置时抛出错误

javascript - 我在我的应用程序中使用一个网站的 img url。有些人收到 reCaptcha

angularjs - 动态更改Recaptcha V2语言

php - 在 GRAPH API 中检查页面的用户粉丝的方法是什么?

php - Google API 中的 token 格式无效

php - 在 Laravel 中创建友好的 url

php - 无法登录 localhost/phpmyadmin

laravel - 如何处理基于非用户的 Laravel API 的授权?

php - Laravel Route::current() 返回 null