Posted in

Ejemplo de uso de Recaptcha v2 de Google

Creamos un Recaptcha en Google https://www.google.com/recaptcha/admin y obtendremos un Clave del sitio y la Clave secreta.

Añadiremos este elemento dentro de nuestro formulario que lleva el site key que nos ha dado Google:

<div class="g-recaptcha" data-sitekey="AQUIELCODIGO-CLAVE-DEL-SITIO"></div>

Y la llamada al javascript

<script src="https://www.google.com/recaptcha/api.js"></script>

Podemos forzar el idioma del plugin pasando el idioma como parámetro: ?hl=ca

<script src="https://www.google.com/recaptcha/api.js?hl=ca"></script>

Y en el script php que recibe los datos del formulario:

$recaptcha_site_secret 	= "CODIGO-CLAVE-SECRETA";

				$captcha_response = Input::get('g-recaptcha-response');
				$curl = curl_init();

				$captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";

				curl_setopt($curl, CURLOPT_URL, $captcha_verify_url);
				curl_setopt($curl, CURLOPT_POST, true);
				curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=" . $recaptcha_site_secret . "&response=" . $captcha_response);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

				$captcha_output = curl_exec ($curl);
				curl_close ($curl);
				$decoded_captcha = json_decode($captcha_output);
				$captcha_status = $decoded_captcha->success;
			
				if($captcha_status === FALSE){
					return Response::json(array(
						'error' => 'yes',
						'message' => trans('texts.captcha-error')
					), 200);
				}else{
					$subject = 'Formulari contacte de la web';
					$mail_de = 'info@cap-i-cua.com';
					$mailTo = 'info@cap-i-cua.com';

					Mail::send('emails.contact', array(
						'data' => Input::all()
					), function ($message) use ($mailTo, $subject, $mail_de) {
						$message->from($mail_de, 'Cap-i-cua');
						$message->to($mailTo, $mail_de)->subject($subject);
					});
					return Response::json(array(
						'error' => 'no',
						'message' => trans('texts.message-sent')
					), 200);
				}

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *


The reCAPTCHA verification period has expired. Please reload the page.