0

我正在使用 Grav 创建网站。我使用 Zammad 作为票务系统,并希望在页面上包含反馈表。为此,我使用 Zammad 的 API“https://admin-docs.zammad.org/en/latest/channels/form.html”。这是可行的。可以通过表单创建新票。现在我想添加一个机器人保护。为此,我选择了 hCaptcha。https://docs.hcaptcha.com/(Google reCaptcha 可以通过现成的插件“Form”轻松使用,但我不想使用 Google reCaptcha)。我也已经开始为 hCaptcha 写一个插件,但是我找不到 Grav 的 API 的正确入口。

我当前的代码:

function onFormProcessed(Event $event){

    if(is_entered_data_valid()) {
        if(isset($_POST['h-captcha-response']) && !empty($_POST['h-captcha-response'])){
            $secret = "0x0000000000000000000000000000000000000000";
            $remote_address = $_SERVER['REMOTE_ADDR'];
            $verify_url = "https://hcaptcha.com/siteverify?secret=".$secret."&response=".$_POST['h-captcha-response']."&remoteip=".$remote_address;
                // This is hcaptcha url
                $response = file_get_contents($verify_url); # Get token from post data with key 'h-captcha-response' and Make a POST request with data payload to hCaptcha API endpoint
                $responseData = json_decode($response);
                $success_msg="";
                $err_msg="";
                if($responseData->success){
                    $success_msg = "You can process your login functionality";
                }else{
                    $err_msg =  "Something went wrong while hCaptcha Validation. Please try again after sometime.";
                }
            }else{
                $err_msg =  "Please fill all the required fields";
            }
        } else {
            // Server side validation failed
            $error_output = "Please fill all the required fields";
        }
        // Get the response and pass it into your ajax as a response.
        $return_msg = array(
            'error'     =>  $err_msg,
            'success'   =>  $success_msg
        );
        echo json_encode($return_msg);

    }

提交表单时必须执行此功能

4

1 回答 1

0

你走对了方向,onFormProcessed就是你需要使用的事件。您可以从 Grav 的 Form 插件中学习。但是,您需要为插件定义特定的表单操作,否则无论表单是否使用您的验证码,您的代码都会针对网站上的所有表单运行。

假设您的表单操作是hcaptcha

    public function onFormProcessed(Event $event): void
    {
        $form = $event['form'];
        $action = $event['action'];

        switch ($action) {
            case 'hcaptcha':
                // If captcha validation fails, stop the form processing.
                if ($validation_fails) {
                    $message = "Please solve the captcha!";

                    $this->grav->fireEvent('onFormValidationError', new Event([
                        'form' => $form,
                        'message' => $message
                    ]));

                    $event->stopPropagation();

                    return;
                 }
            
于 2021-09-01T16:14:11.967 回答