· 7 years ago · Jun 12, 2018, 12:34 PM
1<?php
2
3namespace App\Service;
4
5/**
6 * This class is used to provide protection against bots
7 * more: https://developers.google.com/recaptcha/docs/display
8 */
9class Recaptcha
10{
11 private $publicKey;
12 private $secretKey;
13 private $apiUrl;
14
15 /**
16 * Recaptcha constructor.
17 * @param string $secretKey
18 * @param string $publicKey
19 * @param string $apiUrl
20 */
21 public function __construct(string $secretKey, string $publicKey, string $apiUrl)
22 {
23 $this->secretKey = $secretKey;
24 $this->publicKey = $publicKey;
25 $this->apiUrl = $apiUrl;
26 }
27
28 /**
29 * Validates re-captcha using Google's API
30 *
31 * @param string $recaptchaResponse is g-recaptcha-response from the recaptcha form
32 * @return boolean
33 */
34 public function validate(string $recaptchaResponse): bool
35 {
36 $googleResponseJson = file_get_contents($this->apiUrl . '?secret=' . $this->secretKey . '&response=' . $recaptchaResponse);
37 $googleResponse = json_decode($googleResponseJson);
38
39 return $googleResponse->success;
40 }
41
42 /**
43 * Returns repcaptcha div provided by Google
44 *
45 * @return string
46 */
47 public function createView(): string
48 {
49 $html = '<div class="g-recaptcha" data-theme="dark" data-sitekey="' . $this->publicKey . '"></div>';
50
51 return $html;
52 }
53}