wearesho-team/yii2-recaptcha-v3

reCAPTCHA v3 Yii2 集成

1.1.0 2019-03-10 03:21 UTC

This package is auto-updated.

Last update: 2024-09-05 01:24:22 UTC


README

Build Status codecov

此模块提供行为、验证器和引导,以连接 reCAPTCHA 到 Yii2 应用程序。

安装

composer require wearesho-team/yii2-recaptcha-v3:^1.1

使用方法

配置

要配置当前 reCAPTCHA 环境(将在 Behavior 中使用)您必须使用 ConfigInterface

环境配置

引导

<?php

use Wearesho\ReCaptcha;

// config.php

return [
    'bootstrap' => [
        'reCaptcha' => [
            'class' => ReCaptcha\V3\Yii2\Bootstrap::class,
            'config' => ReCaptcha\V3\EnvironmentConfig::class, // or another config interface implementation
            'yiiConfig' => ReCaptcha\V3\Yii2\EnvironmentConfig::class, // will be used for environment checking
        ],
        // another bootstraps      
    ],
];

有关环境配置的详细信息,请参阅 wearesho-team/recaptcha-v3 文档。

验证器

<?php

use yii\base;
use Wearesho\ReCaptcha;

class Model extends base\Model {
    /** @var string token for reCAPTCHA verification */
    public $token;
    
    public function rules(): array
    {
        return [
            [['token',], 'required',],
            [['token',], ReCaptcha\V3\Yii2\Validator::class,
                'min' => 0.5,
                'max' => 1,
                'actions' => ['login',],
                'hostNames' => ['wearesho.com',],
            ],
        ];
    }
}

请参阅 Validator 的源代码以获取属性详细信息。

行为

行为是在 web\Controller 中验证 reCAPTCHA 令牌的方法。

<?php

use yii\web;
use Wearesho\ReCaptcha;

class Controller extends web\Controller 
{
    public function behaviors(): array
    {
        return [
            'reCaptcha' => [
                'class' => ReCaptcha\V3\Yii2\Behavior::class,
                'actions' => [
                    'login' => ['post',],   
                ],
                'min' => 0.5,
                'max' => 1,
                'hostNames' => ['wearesho.com',],
                'environments' => ['prod',],
            ],      
        ];
    }
    
    // controller code
}

如果指定了 environments 属性,则在执行其他操作之前将执行环境检查。有关环境配置的详细信息,请参阅 配置 部分。

在此示例中,行为将在 login 动作之前检查 X-ReCaptcha-Token 标头(仅限于 POST 动作)。如果标头不存在或其值无效,将抛出 \yii\web\BadRequestHttpException。请参阅 Behavior 的源代码以获取代码细节和属性文档。

当检查 reCAPTCHA 响应时,将使用当前控制器 ID、操作 ID 和请求方法 action 属性:controlleractionmethod,不使用分隔符。例如:loginindexpost,其中 login 是控制器 ID,index 是操作 ID,post 是请求方法。

注意:与 Validator 相比,Behavior::actions 属性的工作方式不同。

贡献者

许可

MIT