weixin_33705053 2018-09-01 19:33 采纳率: 0%
浏览 60

添加Google ReCaptcha

I have an existing contact form that performs validation on the server and client sides. Everything works with the form just fine but I am clueless as to how to add Google ReCaptcha v2. Reading the docs on Google's website I am still no where close to a solution.

Can someone give me an example on how they would go about this?

My goal here is for the form to spit out errors for all required fields including telling the user to fill out the captcha.

PHP:

<?php
require_once 'config.php';
require 'vendor/autoload.php';

$response = [
    'status' => 'success',
    'message' => 'Mail sent successfully',
    'data' => []
];



//Checking is it ajax request
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    //Invalid Ajax request
    http_response_code(403);
    $response = [
        'status' => 'error',
        'message' => 'Invalid request, please try again.',
        'data' => []
    ];
    responseHandler($response);
}

if( !isset($_POST['data']) ) {
    http_response_code(400);
    $response = [
        'status' => 'error',
        'message' => 'Empty post data.',
        'data' => []
    ];
    responseHandler($response);
}
$data = json_decode($_POST['data'], true); $errors = '';

//Email validation
if ( isset($data["userEmail"]) && !empty( $data["userEmail"] ) ) {
    $email = trim($data["userEmail"]);
    if ( filter_var($email, FILTER_VALIDATE_EMAIL) === false){
        $errors .= "$email is <strong>NOT</strong> a valid email address.<br/>";
    }
} else {
    $errors .= 'Please enter your email address.<br/>';
}
//Name Validation
if ( isset($data["userName"]) && !empty( $data["userName"] ) ) {
    $name = trim( $data["userName"] );
    if ( filter_var($name, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a valid name.<br/>';
    } elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) {
        $errors .= 'Only letters and white space allowed for name...<br/>';
    }
} else {
    $errors .= 'Please enter your name.<br/>';
}

