我希望在我的Laravel项目中实现,而不需要使用包。我尝试过用经典的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>右边的浮动reCaptcha条显示正确,但是当然,由于我需要一个按钮来执行实际提交,所以我有一个带有submit类型的按钮,并且reCaptcha div的回调函数都没有触发。当我返回请求时,g-recaptcha-response将为空。
为什么它不被提交独立于回调?
发布于 2017-05-30 11:08:03
reCaptcha的回调函数不会被触发,这取决于您在何处定义了回调函数。
它不应该在$(document).ready()或window.onload范围内定义
若要向服务器提交captcha令牌,请在窗体中放置一个隐藏的输入字段。
<input type="hidden" name="reCaptchaToken" value="" id="reCaptchaToken">将submit按钮替换为常规按钮,这样表单就不会提交,如果不需要,请删除captcha <div>。
<button type="button" class="btn btn-default g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>{{trans('content.input_submit')}}</button>并且可以使用回调函数填充值并提交表单。
// Google reCaptcha callback
function onSubmit (res) {
document.getElementById("reCaptchaToken").value = res;
document.getElementById("subscribeForm").submit();
}并使用Input::get('reCaptchaToken')访问控制器中的captcha令牌。
发布于 2017-06-22 15:20:47
下面是如何通过扩展Validator来正确地完成这个任务,但是这个解决方案使用的是google/recaptcha包(这比使用CURL要优雅得多)。
composer require google/recaptcha "~1.1"在recaptcha_secret_key或其他自定义配置文件中为config/app.php和recaptcha_site_key创建一个新的配置值。
在AppServiceProvider boot()方法中:
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 (例如,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>如果您想要将data-size="invisible"等添加到div中,它是不可见的。
最后,将新的验证规则添加到控制器中:
'g-recaptcha-response' => 'recaptcha'https://stackoverflow.com/questions/44258290
复制相似问题