In the app folder, create a Rules folder. Save the following code as GoogleRecaptcha.php:
<?php
namespace App\Rules;
use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;
class GoogleRecaptcha implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$url='https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
'response' => @$_POST['g-recaptcha-response']
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch , CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$response = json_decode($json,true);
var_dump($response);
if ($response['success'] != false) {
return 'success';}
else{return false;}
#$response= $obj ->{"success"};
#var_dump($response[0]);
#$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
# [
# 'form_params' => [
# 'secret' => env('RECAPTCHA_SECRET_KEY', false),
# 'remoteip' => request()->getClientIp(),
# 'response' => $value
# ]
#]
#);
#$body = json_decode((string)$response->getBody());
#return $body->success;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Are you a robot?';
}
}
In app/Http/Controllers/Auth/RegisterController.php
use App\Rules\GoogleRecaptcha;
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'g-recaptcha-response' => ['required', new GoogleRecaptcha]
]);
}
Original code was with guzzle but it leads to the following issue:
Issue: “cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)”
https://stackoverflow.com/questions/42094842/curl-error-60-ssl-certificate-in-laravel-5-4
in resources/views/auth/register.blade.php
Add in the registration form:
@if(env('GOOGLE_RECAPTCHA_KEY'))
<div class="form-group row">
<div class="g-recaptcha offset-md-4 col-md-6"
data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}">
</div>
</div>
@endif
in the views/layouts/app.blade.php or in the register.blade.php files add the following line:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
In .env
GOOGLE_RECAPTCHA_KEY=site_key
GOOGLE_RECAPTCHA_SECRET=site_secret
to avoid issue with guzzle, let’s consider making the curl REST API call manually: https://weichie.com/blog/curl-api-calls-with-php/
$jsonurl =""
$curl_handle=curl_init();
The CURL manual call worked perfectly