//Subject Validation
if ( isset($data["subject"]) && !empty( $data["subject"] ) ) {
    $subject = trim( $data["subject"] );
    if ( filter_var($subject, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a subject to send.<br/>';
    }
} else {
    $errors .= 'Please enter a subject to send.<br/>';
}

//Message Validation
if ( isset($data["message"]) && !empty( $data["message"] ) ) {
    $message = trim( $data["message"] );
    if ( filter_var($message, FILTER_SANITIZE_STRING) === false){
        $errors .= 'Please enter a message to send.<br/>';
    }
} else {
    $errors .= 'Please enter a message to send.<br/>';
}



if(!empty( $errors )) {
    http_response_code(400);
    $response = [
        'status' => 'error',
        'message' => $errors,
        'data' => []
    ];
    responseHandler($response);
}

//Filtering out newlines in the email subject
$subject = str_replace(array("","
"),array(" "," "),$subject);
$contactContent = file_get_contents('email_templates/contact.html');;
$parameters = ['name' => $name, 'to_name' => TO_NAME, 'message' => $message ];

if(! send_mail( $email, $subject, $contactContent, $parameters ) ){ 
    //Email sent failed.
    http_response_code(500);
    $response = [
        'status' => 'error',
        'message' => 'Email service failing temporarily Or Maybe you are entered invalid E-mail, Please enter valid email and try again.',
        'data' => []
    ];
    responseHandler($response);
} else {
    //Email successfully sent
    http_response_code(200);
    responseHandler($response);
} 

/**
 * responseHandler function
 * @param array $response request response
 */
function responseHandler($response)
{
    header('Content-type: application/json');
    echo json_encode($response);
    exit;
}

/**
 * send_mail function
 * @param  string $email             [[Description]]
 * @param  string $Subject           [[Description]]
 * @param  string $message           [[Description]]
 * @param  array [$parameters = []] [[Description]]
 * @return boolean  [[Description]]
 */

function send_mail($email, $Subject, $message, $parameters = []){
    ////Parse the message with given parameters
    if( !empty( $parameters ) )$message = parse($message, $parameters);



    $mail = new PHPMailer;
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = SMTP_HOST;  // Specify main and backup SMTP servers
    $mail->SMTPAuth = SMTP_AUTH;                               // Enable SMTP authentication
    $mail->Username = SMTP_USERNAME;
    $mail->Password = SMTP_PASSWORD;
    $mail->SMTPSecure = SMTP_SECURE;                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = SMTP_PORT;                                    // TCP port to connect to

    if( isset($parameters['name']) )  
        $mail->setFrom($email, $parameters['name']);
    else 
        $mail->setFrom($email);


    $mail->addAddress(TO_EMAIL);     // Add a recipient
    //$mail->addReplyTo($email, 'Smart Invoice V3 Promotion');
    $mail->addBCC(TO_EMAIL);

    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $Subject;

    $mail->Body = $message;
    $mail->AltBody = strip_tags($message);

    if(!$mail->send()) {//$mail->ErrorInfo;
        return false;
    } 
    return true;
}


/**
 * parse function
 * @param  string $message    [[Description]]
 * @param  array $parameters [[Description]]
 * @return string [[Description]]
 */
function parse($message, $parameters) {
    foreach ($parameters as $key => $value) {
        $message = str_replace('{'.$key.'}', $value, $message);
    }
    return $message;
}

Javascript:

$(window).load(function() {
    $("#loader").fadeOut("slow");
    $('#main').fadeIn("slow");
});
$(document).ready(function(){
    jQuery.validator.setDefaults({
        errorPlacement : function(error, element) {
            element.removeClass('has-success').addClass('has-error');
        }
    });
    $('#emailForm').validate( {
        submitHandler : function(form) {
            return false;
        },
        rules : {
            userEmail:{
                required: true,
                email: true
            },
            userName:{
                required : true,
                minlength : 3,
                maxlength : 50
            },
            subject: {
                required : true,
                minlength : 10
            },
            message: {
                required : true,
                minlength : 50
            }
        },
        messages : {
            userEmail:{
                required : "Please enter your Email"
            },
            userName:{
                required : "Please enter your name"
            },
            subject: {
                required : "Please enter your contact purpose",
                minlength : "Minimum length of subject must be 10 chars long."
            },
            message: {
                required : "Please enter your sweet message",
                minlength : "Minimum length of your message must be 50 chars long."
            }
        },
        errorPlacement : function(error, element) {
            $(element).closest('div.form-group').find('.help-block').html(error.html());
        },
        highlight : function(element) {
            $(element).closest('div.form-group').removeClass('has-success').addClass('has-error');
        },
        unhighlight: function(element, errorClass, validClass) {
             $(element).closest('div.form-group').removeClass('has-error').addClass('has-success');
             $(element).closest('div.form-group').find('.help-block').html('');
        }
    });

    $(document).on('click', '#sendMailBtn', function(e){



        e.preventDefault();
        if( $('#emailForm').valid() ) {
            var sendMailBtn = $('#sendMailBtn');
            sendMailBtn.button('loading');
            $.ajax({
                url: 'ajax.php',
                method: 'post',
                dataType: 'json',
                data : { data: JSON.stringify($('#emailForm').serializeObject()) },
                success: function( response ){
                    sendMailBtn.button('reset');
                    $('input,textarea').val('');
                    showSuccessMessage();
                },
                error: function( response ) {
                    sendMailBtn.button('reset');
                    if( response.status === 400 || response.status === 403 || response.status === 500 ) {
                        showWarningMessage(response.responseJSON.message);
                    } else {
                        showWarningMessage();
                    }
                }
            });
        }

        return false;
    });

    function showSuccessMessage(){
        swal({
            title: "Many Thanks!!!",
            text: "Thanks for contacting us, We will get back to your inbox shortly...",
            type: "success",
            html: true
            /*imageUrl: "img/thumbs-up.jpg"*/
        });
    }

    function showWarningMessage(message){
        if(typeof message === 'undefined' || message === '' ) message = "Something went wrong, Please try again.";
        swal({
            title: "Oops...",
            text: message,
            type: "error",
            html: true
        });
    }

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
});
  • 写回答

1条回答 默认 最新

  • weixin_33744141 2018-09-01 20:01
    关注

    A successful solution to any Recaptcha will return a grecapcha object. Therefore:

    var rcResponse = grecaptcha.getResponse();
      if (rcResponse.length > 0) {
           //Recaptcha succeeded .... continue
      }
    

    Your form should have a wrapper for the Recaptcha itself:

    <div style="display:inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxx"></div>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了