2016-07-23 2 views
1

연락처 양식에 Google reCaptcha를 구현하려고합니다. 나는 SA에 관한 몇 가지 튜토리얼과 게시물을 읽었지만 성공하지는 못했다.Google reCaptcha 응답을 처리하는 문의 양식 문제

내 문제는 사용자가 reCaptcha를 확인했는지 여부와 관계없이 reCaptcha가 고려되지 않은 것처럼 양식이 보내지는 것입니다.

나는 this post에 기술 된 방법을 사용하고 내 전체 코드 아래 참조 :

문제가 무엇입니까?

많은 감사

FORM

<form action="sendmessage-test.php" class="well form-horizontal" id="contact_form" method="post" name="contact_form"> 

    fields etc. 

    <button class="" name="submit" type="submit"> SEND</button> 
    <div class="g-recaptcha" data-sitekey="mykey"></div> 

     <!-- Success message --> 
     <div class="alert alert-success" id="success_message" role="alert"> 
      Votre message a bien été envoyé. Merci! 
     </div> 
     <!-- error message --> 
     <div class="alert alert-danger" id="error_message" role="alert"> 
      Le message n'a pas pu être envoyé. Veuillez nous contacter par téléphone. Merci. 
     </div> 

</form> 

AJAX는

$(document).ready(function() { 

     $('#contact_form').bootstrapValidator({ 
      feedbackIcons: { 
       valid: 'fa fa-check', 
       invalid: 'fa fa-times', 
       validating: 'fa fa-refresh' 
      }, 
      fields: { 
       first_name: { 
        validators: { 
          stringLength: { 
          min: 2, 
         }, 
          notEmpty: { 
          message: 'Veuillez indiquer votre prénom' 
         } 
        } 
       }, 
       last_name: { 
        validators: { 
         stringLength: { 
          min: 2, 
         }, 
         notEmpty: { 
          message: 'Veuillez indiquer votre nom' 
         } 
        } 
       }, 
       email: { 
        validators: { 
         notEmpty: { 
          message: 'Veuillez indiquer votre adresse e-mail' 
         }, 
         regexp: { 
         regexp: '^[^@\\s][email protected]([^@\\s]+\\.)+[^@\\s]+$', 
         message: 'Veuillez indiquer une adresse e-mail valide' 
           } 
        } 
       }, 
       message: { 
        validators: { 
          stringLength: { 
          min: 10, 
          max: 1000, 
          message:'Votre message doit faire plus de 10 caractères et moins de 1000.' 
         }, 
         notEmpty: { 
          message: 'Veuillez indiquer votre message' 
         } 
         } 
        } 
       }}).on('success.form.bv', function (e) { 
       e.preventDefault(); 
       $('button[name="submit"]').hide(); 

       var bv = $(this).data('bootstrapValidator'); 
       // Use Ajax to submit form data 
       $.post($(this).attr('action'), $(this).serialize(), function (result) { 
        if (result.status == 1) { 
         $('#success_message').slideDown({ 
          opacity: "show" 
         }, "slow") 
         $('#contact_form').data('bootstrapValidator').resetForm(); 
        } else { 
         $('#error_message').slideDown({ 
          opacity: "show" 
         }, "slow")    } 
       }, 'json'); 
      } 
      ); 

    }); 

PHP

<?php 

require 'PHPMailer/PHPMailerAutoload.php'; 

$mail = new PHPMailer; 
$mail->CharSet = 'utf-8'; 

$email_vars = array(
    'message' => str_replace("\r\n", '<br />', $_POST['message']), 
    'first_name' => $_POST['first_name'], 
    'last_name' => $_POST['last_name'], 
    'phone' => $_POST['phone'], 
    'email' => $_POST['email'], 
    'organisation' => $_POST['organisation'], 
    'server' => $_SERVER['HTTP_REFERER'], 
    'agent' => $_SERVER ['HTTP_USER_AGENT'], 

); 

// CAPTCHA 


