Skip to content

Instantly share code, notes, and snippets.

@JSila
Created February 6, 2015 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JSila/41d40910bcd22edc934b to your computer and use it in GitHub Desktop.
Save JSila/41d40910bcd22edc934b to your computer and use it in GitHub Desktop.
Google ReCaptcha Laravel 5 Integration (validation rule)
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->app->validator->resolver(function($translator, $data, $rules, $messages)
{
return new GoogleReCaptchaValidator($translator, $data, $rules, $messages);
});
}
<?php namespace App\Services\Validators\GoogleReCaptcha;
class GoogleReCaptcha {
const GOOGLE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
private $secret;
/**
* @param string $secret
*/
function __construct($secret)
{
$this->secret = $secret;
}
/**
* Verifies reCAPTCHA's response by sending GET request to Google.
*
* @param string $gReCaptchaResponse
* @return array
*/
public function verify($gReCaptchaResponse)
{
$queryString = http_build_query([
'secret' => $this->secret,
'response' => $gReCaptchaResponse
]);
$url = sprintf('%s?%s', self::GOOGLE_VERIFY_URL, $queryString);
return json_decode(file_get_contents($url), true);
}
}
<?php namespace App\Services\Validators\GoogleReCaptcha;
use \Illuminate\Validation\Validator as IlluminateValidator;
class GoogleReCaptchaValidator extends IlluminateValidator {
/**
* @param \Symfony\Component\Translation\TranslatorInterface $translator
* @param array $data
* @param array $rules
* @param array $messages
* @param array $customAttributes
*/
public function __construct($translator, $data, $rules, $messages = [], $customAttributes = [])
{
parent::__construct($translator, $data, $rules, $messages, $customAttributes);
$this->setCustomMessages([
'reCaptchVerified' => 'Google reCaptcha response returned failure. Try again.'
]);
}
/**
* Implementation of our validation rule for Google reCaptcha.
*
* @param string $attribute
* @param string $value
* @param array $parameters
* @return boolean mixed
*/
public function validateReCaptchaVarified($attribute, $value, array $parameters)
{
$recaptcha = new GoogleReCaptcha(env('RECAPTCHA_KEY'));
$response = $recaptcha->verify($value);
return $response->success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment