Created
April 4, 2017 18:40
-
-
Save tomfordweb/0ac71aa9b190759fbcced00e429e55e9 to your computer and use it in GitHub Desktop.
Laravel Recaptcha Trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http; | |
/** | |
* Need to create goog recaptcha data before usage | |
*/ | |
use Request; | |
trait RecaptchaTrait { | |
public function validateCaptchaString($secret, $response_string, $remote_ip) | |
{ | |
$options = [ | |
CURLOPT_POST => true, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_POSTFIELDS => [ | |
'secret' => $secret, | |
'response' => $response_string, | |
'remoteit' => $remote_ip | |
] | |
]; | |
$response = $this->_submitRequest($options); | |
$success_code = $response['success']; | |
if(! $success_code) | |
throw new \Exception('Failed recaptcha validation.'); | |
return true; | |
} | |
private function _submitRequest($options) | |
{ | |
$request = CURLRequest::simpleRequest('https://www.google.com/recaptcha/api/siteverify', $options); | |
$response = json_decode($request, true); | |
return $response; | |
} | |
} | |
class CURLRequest | |
{ | |
/** | |
* Submit a simple curl request | |
* @param string $url The URL to ping | |
* @param array $options Curl Options | |
* @return string The response from the CURL request | |
*/ | |
public static function simpleRequest($url, array $options) | |
{ | |
$ch = curl_init($url); | |
curl_setopt_array($ch, $options); | |
$content = curl_exec($ch); | |
curl_close($ch); | |
if(is_null($content) || ! $content) { | |
throw new \Exception('No response from ' . $url); | |
} | |
return $content; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment