【问题标题】:Add Google Recaptcha on a SilverStripe form在 SilverStripe 表单上添加 Google Recaptcha
【发布时间】:2017-01-08 18:36:22
【问题描述】:

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

我已生成 Google 公钥和私钥,但我不知道将它们放在哪里以在我的网站上显示验证码。

这是我当前的代码:

联系页面

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 添加到我的表单中?

【问题讨论】:

标签: captcha recaptcha silverstripe


【解决方案1】:

我们可以使用 SilverStripe Nocaptcha module 将 Google Nocaptcha 添加到我们的表单中。

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

composer require undefinedoffset/silverstripe-nocaptcha

安装模块后请务必致电dev/build?flush=all

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

mysite/_config/config.yml

# ...

FormSpamProtectionExtension:
  default_spam_protector: NocaptchaProtector

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

在设置 new Nocaptcha account 时通过 Google 检索密钥。

确保在添加这些设置后致电?flush=all

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

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。

【讨论】:

    【解决方案2】:

    添加

    new LiteralField('recaptcha_bubble', '<div id="recaptcha_bubble" class="field"></div>')
    

    在您的表单字段列表中 然后添加 google javascript 与

    Requirements::javascript("https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=en-GB");
    

    然后将函数添加到您的 javascript

    var recaptchaCallback = function () {
    var elementExists = document.getElementById('recaptcha_bubble');
    if (null != elementExists) {
        grecaptcha.render('recaptcha_bubble', {
            'sitekey' : 'the site key here'
        });
    }};
    

    何时提交带有变量“g-recaptcha-response”的表单

    function getPostUrlContents($url, $fields){
        $result = null;
    
        $ch = curl_init();
        $timeout = 30;
    
        $fields_string = '';
        foreach($fields as $key=>$value) {
            $fields_string .= $key.'='.$value.'&';
        }
    
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, rtrim($fields_string, '&'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $result = curl_exec($ch);
    
        curl_close($ch);
        return $result;
    }
    
    public function checkGoogle_recaptcha_Response($code) {
        $result = $this->getPostUrlContents(
            'https://www.google.com/recaptcha/api/siteverify',
            array(
                'secret' => urlencode('secret key here'),
                'response' => urlencode($code)
            )
        );
        if (!$result) return false;
        $gResult = json_decode($result, true);
        if ($gResult['success']) {
            return true;
        }
    
        return false;
    }
    
    public function yourForm(SS_HTTPRequest $request) {
    
        $vars = $request->postVars();
        if (!$this->checkGoogle_recaptcha_Response($vars['g-recaptcha-response'])) {
            // throw error
        } else {
            //not a robot, do something with request
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多