andrewdanilov/yii2-grecaptchav3

Classes and assets for using google recaptcha v3

1.0.2 2021-08-29 11:13 UTC

This package is auto-updated.

Last update: 2024-04-29 03:38:57 UTC


README

Classes and assets for using google recaptcha v3

Installation

The preferred way to install this extension is through composer.

Either run

composer require andrewdanilov/yii2-grecaptchav3 "~1.0.0"

or add

"andrewdanilov/yii2-grecaptchav3": "~1.0.0"

to the require section of your composer.json file.

Usage

In site config

<?php
// ...
return [
	// ...
	'components' => [
		// ...
		'recaptcha' => [
			'class' => \andrewdanilov\grecaptchav3\Recaptcha::class,
			'sitekey' => 'place your sitekey here', // optional, if not set, you need to define it in widget config
			'secret' => 'place yout secret here',
		],
	],
];

In controller action

<?php
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
	$token = Yii::$app->request->post('g-recaptcha-token');
	$action = Yii::$app->request->post('g-recaptcha-action');
	if (Yii::$app->recaptcha->verify($token, $action)) {
		// ...
		// additionally you can check your action here
	} else {
		$model->addError('recaptcha', 'Recaptcha error');
	}
}

In view

<form action="/register" method="post" id="registerForm">
	<!-- form fields -->
</form>

<?= \andrewdanilov\grecaptchav3\RecaptchaInit::widget([
	'formID' => 'registerForm',
	'action' => 'my_register_action', // optional, default is <controller_id>_<action_id>_<widget_id>
	'sitekey' => 'place your sitekey here', // optional, if you defined sitekey in component config
]) ?>

Widget param action must contain only chars from set [A-Za-z_] and has to be unique per form on page.