lundi 3 juillet 2017

Google recaptcha and Laravel 5

Following this tutorial I'm trying to implement google recaptcha with a contact form I have.

I submit the contact form with ajax.

In the form I have this:

<div id='recaptcha' class="g-recaptcha" data-sitekey=""></div>

In my controller I have this function:

 public function contact(Request $request)
    {
        $validator = Validator::make(Input::all(), [
            'first_name' => 'required',
            'surname' => 'required',
            'email' => 'required|email',
            'message' => 'required',
            'recaptcha-response'=>'required|recaptcha'
        ]);

        if( $validator->fails() )
        {
            return response()->json([
                'errors' => $validator->errors()->getMessages(),
                'success' => false,
                'code' => 422
            ]);
        }

The ReCaptcha validator:

namespace App\Validators;

use GuzzleHttp\Client;

class ReCaptcha
{
    public function validate($attribute, $value, $parameters, $validator){

        $client = new Client();

        $response = $client->post('http://ift.tt/1AMIfbj',
            ['form_params'=>
                [
                    'secret'=>env('GOOGLE_RECAPTCHA_SECRET'),
                    'response'=>$value
                 ]
            ]
        );

        $body = json_decode((string)$response->getBody());
        return $body->success;
    }

}

When I verify the code, I get the Green check from Google, but the response from userverify is: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.

So it always fails.

What am I doing wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire