-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReCaptchaComponent.php
105 lines (95 loc) · 2.59 KB
/
ReCaptchaComponent.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace recaptcha;
use yii\base\Component;
use Yii;
use yii\base\InvalidConfigException;
use yii\di\Instance;
use yii\httpclient\Client;
/**
* @author Sergey Bogatyrev <[email protected]>
* @since 2.0
*/
class ReCaptchaComponent extends Component
{
/**
* Base api js url.
*/
const API_URL = 'https://www.google.com/recaptcha/api.js';
/**
* Url to verify response.
*/
const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Asset manager js api key.
*/
const API_FILE_KEY = 'recaptcha-js-api';
/**
* @var string $siteKey
*/
public $siteKey;
/**
* @var string $secretKey
*/
public $secretKey;
/**
* @var bool whether or not send user IP address.
*/
public $remoteIp;
/**
* @var Client|array|string internal HTTP client.
*/
private $_httpClient = 'yii\httpclient\Client';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (empty($this->siteKey)) {
throw new InvalidConfigException('Property \'siteKey\' must be set.');
}
if (empty($this->secretKey)) {
throw new InvalidConfigException('Property \'secretKey\' must be set.');
}
}
/**
* Sets HTTP client to be used.
* @param array|Client $httpClient internal HTTP client.
*/
public function setHttpClient($httpClient)
{
$this->_httpClient = $httpClient;
}
/**
* Returns HTTP client.
* @return Client internal HTTP client.
*/
public function getHttpClient()
{
if (!is_object($this->_httpClient)) {
$this->_httpClient = Instance::ensure($this->_httpClient, Client::className());
}
return $this->_httpClient;
}
/**
* Calls the reCAPTCHA siteverify API to verify whether the user passes
* CAPTCHA test.
*
* @param string $response The value of 'g-recaptcha-response' in the submitted form.
* @param string $remoteIp The end user's IP address.
* @return bool Response from the service.
*/
public function verify($response, $remoteIp = null)
{
$params = ['secret' => $this->secretKey, 'response' => $response];
if (!is_null($remoteIp)) {
$params['remoteip'] = $this->remoteIp;
}
$client = $this->getHttpClient();
$response = $client->post(
self::VERIFY_URL, $params, ['content-type' => 'application/x-www-form-urlencoded']
)->send();
$result = $response->getData();
return $result['success'];
}
}