function isValid() 
{ 
    try { 

     $url = 'https://www.google.com/recaptcha/api/siteverify'; 
     $data = ['secret' => 'mykey', 
       'response' => $_POST['g-recaptcha-response'], 
       'remoteip' => $_SERVER['REMOTE_ADDR']]; 

     $options = [ 
      'http' => [ 
       'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
       'method' => 'POST', 
       'content' => http_build_query($data) 
      ] 
     ]; 

     $context = stream_context_create($options); 
     $result = file_get_contents($url, false, $context); 
     return json_decode($result)->success; 
    } 
    catch (Exception $e) { 
     return null; 
    } 
} 



//Enable SMTP debugging. 
$mail->SMTPDebug = false;        
//Set PHPMailer to use SMTP. 
$mail->isSMTP();    
//Set SMTP host name       
$mail->Host = "smtp.sendgrid.net"; 
//Set this to true if SMTP host requires authentication to send email 
$mail->SMTPAuth = true;       
//Provide username and password  
$mail->Username = "";     
$mail->Password = "";       
//If SMTP requires TLS encryption then set it 
$mail->SMTPSecure = "tls";       
//Set TCP port to connect to 
$mail->Port = 587;         

$mail->FromName = $_POST['first_name'] . " " . $_POST['last_name']; 

//To be anti-spam compliant 

/* $mail->From = $_POST['email']; */  
$mail->From = ('[email protected]'); 
$mail->addReplyTo($_POST['email']); 



$mail->addAddress("@gmail.com"); 
//CC and BCC 
$mail->addCC(""); 
$mail->addBCC(""); 

$mail->isHTML(true); 

$mail->Subject = "Nouveau message "; 

$body = file_get_contents('emailtemplate.phtml'); 

if(isset($email_vars)){ 
    foreach($email_vars as $k=>$v){ 
     $body = str_replace('{'.strtoupper($k).'}', $v, $body); 
    } 
} 
$mail->MsgHTML($body); 

/* $mail->Body = $_POST['message']."<br><br>Depuis la page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ; */ 


$response = array(); 
if(!$mail->send()) { 
    $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0); 
} else { 
    $response = array('message'=>"Message has been sent successfully", 'status'=> 1); 
} 

/* send content type header */ 
header('Content-Type: application/json'); 

/* send response as json */ 
echo json_encode($response); 


?> 
+1

당신은 결코 isValid 함수를 호출하지 않으므로 체크하지 않습니다. – jmattheis

답변

2

당신은 함수를 호출하기 만 아직 정의 isValid이 필요합니다.

$response = array(); 
if(isValid()) { 
    // send mail 
    if(!$mail->send()) { 
     $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0); 
    } else { 
     $response = array('message'=>"Message has been sent successfully", 'status'=> 1); 
    } 
} else { 
    // handle error 
    $response = array('message' => 'Captcha was not valid', 'status'=> 0); 
} 

정의 된 isValid를 호출해야합니다.

+0

감사합니다. "퇴장"을하는 것이 적절합니까? 다른 후에? PHP 파일의 어느 부분을 // 메일 보내기 대신 넣어야한다고 말할 수 있습니까? (내가 PHP 파일을 볼 때 모든 것이 변수처럼 보이기 때문에 어느 부분이 실제로 전자 메일을 보냈는지 확실하지 않습니다.) 많은 분들께서 – Greg

+0

에게 감사를드립니다 :''$ response = array(); if (! $ mail-> send()) { $ response = array ('message'=> "메일러 오류 :". $ mail-> ErrorInfo, 'status'=> 0); } else { $ response = array ('message'=> '메시지가 성공적으로 전송되었습니다.', 'status'=> 1); } ''당신은 끝낼 수 있지만 응답을 사용하고 있습니다. 내 대답을 편집하십시오. – jmattheis

+0

실제로 문제가있는 것으로 보입니다. reCaptcha가 양식에서 올바르게 확인 되었더라도 메시지가 전송되지 않습니다. AJAX 파일에서 #error_message가 표시됩니다. 문제가 뭔지 아십니까? 감사. – Greg