kmergen / yii2-recaptcha3
Google ReCaptcha 3 的验证器和小部件
dev-master
2022-01-03 16:41 UTC
Requires
- yiisoft/yii2: ~2.0.15
- yiisoft/yii2-httpclient: *
This package is auto-updated.
Last update: 2024-08-29 05:50:31 UTC
README
Yii2 ReCaptcha3 提供了 Google ReCaptcha 3 的验证器和小部件。
它不需要 jQuery。
安装此扩展的首选方法是使用 composer。
运行以下命令之一:
composer require "kmergen/yii2-recaptcha3: "*"
或者
"kmergen/yii2-recaptcha3": "*",
将以下内容添加到您的 composer.json
文件的 require
部分。
2. 配置
在您的配置文件中设置以下内容
'components' => [ ... 'recaptcha3' => [ 'class' => 'kmergen\recaptcha3\RecaptchaConfig', 'siteKey' => 'google_recaptcha_v3_site key', 'secret' => 'google_recaptcha_v3_secret key', ], ... ]
2. 在模型中设置验证器
public $recaptcha; public function rules() { return [ ... [['recaptcha'], \kmergen\recaptcha3\RecaptchaValidator::class, 'threshold' => 0.5] ]; }
然后在表单视图中
<?= $form->field($model, 'recaptcha')->widget( \kmergen\recaptcha3\RecaptchaWidget::class, ['action' => 'homepage', // optional] ) ?>
或者
<?= \kmergen\recaptcha3\RecaptchaWidget::widget([ 'name' => 'FormName[recaptcha]', 'action' => 'homepage', // optional ]) ?>
注意:您可以响应错误响应码 'duplicate-or-timeout'。然后返回的错误消息是 'duplicate-or-timeout'。此错误出现在用户刷新已提交表单的页面时,因此您可以在控制器中执行以下操作
if ($model->load($post)) { if ($model->validate()) { if ($model->sendEmail()) { Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Thank you for contacting us. We will respond to you as soon as possible.')); } else { Yii::$app->getSession()->setFlash('danger', Yii::t('app', 'There was an error while sending your message.')); } } else { if ($model->hasErrors('recaptcha')) { $errors = $model->getErrors('recaptcha'); if (strcmp($errors[0] , 'timeout-or-duplicate') !== 0) { Yii::$app->getSession()->setFlash('danger', Yii::t('app', 'flashmessage.recaptcha3.failed')); } } } } return $this->render('contact', ['model' => $model]);