1 | <?php |
||
32 | class ReCaptcha |
||
33 | { |
||
34 | /** |
||
35 | * Version of this client library. |
||
36 | * @const string |
||
37 | */ |
||
38 | const VERSION = 'php_1.1.2'; |
||
39 | |||
40 | /** |
||
41 | * Shared secret for the site. |
||
42 | * @var string |
||
43 | */ |
||
44 | private $secret; |
||
45 | |||
46 | /** |
||
47 | * Method used to communicate with service. Defaults to POST request. |
||
48 | * @var RequestMethod |
||
49 | */ |
||
50 | private $requestMethod; |
||
51 | |||
52 | /** |
||
53 | * Create a configured instance to use the reCAPTCHA service. |
||
54 | * |
||
55 | * @param string $secret shared secret between site and reCAPTCHA server. |
||
56 | * @param RequestMethod $requestMethod method used to send the request. Defaults to POST. |
||
57 | */ |
||
58 | public function __construct($secret, RequestMethod $requestMethod = null) |
||
59 | { |
||
60 | if (empty($secret)) { |
||
61 | throw new \RuntimeException('No secret provided'); |
||
62 | } |
||
63 | |||
64 | if (!is_string($secret)) { |
||
65 | throw new \RuntimeException('The provided secret must be a string'); |
||
66 | } |
||
67 | |||
68 | $this->secret = $secret; |
||
69 | |||
70 | if (!is_null($requestMethod)) { |
||
71 | $this->requestMethod = $requestMethod; |
||
72 | } else { |
||
73 | $this->requestMethod = new RequestMethod\Post(); |
||
74 | } |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Calls the reCAPTCHA siteverify API to verify whether the user passes |
||
79 | * CAPTCHA test. |
||
80 | * |
||
81 | * @param string $response The value of 'g-recaptcha-response' in the submitted form. |
||
82 | * @param string $remoteIp The end user's IP address. |
||
83 | * @return Response Response from the service. |
||
84 | */ |
||
85 | public function verify($response, $remoteIp = null) |
||
86 | { |
||
87 | // Discard empty solution submissions |
||
88 | if (empty($response)) { |
||
89 | $recaptchaResponse = new Response(false, array('missing-input-response')); |
||
90 | return $recaptchaResponse; |
||
91 | } |
||
92 | |||
93 | $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION); |
||
94 | $rawResponse = $this->requestMethod->submit($params); |
||
95 | return Response::fromJson($rawResponse); |
||
96 | } |
||
97 | } |
||
98 |