在SilverStripe表单上添加Google Recaptcha [英] Add Google Recaptcha on a SilverStripe form

查看:65
本文介绍了在SilverStripe表单上添加Google Recaptcha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Google Recaptcha添加到我的自定义SilverStripe表单中。

I am trying to add Google Recaptcha to my custom SilverStripe form.

我生成了Google的公钥和私钥,但是我不知道将它们放置在网站上的验证码中的位置。

I have generated Google public and private keys but I do not know where to put them to show a captcha on my website.

这是我当前的代码:

联系页面

class ContactPage extends Page
{
    private static $db = array(
        'TelCustomerSupport'    => 'Varchar',
        'TelProjectSupport'     => 'Varchar',
        'OfficeName'            => 'Text',
        'OfficeStreetAddress'   => 'Text',
        'OfficeAddressLocality' => 'Text',
        'OfficePostalCode'      => 'Varchar',
        'OfficeMapLink'         => 'Text',
        'OfficeLatitude'        => 'Text',
        'OfficeLongitude'       => 'Text',
    );

    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        // Add extra fields
        $fields->addFieldToTab("Root.Main", new TextField('TelCustomerSupport', 'Phone - Customer, Trade & Retail Support'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('TelProjectSupport', 'Phone - Project Support'), "Content");

        $fields->addFieldToTab("Root.Main", new TextField('OfficeName'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficeStreetAddress'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficeAddressLocality'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficePostalCode'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficeMapLink'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficeLatitude'), "Content");
        $fields->addFieldToTab("Root.Main", new TextField('OfficeLongitude'), "Content");

        return $fields;
    }

}

class ContactPage_Controller extends NetSuitePage_Controller
{
    private static $allowed_actions = array('ContactForm');

    // Generate the form
    public function ContactForm()
    {
        // Create fields
        $fields = new FieldList(
            TextField::create("FirstName")->setTitle(_t('Contact.FIRSTNAME')),
            TextField::create("LastName")->setTitle(_t('Contact.LASTNAME')),
            EmailField::create("Email")->setTitle(_t('Contact.EMAILADDRESS')),
            TextField::create("Phone")->setTitle(_t('Contact.PHONENUMBER')),
            DropdownField::create('Iam', _t('Contact.IAMA'), $this->translateNetsuiteConfigArray('Contact', 'Iam')),
            TextField::create("SendSubject")->setTitle(_t('Contact.SUBJECT')),
            HoneyPotField::create("Subject2")->setTitle('Subject2'),
            TextareaField::create("Message")->setTitle(_t('Contact.MESSAGE'))->setColumns(30)->setRows(10)
        new RecaptchaField('MyCaptcha')
        );

        // Create actions
        $submitbutton = new FormAction('doContactForm', _t('Contact.SEND'));
        $submitbutton->addExtraClass('btn btn-black');
        $actions = new FieldList(
            $submitbutton
        );

        $validator = ZenValidator::create();
        $validator->addRequiredFields(array('FirstName', 'LastName', 'Email', 'Phone', 'Iam', 'SendSubject', 'Message'));
        $validator->setConstraint('FirstName', Constraint_length::create('max', 32));
        $validator->setConstraint('LastName', Constraint_length::create('max', 32));
        $validator->setConstraint('Phone', Constraint_length::create('min', 7));
        $validator->setConstraint('Email', Constraint_type::create('email'));
        $validator->setConstraint('Phone', Constraint_type::create('digits'));

        $form = new Form($this, 'ContactForm', $fields, $actions, $validator);
        $form->addExtraClass('contact-form');
        $form->setFormMethod('POST', true);

        return $form;
    }

    // Deal with form submission
    public function doContactForm($data, $form)
    {

        $submission = new ContactFormSubmission();
        $form->saveInto($submission);
        $submission->write();

        $data['path'] = print_r($this->refererTracker->retrieveAll(), true);

        $email = new Email();
        $email->setTemplate('ContactFormEmail');
        $email->populateTemplate($data);
        $email->setTo($this->getNetsuiteConfig('Contact', 'Emails'));
        $email->setFrom("no-reply@warmup.co.uk");
        $email->setSubject('[warmup.co.uk] New contact from the website');
        $email->populateTemplate($data);
        $email->send();

        $post = $this->getNetsuiteConfig('Contact');

        $post->firstname                    = $data['FirstName'];
        $post->lastname                     = $data['LastName'];
        $post->email                        = $data['Email'];
        $post->phone                        = $data['Phone'];
        $post->custentity116                = $data['Iam'];
        $post->custentitysubject_contact_us = $data['SendSubject'];
        $post->custentitymessage_contact_us = $data['Message'];


        // Check for success
        if ($this->queueNetSuitePost($post)) {
            return $this->redirect(Director::get_current_page()->Link()."?success=1");
        }

        // Redirect back with form data and error message
        Session::set('FormInfo.' . $form->FormName() . '.data', $data);
        Session::set('FormInfo.'.$form->FormName().'.errors', array());
        $form->sessionMessage("Netsuite error", 'bad');

        return $this->redirectBack();

    }

    // Returns true if form submitted successfully
    public function Success()
    {
        return isset($_REQUEST['success']) && $_REQUEST['success'] == "1";
    }

    public function getCurrentSubsite()
    {
        $subsite = Subsite::currentSubsite();

        if($subsite) {
            return $subsite->Title;
        }
        return $subsite;
    }

}






ContactFormSubmission

class ContactFormSubmission extends DataObject {
    private static $db = array(
        'FirstName' => 'Text',
        'LastName' => 'Text',
        'Email' => 'Text',
        'Phone' => 'Text',
        'Iam' => 'Text',
        'Subject' => 'Text',
        'Message' => 'Text'
    );
}

如何正确将Google Recaptcha添加到我的表单中?

How do I correctly add Google Recaptcha to my form?

推荐答案

我们可以使用 SilverStripe Nocaptcha模块

安装此模块的最简单方法是通过 composer 使用以下命令:

The easiest way to install this module is through composer with the following command:

composer require undefinedoffset/silverstripe-nocaptcha

安装模块后,请确保调用 dev / build?flush = all

After installing the module be sure to call dev/build?flush=all.

接下来,我们必须通过我们的站点config.yml文件将垃圾邮件保护程序设置为 NocaptchaProtector ,并设置 Nocaptcha 键。

Next we must set the spam protector to NocaptchaProtector through our site config.yml file, as well as set the Nocaptcha keys.

mysite / _config / config.yml

# ...

FormSpamProtectionExtension:
  default_spam_protector: NocaptchaProtector

NocaptchaField:
  site_key: "YOUR_SITE_KEY"
  secret_key: "YOUR_SECRET_KEY"

The设置 Nocaptcha 时,通过Google检索密钥帐户

The keys are retrieved through Google when setting up a new Nocaptcha account.

添加这些设置后,请确保调用?flush = all

Make sure to call ?flush=all after adding these settings.

我们现在准备在表单上启用垃圾邮件保护功能。为此,我们只需在表单函数中调用 $ form-> enableSpamProtection()

We are now ready to enable spam protection on our form. To do this we simply call $form->enableSpamProtection() in our form function:

public function ContactForm()
{
    // Create fields
    $fields = FieldList::create(
        // ...
    );

    // Create actions
    $actions = FieldList::create(
        // ...
    );

    $validator = ZenValidator::create();

    $form = Form::create($this, 'ContactForm', $fields, $actions, $validator);

    $form->enableSpamProtection();

    return $form;
}

现在应在我们的表单上启用Google Nocaptcha。

Google Nocaptcha should now be enabled on our form.

这篇关于在SilverStripe表单上添加Google Recaptcha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