问题描述
我已经看到了一些关于它的例子和示例,并且已经以某种方式实现了它。 控制器中的方法如下:
使用的逻辑只是PHP,我想使用更多的lumen / laravel逻辑,而不仅仅是简单的PHP。我也尝试过但没有成功 anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request,[
'reference' => 'required|string','first_name' => 'required|string|max:50','last_name' => 'required|string|max:50','birthdate' => 'required|before:today','gender' => 'required|string','email' => 'required|email|unique:candidates','g-recaptcha-response' => 'required',]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success","message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger","message" => "Robot verification Failed,please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id,$response]);
}
解决方法
Okey。 Google为此提供了一个软件包:reCAPTCHA PHP client library
just:composer require google/recaptcha "^1.2"
以及在控制器内部的方法中
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'),$_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key')
意味着我从config / app.php中获取了密钥,并从.env文件中获取了该密钥。
如果没有config文件夹,则应创建它,并创建与laravel中相同的app.php文件。