client = $client; } public function init() { parent::init(); $this->component = Instance::ensure($this->component, Component::class); } /** * @inheritdoc */ protected function validateValue($value) { if (empty($value)) { return [$this->requiredMessage, []]; } $repeats = 0; do { $isSuccess = true; try { $response = $this->performRequest($value); } catch (ConnectException | ServerException $e) { if (++$repeats >= self::REPEAT_LIMIT) { throw $e; } $isSuccess = false; sleep(self::REPEAT_TIMEOUT); } } while (!$isSuccess); /** @noinspection PhpUndefinedVariableInspection */ $data = json_decode($response->getBody(), true); if (!isset($data['success'])) { throw new Exception('Invalid recaptcha verify response.'); } if (!$data['success']) { return [$this->message, []]; } return null; } /** * @param string $value * @throws \GuzzleHttp\Exception\GuzzleException * @return ResponseInterface */ protected function performRequest(string $value): ResponseInterface { return $this->client->request('POST', self::SITE_VERIFY_URL, [ 'form_params' => [ 'secret' => $this->component->secret, 'response' => $value, 'remoteip' => Yii::$app->getRequest()->getUserIP(), ], ]); } }