О нас
Разработчикам
Заметки
Переводчик
Транслитератор
Сравнить текст
Генератор пароля
Ip и информация
Декодировать JSON
Локация
О нас
Разработчикам
Заметки
Переводчик
Транслитератор
Сравнить текст
Генератор пароля
Ip и информация
Декодировать JSON
Локация
Yandex Smart Captcha invisible
us.content
FRONTEND В форму, которую нужно проверять добавить класс smartcaptcha <form class="smartcaptcha"></form> Перед закрывающем тегом body <div id="captcha-container"></div> <script> const smartCaptchaPublicKey = '{{ config('app.smartcaptcha_public_key') }}' </script> <script src="https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadFunctionSmartCaptcha" defer></script> <script> // После загрузки страницы инициализируем smartCaptcha document.addEventListener('DOMContentLoaded', function () { if (window.smartCaptcha) { window.smartCaptcha.execute() } else { console.error('SmartCaptcha не загружена!') } }) // По классу smart_captcha_init инициализируем smartCaptcha if (document.querySelector('.smart_captcha_init')) { // Проверяем, существует ли smartCaptcha if (window.smartCaptcha) { window.smartCaptcha.execute(); } // Если smartCaptcha ещё не загружена, ждём её инициализации const interval = setInterval(function () { if (window.smartCaptcha) { window.smartCaptcha.execute() // Останавливаем проверку clearInterval(interval) } }, 500); // Проверяем каждые пол секунды } function initSmartCaptcha() { if (window.smartCaptcha) { window.smartCaptcha.execute() } else { setTimeout(function () { window.smartCaptcha.execute() }, 500) } } function onloadFunctionSmartCaptcha() { if (!window.smartCaptcha) { return } window.smartCaptcha.render('captcha-container', { sitekey: smartCaptchaPublicKey, invisible: true, hideShield: true, shieldPosition: 'bottom-left', callback: callbackSmartCaptcha, }) } function callbackSmartCaptcha(token) { const forms = document.querySelectorAll('.smart_captcha'), input = document.createElement('input') if (forms.length) { // Формируем input input.type = 'hidden' input.name = 'smart_captcha' input.value = token // Цикл по формам forms.forEach(function (el) { el.append(input) }) } } </script> BACKEND В конфиг app прописать значения smartcaptcha_public_key и smartcaptcha_secret_key Класс Laravel для проверки smartcaptcha, создать в App/Helpers <?php namespace App\Helpers; use Exception; use Illuminate\Support\Facades\Http; class YandexSmartCaptcha { /** * https://yandex.cloud/ru/docs/smartcaptcha/concepts/invisible-captcha * * @param string|null $token * @param string|null $ip * @return bool */ public static function check(string|null $token, string|null $ip): bool { $api = 'https://smartcaptcha.yandexcloud.net/validate'; $res = null; if ($token && $ip) { try { $params = [ 'secret' => config('app.smartcaptcha_secret_key'), 'token' => $token, 'ip' => $ip, ]; $response = Http::timeout(2) ->connectTimeout(2) ->get($api, $params); if ($response->ok()) { $data = $response->json(); $res = ($data['status'] ?? null) === 'ok'; } } catch (Exception $e) { } } return (bool) $res; } } Если нужно создать свой валидатор, то в AppServiceProvider в метод boot добавить: use App\Helpers\YandexSmartCaptcha; use Illuminate\Support\Facades\Validator; Validator::extend('smartcaptcha', function ($attribute, $value, $parameters, $validator) { return YandexSmartCaptcha::check($value, request()->ip()); }); Вызов валидатора, в request нужно добавить ip адрес пользователя: $rules = [ 'smartcaptcha' => ['required', 'smartcaptcha'], 'ip' => ['ip'], ];
Список