带有 ZF3 错误值的 ReCaptcha

ReCaptcha with ZF3 wrong value

我使用最新的 Zend Framework,现在我想在我的表单上使用 ReCaptcha。 ReCaptcha 元素与其他一些元素一起定义为:

$pubKey = 'replaced by the actual pubkey';
$privKey = 'replaced by the actual privkey';
$recaptcha = new \Zend\Captcha\ReCaptcha(['pubKey' => $pubKey, 'privKey' => $privKey]);

$this->add(array(
    'attributes' => array (
        'data-role' => 'none',
    ),
    'name' => 'captcha',
    'type' => 'captcha',
    'options' => array(
        'captcha' => $recaptcha,
    ),
));

此代码验证控制器中的表单:

public function contactAction () {
    $contactForm = new ContactForm();
    if($this->getRequest()->isPost()) {
        $contactForm->setData($this->getRequest()->getPost());

        if($contactForm->isValid()){
            // send actual mail
            return $this->redirect()->toRoute('page', ['lang' => $this->translator->getLocale(), 'page' => 'contact']);
        }
    }
    $viewModel = new ViewModel ([
        'contactForm' => $contactForm
    ]);
    $viewModel->setTemplate('application/index/contact');
    return $viewModel;
}

最后,这是观点:

<?= $this->form($contactForm); ?>

对我来说,这段代码非常简单,应该可以工作。但是,在发送联系表时,它显示错误 'Captcha value is wrong'。有什么想法吗?

您必须根据 Google 的规则命名元素。使用此代码,它的工作方式类似于 breeze

$pubKey = 'replaced by the actual pubkey';
$privKey = 'replaced by the actual privkey';
$recaptcha = new \Zend\Captcha\ReCaptcha(['pubKey' => $pubKey, 'privKey' => $privKey]);

$this->add(array(
    'name' => 'g-recaptcha-response',
    'type' => 'captcha',
    'options' => [
        'captcha' => $recaptcha,
    ]
));

无论如何,ZF 文档一如既往地非常简短并且缺少示例。