· 6 years ago · Oct 14, 2019, 12:52 PM
1<?php
2
3/**
4 * class Google Captcha
5 * author Tomas Doubek
6 * framework DntLibrary
7 * package dnt3
8 * date 2017
9 */
10class GoogleCaptcha {
11
12 const SERVICE_URL = "https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s";
13
14 public $privateToken;
15 public $publicToken;
16 public $postName;
17 public $checkedOptions = null;
18 protected $config = array(
19 'google-recaptcha' => array(
20 'postName' => 'g-recaptcha-response'
21 ),
22 );
23
24 /**
25 *
26 * @param type $config
27 * @return \Application\Service\GoogleCaptcha
28 * @throws \Exception
29 */
30 public function __construct($siteKey, $secretKey) {
31 if (!isset($this->config['google-recaptcha'])) {
32 throw new \Exception("No google captcha set-up");
33 }
34
35 $this->publicToken = $siteKey;
36 $this->privateToken = $secretKey;
37 $this->postName = $this->config['google-recaptcha']['postName'];
38 return $this;
39 }
40
41 /**
42 *
43 * @param type $checkedOptions
44 * @return \Application\Service\GoogleCaptcha
45 */
46 public function setCheckedOptions($checkedOptions) {
47 $this->checkedOptions = $checkedOptions;
48 return $this;
49 }
50
51 /**
52 *
53 * @return boolean
54 */
55 public function getResponse() {
56 $verifyResponse = file_get_contents(sprintf(self::SERVICE_URL, $this->privateToken, $this->checkedOptions));
57 $responseData = json_decode($verifyResponse);
58 if ($responseData->success) {
59 return true;
60 }
61 return false;
62 }
63
64 /**
65 * V pripade chybnej odpovede FALSE
66 * @return boolean
67 */
68 public function getResult() {
69 if (is_null($this->checkedOptions)) {
70 return false;
71 }
72
73 return $this->getResponse();
74 }
75
76 /**
77 * Nazov _POST parametra google re-captcha inputu
78 * @return string
79 */
80 public function getPostName() {
81 return $this->postName;
82 }
83
84}