wearesho-team / yii2-recaptcha-v3
reCAPTCHA v3 Yii2 Integration
Requires
- php: ^7.1
- ext-mbstring: *
- horat1us/yii2-environment-config: ^1.0
- wearesho-team/recaptcha-v3: ^0.2.0
- yiisoft/yii2: ^2.0.15
Requires (Dev)
- ext-json: *
- phpunit/phpunit: ^7.5
- squizlabs/php_codesniffer: ^3.4
This package is auto-updated.
Last update: 2024-11-05 01:48:47 UTC
README
This module provides behavior, validator and bootstrap to connection reCAPTCHA to Yii2 Application.
Installation
composer require wearesho-team/yii2-recaptcha-v3:^1.1
Usage
Configuration
To configure current reCAPTCHA environment (will be used in Behavior) you have to use ConfigInterface.
Environment Configuration
Bootstrap
<?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 ], ];
See wearesho-team/recaptcha-v3 docs for environment config details.
Validator
<?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',], ], ]; } }
See Validator source code for properties details.
Behavior
Behavior is way to validate reCAPTCHA token in web\Controller
.
<?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 }
If environments
property specified, environment check will be performed before others.
See configuration section for environment configuring details.
In this example behavior will check for X-ReCaptcha-Token
header before login
action (only in case of POST action).
If header is missing or it's value invalid \yii\web\BadRequestHttpException
will be threw.
See Behavior source code for code details and property docs.
When checking reCAPTCHA response action
attribute will be used current controller ID, action ID and request method:
controlleractionmethod
, without dividers. Example: loginindexpost
, where login
is controller ID, index
is action ID and post
is request method).
Note: Behavior::actions
property works different way compared to Validator