使用reCAPTCHA在WordPress上通过AJAX提交表单时遇到问题

时间:2019-05-24 13:00:27

标签: ajax wordpress recaptcha custom-post-type

我花了好几个小时尝试以这种方式向Google寻求帮助,但我不断提出一个或另一个问题。我陷入困境,希望有人能帮我一个比喻,打在脸上,并向我展示如何正确地做到这一点。

好吧...所以我的前端有一个短代码插入的页面。该表单本质上是一种AMA(“问我什么”)表单,我正在使用该表单在“管理”区域中创建帖子。访客输入他们的问题,姓名和电子邮件,然后通过AJAX将表单提交给我。提交内容以ama自定义帖子类型保存到WordPress数据库中,并且通过wp_mail发送了一封电子邮件给我,因为我安装了一个SMTP插件,该插件可将wp_mail的所有请求路由到那里。我的网站上安装了CMB2,并在那里保存了reCAPTCHA的密钥。

到目前为止,很好。

我有一个包含CMB2字段的工作表,但是CMB2似乎不支持reCAPTCHA(否则它工作正常)。因此,我决定从头开始并编写自己的表格,因为这只是我要提交的三个字段。可能出什么事了吧?

这是我的弗兰肯代码。

<?php
function ccdClient_shortcode_amaForm( $atts ) {

    // Parse attributes
    $atts = ( shortcode_atts( array(
        'id'        => uniqid('ccdClient_amaForm_'),
    ), $atts, 'ama_form' ) );

    $rcKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_sitekey' );

    $form = '
    <form id="' . $atts['id'] . '" name="' . $atts['id'] . '" method="post" action="">
        <div class="amaError"></div>
        <div class="amaForm-field-question amaForm-field">
            <p><label for="question">Your Question</label></p>
            <p><textarea id="question" name="question" tabindex="1"></textarea></p>
        </div>
        <div class="amaForm-fieldGroup amaForm-groupTwo">
            <div class="amaForm-field-name amaForm-field">
                <p><label for="name">Your Name</label></p>
                <p><input type="text" id="name" name="name" tabindex="2" /></p>
            </div>
            <div class="amaForm-field-email amaForm-field">
                <p><label for="email">Your Email</label></p>
                <p><input type="email" id="email" name="email" tabindex="3" /></p>
            </div>
        </div>
        <div class="amaForm-fieldGroup amaForm-groupTwo">
            <div class="amaForm-field-recaptcha amaForm-field amaForm-recaptcha">
                <div class="g-recaptcha" data-sitekey="' . $rcKey . '"></div>
            </div>
            <div class="amaForm-field-submit amaForm-field amaForm-submit">
                <input type="submit" value="Publish" id="submit" name="submit" />
            </div>
        </div>
    </form>
    <script>
        $(document).ready(function() {

            // Get form
            var amaForm = $("#' . $atts['id'] . '");
            // Get messages div
            var amaError = $("#' . $atts['id'] . ' .amaError");
            // Set data
            var amaData = { "action" : "ama_form_process"}

            var options = { 
                url: "'. admin_url( 'admin-ajax.php' ) .'",
                type: "post",
                dataType: "json",
                data: amaData,
                success : function(responseText, statusText, xhr, $form) {
                    $(amaError).html("Your form has been submitted successfully");
                },
            };

            //Set submit function
            amaForm.on("submit", function(e) {
                //Prevent default form behavior
                e.preventDefault();
                // Serialise form data
                //Post via AJAX
                $.ajax(options)
                .done(function(response) {
                    // Make sure that the amaError div has the "success" class.
                    $(amaError).removeClass("error");
                    $(amaError).addClass("success");
                    // Set the message text.
                    $(amaError).text(response);
                })
                .fail(function(data) {
                    // Make sure that the amaError div has the "error" class.
                    $(amaError).removeClass("success");
                    $(amaError).addClass("error");

                    // Set the message text.
                    if (data.responseText !== "") {
                        $(amaError).text(data.responseText);
                    } else {
                        $(amaError).text("Oops! An error occured, and your message could not be sent.");
                    }
                });
            });
        });
    </script>';

    return $form;
}
add_shortcode('ama_form', 'ccdClient_shortcode_amaForm');

function ama_form_process() {
    // If the form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        // Include WordPress files
        include_once '../../../../../wp-includes/wp-load.php';

        // Set reCaptcha private key
        $recaptchaKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_secretkey' );

        // If the Google Recaptcha box was clicked
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
            $captcha = $_POST['g-recaptcha-response'];
            $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptchaKey . "&response=" . $captcha);
            $obj = json_decode($response);

            // If the Google Recaptcha check was successful
            if($obj->success == true) {
                $question = strip_tags( trim( $_POST['question'] ) );
                $name = strip_tags( trim( $_POST["name"] ) );
                $name = str_replace( array("\r","\n"), array(" "," "), $name);
                $email = filter_var( trim( $_POST["email"] ), FILTER_SANITIZE_EMAIL );
                if ( !$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    echo "Oops! There was a problem with your submission. Please complete the form and try again.";
                    exit;
                }

                // Add the content of the form to $post as an array
                $post = array(
                    'post_title'    => $question,
                    'post_status'   => 'pending',   // Could be: publish
                    'post_type'     => 'ama', // Could be: `page` or your CPT
                    'meta_input'    => array(
                        '_ccdclient_ama_name'   => $name,
                        '_ccdclient_ama_email'  => $email,
                    ),
                );
                wp_insert_post($post);
                echo 'Saved your post successfully! :)';

                $recipient = get_option('admin_email');
                $subject = "New question from $name";
                $email_content = "Name: $name\n";
                $email_content .= "Email: $email\n\n";
                $email_content .= "Message:\n$question\n";
                $email_headers = "From: $name <$email>";
                wp_mail( $recipient, $subject, $email_content, $email_headers );
            }
            // If the Google Recaptcha check was not successful
            else {
                echo "Robot verification failed. Please try again. Success:" . $response;
            }
        }
        // If the Google Recaptcha box was not clicked
        else {
            echo "Please click the reCAPTCHA box.";
        }
    }
    // If the form was not submitted
    // Not a POST request, set a 403 (forbidden) response code.
    else {
        echo "There was a problem with your submission, please try again.";
    }
}
add_action("wp_ajax_ama_form_process", "ama_form_process");

//use this version for if you want the callback to work for users who are not logged in
add_action("wp_ajax_nopriv_ama_form_process", "ama_form_process");

您可能已经猜到,我浏览了大约十二页,并结合了每一页的努力,因此覆盖了可能会奏效的部分并使自己困惑不已,因此,我在这里求助于保留什么内容离开了我的理智。

编辑:抱歉。在复制代码的同时,我并没有具体说明自己面临的问题。用来显示我沮丧的程度。

此代码存在很多问题。当前,当我提交表单时,它保留相同的URL,但返回404错误页面。但是,它以前告诉我说它无法识别功能,因此无法运行,例如cmb2_get_option(这是对get_option的修改,专门用于CMB2选项页)和{{1 }}。当密钥被硬编码到脚本中而不被wp_insert_post函数调用时,出现后一个错误(即:wp_insert_post)。

0 个答案:

没有答案