|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace rias\contactformextensions\models; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
|
6
|
|
|
|
|
7
|
|
|
class RecaptchaV3 |
|
8
|
|
|
{ |
|
9
|
|
|
const API_URI = 'https://www.google.com/recaptcha/api.js'; |
|
10
|
|
|
const VERIFY_URI = 'https://www.google.com/recaptcha/api/siteverify'; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var \GuzzleHttp\Client |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $client; |
|
16
|
|
|
|
|
17
|
|
|
private $siteKey; |
|
18
|
|
|
private $secretKey; |
|
19
|
|
|
private $threshold; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(string $siteKey, string $secretKey, float $threshold, int $timeout = 5) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->siteKey = $siteKey; |
|
24
|
|
|
$this->secretKey = $secretKey; |
|
25
|
|
|
$this->client = new Client([ |
|
26
|
|
|
'timeout' => $timeout |
|
27
|
|
|
]); |
|
28
|
|
|
$this->threshold = $threshold; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function render($action = 'homepage') |
|
32
|
|
|
{ |
|
33
|
|
|
$siteKey = $this->siteKey; |
|
34
|
|
|
$api_uri = static::API_URI; |
|
35
|
|
|
|
|
36
|
|
|
$html = <<<HTML |
|
37
|
|
|
<script src="${api_uri}?render=${siteKey}"></script> |
|
38
|
|
|
<script> |
|
39
|
|
|
grecaptcha.ready(function() { |
|
40
|
|
|
grecaptcha.execute('${siteKey}', {action: '${action}'}).then(function(token) { |
|
41
|
|
|
document.getElementById('g-recaptcha-response').value = token; |
|
42
|
|
|
}); |
|
43
|
|
|
}); |
|
44
|
|
|
</script> |
|
45
|
|
|
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" value=""> |
|
46
|
|
|
HTML; |
|
47
|
|
|
|
|
48
|
|
|
return $html; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function verifyResponse($response, $clientIp) |
|
52
|
|
|
{ |
|
53
|
|
|
if (empty($response)) { |
|
54
|
|
|
return false; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
$response = $this->sendVerifyRequest([ |
|
58
|
|
|
'secret' => $this->secretKey, |
|
59
|
|
|
'remoteip' => $clientIp, |
|
60
|
|
|
'response' => $response |
|
61
|
|
|
]); |
|
62
|
|
|
|
|
63
|
|
|
if (!isset($response['success']) || $response['success'] !== true) { |
|
64
|
|
|
return false; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
if (isset($response['score']) && $response['score'] >= $this->threshold) { |
|
68
|
|
|
return true; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return false; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
protected function sendVerifyRequest(array $query = []) |
|
75
|
|
|
{ |
|
76
|
|
|
$response = $this->client->post(static::VERIFY_URI, [ |
|
77
|
|
|
'form_params' => $query, |
|
78
|
|
|
]); |
|
79
|
|
|
|
|
80
|
|
|
return json_decode($response->getBody(), true); |
|
81
|
|
|
} |
|
82
|
|
|
} |