-
npm install --save vue-recaptcha
-
form
<my-form inline-template>
<form action="{{ route('...') }}" @submit.prevent="FormSubmit($event)">
// other inputs
{{-- CAPTCHA --}}
<vue-recaptcha
ref="recaptcha"
@verify="onCaptchaVerified"
@expired="resetCaptcha"
size="invisible"
sitekey="{{ env('INVISIBLE_RECAPTCHA_SITEKEY') }}">
</vue-recaptcha>
{{-- Submit --}}
<button type="submit" class="button" :disabled="isSubmitting">Sign Up</button>
</form>
</my-form>
- vue "MyForm.vue"
<style>
.grecaptcha-badge {
visibility: hidden !important;
}
</style>
<script>
import VueRecaptcha from 'vue-recaptcha'
export default {
components: {VueRecaptcha},
data() {
return {
errors: [],
isSubmitting: false,
myForm: null,
}
},
methods: {
FormSubmit(event) {
this.myForm = event
this.isSubmitting = true
this.$refs.recaptcha.execute()
},
onCaptchaVerified(token) {
this.resetCaptcha()
let fData = new FormData(this.myForm.target)
fData.append('g-recaptcha-response', token)
axios({
method: this.myForm.target.method,
url: this.myForm.target.action,
data: fData
}).then(({data}) => {
this.errors = []
// all good
window.location.replace('/')
}).catch((err) => {
this.isSubmitting = false
this.errors = err.response.data.errors
})
},
resetCaptcha() {
this.$refs.recaptcha.reset()
}
},
render() {}
}
</script>
Backend "https://github.com/google/recaptcha"
-
composer require google/recaptcha
-
add to
.env
INVISIBLE_RECAPTCHA_SITEKEY=xxx
INVISIBLE_RECAPTCHA_SECRETKEY=xxx
- RecaptchaValidatorServiceProvider
<?php
namespace App\Providers;
use ReCaptcha\ReCaptcha;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class RecaptchaValidatorServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
Validator::extend('captcha', function ($attribute, $value, $parameters, $validator) {
$ip = request()->getClientIp();
$recaptcha = new ReCaptcha(env('INVISIBLE_RECAPTCHA_SECRETKEY'));
$resp = $recaptcha->verify($value, $ip);
return $resp->isSuccess();
});
}
}
- register the sp
<?php
'providers' => [
// ...
App\Providers\RecaptchaValidatorServiceProvider::class,
]
- validation
<?php
$validate = Validator::make(Input::all(), [
'g-recaptcha-response' => 'required|captcha'
]);
thx it was very helpful ;)