ReCaptcha\Validator теперь повторяет запрос к API Google, если запрос не удался

This commit is contained in:
ErickSkrauch
2017-05-18 17:06:01 +03:00
parent 27440481f5
commit d0a7c08b2c
2 changed files with 81 additions and 11 deletions

View File

@@ -3,13 +3,19 @@ namespace api\components\ReCaptcha;
use common\helpers\Error as E;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ServerException;
use Psr\Http\Message\ResponseInterface;
use Yii;
use yii\base\Exception;
use yii\di\Instance;
class Validator extends \yii\validators\Validator {
protected const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
private const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
private const REPEAT_LIMIT = 3;
private const REPEAT_TIMEOUT = 1;
public $skipOnEmpty = false;
@@ -42,20 +48,47 @@ class Validator extends \yii\validators\Validator {
return [$this->requiredMessage, []];
}
$response = $this->client->request('POST', self::SITE_VERIFY_URL, [
$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(),
],
]);
$data = json_decode($response->getBody(), true);
if (!isset($data['success'])) {
throw new Exception('Invalid recaptcha verify response.');
}
return $data['success'] ? null : [$this->message, []];
}
}