/
bitrix-dev
/
Starter-kit
Обзор
Документация
Войти
/
bitrix-dev
/
Starter-kit
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
main
local/php_interface/classes/mwi/SmartCaptcha.php
155 строк
4 KB
Alexey Karizhenskiy
Первая сборка (из ранее используемого)
19 янв 2026, 21:00
19 янв 2026, 21:00
d843e36
Код
Авторство
О чём код?
<?php /* * Created by PhpStorm. * @author: AlexeyS <Karizhenskiy@bk.ru> * @date: 2025.03.12 */ namespace MWI; class SmartCaptcha { private static $instance; private static ?string $publicKey = null; private static ?string $secretKey = null; private static ?string $lastMessage = null; public static function getInstance(): SmartCaptcha { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } public function __construct() { self::$publicKey = \SiteOption::get('SMARTCAPTCHA_PUBLIC_KEY'); self::$secretKey = \SiteOption::get('SMARTCAPTCHA_SECRET_KEY'); } /** * Проверяет доступность капчи * @return bool */ public static function isEnabled(): bool { return !empty(self::getPublicKey()) && !empty(self::getSecretKey()); } /** * Возвращает публичный ключ * @return string|null */ public static function getPublicKey(): ?string { $instance = self::getInstance(); return $instance::$publicKey; } /** * Возвращает секретный ключ * @return string|null */ public static function getSecretKey(): ?string { $instance = self::getInstance(); return $instance::$secretKey; } /** * Возвращает последнее сообщение * @return string|null */ public static function getLastMessage(): ?string { return self::$lastMessage; } /** * Проверяет валидность токена капчи * @param string $token Токен капчи * @return bool */ public static function verify(string $token = ''): bool { if (!self::isEnabled()) { self::$lastMessage = 'Капча не включена'; return true; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://smartcaptcha.yandexcloud.net/validate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'secret' => self::getSecretKey(), 'token' => $token, 'ip' => $_SERVER['REMOTE_ADDR'] ])); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); self::$lastMessage = ''; if ($httpCode !== 200) { self::$lastMessage = 'Ошибка при проверке капчи'; return false; } if (empty($response)) { self::$lastMessage = 'Пустой ответ от сервиса капчи'; return false; } $result = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { self::$lastMessage = 'Ошибка при декодировании ответа от сервиса капчи'; return false; } if (!empty($response['message'])) { self::$lastMessage = $response['message']; return false; } if (isset($result['status']) && $result['status'] === 'ok') { return true; } self::$lastMessage = 'Не удалось убедиться в прохождении капчи'; return false; } /** * Добавляет скрипт капчи */ public static function addScript($isLoad = true) { if (!self::isEnabled()) { return; } $arJsConfig = [ 'smartcaptcha' => [ 'js' => '/local/js/smartcaptcha/smartcaptcha.js', 'css' => '/local/js/smartcaptcha/smartcaptcha.css', 'rel' => [], ], ]; foreach ($arJsConfig as $ext => $arExt) { \CJSCore::RegisterExt($ext, $arExt); } if ($isLoad) { \CJSCore::Init([ 'smartcaptcha', ]); } $key = self::getPublicKey(); $script = '<script>window.smartCaptchaKey = "' . $key . '";</script>'; \Bitrix\Main\Page\Asset::getInstance()->addString($script, true); } }