Lumen Google reCAPTCHA 验证

Lumen Google reCAPTCHA validation

我已经看过一些关于它的图和示例,并且我已经以某种方式实现了它。 控制器中的方法如下所示:

使用的逻辑只是 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]);

}

好的。 Google 有一个包:reCAPTCHA PHP client library

只是: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 文件中获得了密钥。

如果您没有配置文件夹,您应该创建它,同时创建 app.php 与 laravel 中相同的文件。