Laravel reCaptcha integration

喜夏-厌秋 提交于 2019-12-05 22:12:36

The callback function of reCaptcha doesn't get triggered, that depends where you have defined your callback function.

It shouldn't be defined inside $(document).ready() or window.onload scope

To submit the captcha token to the server, place an hidden input field within your form

<input type="hidden" name="reCaptchaToken" value="" id="reCaptchaToken">

Replace the submit button with a regular button so that the form isn't submitted, remove the captcha <div> as it isn't needed.

<button type="button" class="btn btn-default g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>{{trans('content.input_submit')}}</button>

and you could populate the value using the callback function and submit the form

// Google reCaptcha callback
function onSubmit (res) {
    document.getElementById("reCaptchaToken").value = res;
    document.getElementById("subscribeForm").submit();
}

and access the captcha token in the controller using Input::get('reCaptchaToken')

Here is how to do it properly by extending the Validator, however this solution uses the google/recaptcha package (which is much more elegant than using CURL).

composer require google/recaptcha "~1.1"

Create a new config value for recaptcha_secret_key and recaptcha_site_key in config/app.php or another custom config file.

In AppServiceProvider boot() method:

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();
});

In resources/lang/validation.php add:

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

Also, add this to the attributes array inside the same file in order to make the error message nicer:

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

In the view file you want to display the reCAPTCHA e.g. 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>

Add data-size="invisible" etc. to the div if you want it invisible.

Finally, add the new validation rule to your controller:

'g-recaptcha-response' => 'recaptcha'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!