我已经在“与我们联系”表单中添加了Google Recaptcha,但价值也没有验证码就提交了。我在联系页面中使用了以下验证码代码:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXX"></div>
<script src='https://www.google.com/recaptcha/api.js'></script>
我使用了这两个代码。请告诉我如何验证验证码。
我已经在“与我们联系”表单中添加了Google Recaptcha,但价值也没有验证码就提交了。我在联系页面中使用了以下验证码代码:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXX"></div>
<script src='https://www.google.com/recaptcha/api.js'></script>
我使用了这两个代码。请告诉我如何验证验证码。
Answers:
您应该尝试以下代码:我已经在我的网站上使用了它。
<script>
window.onload = function() {
var recaptcha = document.forms["contactForm"]["g-recaptcha-response"];
recaptcha.required = true;
recaptcha.oninvalid = function(e) {
alert("Please complete the captcha");
}
}
</script>
此脚本用于验证Google reCaptcha,就像magento的默认验证一样。请使用它。
<form name="freeeventForm" id="freeeventForm">
<div id="RecaptchaField"></div>
<input type="hidden" class="validate-reCAPTCHA">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
<script type="text/javascript">
//< ![CDATA[
var CaptchaCallback = function() {
grecaptcha.render('RecaptchaField', {'sitekey' : '6LeuiDwUAAAAALByt-xxxxxxxxxxx-xUsZHFkeEP'});
};
var customForm = new VarienForm('freeeventForm');
Validation.add('validate-reCAPTCHA','reCAPTCHA is mandatory',function(){
var response = grecaptcha.getResponse();
if (response.length === 0) {
return false;
}
return true;
});
//]]>
</script>
我在联系表格中使用了Recaptcha。
<form action="<?php echo Mage::getUrl('mcrecaptcha/index/save'); ?>" id="contactForm" method="post" onSubmit="return checkcaptcha() ;">
<ul class="form-list">
<li class="fields">
<div class="field">
<div class="input-box">
<input placeholder="Name" name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" />
</div>
</div>
<div class="field">
<div class="input-box">
<input placeholder="Email" name="email" id="email" title="<?php echo Mage::helper('contacts')->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email contact_us_margin_top" type="text" />
</div>
</div>
</li>
<li>
<div class="input-box">
<input placeholder="Telephone" name="telephone" id="telephone" title="<?php echo Mage::helper('contacts')->__('Telephone') ?>" value="" class="input-text contact_us_margin_top" type="text" />
</div>
</li>
<li class="wide">
<div class="input-box">
<textarea placeholder="Comment" name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text contact_us_margin_top" cols="5" rows="3" style="width:100%;"></textarea>
</div>
</li>
<li id="rcode">
<div class="captcha">
<div class="g-recaptcha contact_us_margin_top" data-sitekey="6Ldi8xsUAAAAAHsK15YxKsdhIn6lGk-RUIk222-f"> </div>
</div>
<div class="buttons-set contact_us_margin_top">
<input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
<button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button" onClick="_gaq.push(['_trackEvent', 'Submit', 'contacts click','Contact Us'])"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
</div>
<span class='captcha-error'><?php echo Mage::helper('contacts')->__('Please check the the captcha form.') ?></span>
</li>
</ul>
</form>
<script>
function checkcaptcha()
{
if((jQuery('#g-recaptcha-response').val())=='')
{
jQuery('.captcha-error').css('display','block');
return false;
}
else
{
jQuery('.captcha-error').css('display','none');
}
}
</script>
在我看来,上面公认的JavaScript解决方案绝对不是可行的方法。任何不使用JS(大多数都是JS)的bot都会绕过您的验证,您将获得所有您要阻止的垃圾邮件。始终始终在服务器上始终进行验证。JS验证只是UX的第一步。
无论如何,有多种解决方案,但这是经过大量研究之后在Magento 1.9中对我有用的解决方案。这最初是基于上述Mike的答案建立的,但是将file_get_contents换成了cURL,因为前一个函数通常会根据您的服务器配置为您提供http包装器错误。
通过创建文件夹/ app / code / local / YourVendorName / ValidateCaptcha /创建自己的模块
在新的ValidateCaptcha文件夹中,添加带有Customer.php文件的Model文件夹。这将用于覆盖Magento提供的核心Customer.php文件。
复制并粘贴此代码:
<?php
class YourVendorName_ValidateCaptcha_Model_Customer extends Mage_Customer_Model_Customer {
/**
* Validate customer attribute values.
*
* @return bool
*/
public function validate()
{
// This section is from the core file
$errors = array();
if (!Zend_Validate::is( trim($this->getFirstname()) , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The first name cannot be empty.');
}
if (!Zend_Validate::is( trim($this->getLastname()) , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The last name cannot be empty.');
}
if (!Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
$errors[] = Mage::helper('customer')->__('Invalid email address "%s".', $this->getEmail());
}
$password = $this->getPassword();
if (!$this->getId() && !Zend_Validate::is($password , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The password cannot be empty.');
}
if (strlen($password) && !Zend_Validate::is($password, 'StringLength', array(6))) {
$errors[] = Mage::helper('customer')->__('The minimum password length is %s', 6);
}
$confirmation = $this->getPasswordConfirmation();
if ($password != $confirmation) {
$errors[] = Mage::helper('customer')->__('Please make sure your passwords match.');
}
$entityType = Mage::getSingleton('eav/config')->getEntityType('customer');
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'dob');
if ($attribute->getIsRequired() && '' == trim($this->getDob())) {
$errors[] = Mage::helper('customer')->__('The Date of Birth is required.');
}
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'taxvat');
if ($attribute->getIsRequired() && '' == trim($this->getTaxvat())) {
$errors[] = Mage::helper('customer')->__('The TAX/VAT number is required.');
}
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'gender');
if ($attribute->getIsRequired() && '' == trim($this->getGender())) {
$errors[] = Mage::helper('customer')->__('Gender is required.');
}
// additional reCAPTCHA validation
// this should actually be in it's own function, but I've added
// it here for simplicity
// Magento uses this method for a few different requests, so make
// sure it's limited only to the 'createpost' action
$action = Mage::app()->getRequest()->getActionName();
if ( $action == 'createpost' ) { // restrict to the registration page only
$captcha = Mage::app()->getRequest()->getPost('g-recaptcha-response', 1);
if ( $captcha == '' ) {
// if the field is empty, add an error which will be
// displayed at the top of the page
$errors[] = Mage::helper('customer')->__('Please check the reCAPTCHA field to continue.');
} else {
$secret = 'your-secret-key-goes-here';
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha . '&remoteip=' . $_SERVER["REMOTE_ADDR"];
$ch = curl_init();
// if you're testing this locally, you'll likely need to
// add your own CURLOPT_CAINFO parameter or you'll get
// SSL errors
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
$result = json_decode( $response, true );
if ( trim( $result['success'] ) != true ) {
// Add reCAPTCHA error
// This will be shown at the top of the registration page
$errors[] = Mage::helper('customer')->__('reCAPTCHA unable to verify.');
}
}
}
// now return the errors with your reCAPTCHA validation as well
if (empty($errors)) {
return true;
}
return $errors;
}
}
现在将一个etc文件夹添加到您的模块中,并使用以下命令创建config.xml:
<?xml version="1.0"?>
<config>
<modules>
<YourVendorName_ValidateCaptcha>
<version>1.0</version>
</YourVendorName_ValidateCaptcha>
</modules>
<global>
<models>
<customer>
<rewrite>
<customer>YourVendorName_ValidateCaptcha_Model_Customer</customer>
</rewrite>
</customer>
</models>
</global>
</config>
接下来,您需要将JS添加到主题标题中。在app / design / frontend / default / YOURTHEME / template / page / html / head.phtml下,在末尾添加此权限。如果没有此文件,请从基本文件中复制它。但是,请勿覆盖基本文件。永远做自己的!
<?php
/* reCAPTCHA */
if ( strpos( Mage::helper('core/url')->getCurrentUrl(), 'account/create') != false ) { ?>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<?php } ?>
现在在app / design / frontend / default / YOURTHEME / template / persistent / customer / form / register.phtml中,在靠近底部的按钮设置div之前添加此代码:
<div class="g-recaptcha" data-sitekey="your-site-key-goes-here"></div>
<span id="captcha-required" style='display:none; color:#ff0000'><?php echo $this->__('Please Fill Recaptcha To Continue'); ?></span>
快完成了!现在,只需使用以下内容创建一个app / etc / modules / YourVendorName / ValidateCaptcha.xml来注册新模块:
<?xml version="1.0"?>
<config>
<modules>
<YourVendorName_ValidateCaptcha>
<active>true</active>
<codePool>local</codePool>
</YourVendorName_ValidateCaptcha>
</modules>
</config>
随便用您想要的内容替换YourVendorName。您的最终结构应类似于:
- app
- code
- local
- YourVendorName
- ValidateCaptcha
- etc
config.xml
- Model
Customer.php
- design
- frontend
- default
- YOURTHEME
- template
- customer
- form
register.phtml
- page
- html
head.phtml
- persistent
- customer
- form
register.phtml
- etc
- modules
YourVendorName_ValidateCaptcha.xml
要验证验证码,请创建一个保存控制器,用于保存您的表单值以及验证。
namespace Mike\SampleModule\Controller;
class Save extends \Magento\Framework\App\Action\Action
{
/**
* @var Google reCaptcha Options
*/
private static $_siteVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";
/**
* Save Form Data
*
* @return array
*/
public function execute()
{
$captcha = $this->getRequest()->getParam('g-recaptcha-response');
$secret = "<--your secret key-->"; //Replace with your secret key
$response = null;
$path = self::$_siteVerifyUrl;
$dataC = array (
'secret' => $secret,
'remoteip' => $_SERVER["REMOTE_ADDR"],
'v' => self::$_version,
'response' => $captcha
);
$req = "";
foreach ($dataC as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req = substr($req, 0, strlen($req)-1);
$response = file_get_contents($path . $req);
$answers = json_decode($response, true);
if(trim($answers ['success']) == true) {
// Captcha Validated
// Save Form Data
}else{
// Display Captcha Error
}
}
}
确保已替换上述示例代码中的站点密钥和秘密密钥。
NID,
您的reCaptcha脚本片段看起来可以运行,但请澄清是否已将其输入到Magento的源head.phtml中?(或form.phtml?)放置在Magento默认PHP之前的绿色正下方,因为它是a。
尤其是在输入php时的问题是,Magento在其大多数模板源页面的顶部放置的即刻php注释部分之后,是否会像下面的示例所示那样在其后立即的php注释部分之后输入它?
Magento免责声明代码在php标签中。将RECAPTCHA放在这里snippit脚本?
还有什么因素使得下面视频中的reCaptcha响应验证代码更适合Magento的方法结构:本教程在第一行中使用$ reCaptcha = $ _POST行?
最后一个问题替代方案:如果我使用php版本执行此reCaptcha响应验证,将会在php的诸如此类的顶部magento默认模板绿色注释部分之后输入php代码段
我不希望某些代码出现在前端,因为默认的contactForm已经发出了红色警报,如果用户没有输入所有信息,它将在每个字段下说,我只想让reCaptcha可以为该contactForm工作。但以某种方式,我也会理解以备将来使用。您是由开发人员还是程序员创建的?