$settings */ public function __construct(private array $settings) { } /** * @return array{valid: bool, code: string, fail_open: bool, message: string} */ public function validate(string $token): array { $token = trim($token); if ($token === '') { return [ 'valid' => false, 'code' => 'TOKEN_MISSING', 'fail_open' => false, 'message' => 'В форме нет токена проверки.', ]; } $siteKey = trim((string) ($this->settings['site_key'] ?? '')); $secretKey = trim((string) ($this->settings['secret_key'] ?? '')); $baseUrl = Settings::BASE_URL; if ($siteKey === '' || $secretKey === '') { return [ 'valid' => false, 'code' => 'NOT_CONFIGURED', 'fail_open' => false, 'message' => 'Плагин не настроен.', ]; } $payload = (string) wp_json_encode([ 'secret_key' => $secretKey, 'site_key' => $siteKey, 'token' => $token, ]); $response = wp_remote_post($baseUrl . '/api/v1/validate', [ 'timeout' => 5, 'redirection' => 0, 'sslverify' => true, 'headers' => [ 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], 'body' => $payload, ]); if (is_wp_error($response)) { return $this->unavailable($response->get_error_message()); } $status = (int) wp_remote_retrieve_response_code($response); $body = (string) wp_remote_retrieve_body($response); $data = json_decode($body, true); if ($status === 429 || $status === 0 || $status >= 500 || !is_array($data)) { return $this->unavailable('Сервис проверки недоступен (HTTP ' . $status . ').'); } if ($status === 401) { return [ 'valid' => false, 'code' => (string) ($data['code'] ?? 'INVALID_CREDENTIALS'), 'fail_open' => false, 'message' => (string) ($data['message'] ?? 'Секретный ключ не принят.'), ]; } if ($status !== 200) { return [ 'valid' => false, 'code' => (string) ($data['code'] ?? 'VALIDATION_FAILED'), 'fail_open' => false, 'message' => (string) ($data['message'] ?? 'Проверка не пройдена.'), ]; } $valid = !empty($data['valid']); return [ 'valid' => $valid, 'code' => (string) ($data['code'] ?? ($valid ? 'OK' : 'NOT_VALID')), 'fail_open' => false, 'message' => '', ]; } /** * @return array{valid: bool, code: string, fail_open: bool, message: string} */ private function unavailable(string $reason): array { $failOpen = !empty($this->settings['fail_open']); return [ 'valid' => $failOpen, 'code' => 'SERVICE_UNAVAILABLE', 'fail_open' => $failOpen, 'message' => $reason, ]; } }