PHP code example of rasuvaeff / yii3-recaptcha

1. Go to this page and download the library: Download rasuvaeff/yii3-recaptcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rasuvaeff / yii3-recaptcha example snippets


> // A) container-backed resolver (all rule handlers resolved via the container)
> RuleHandlerResolverInterface::class => RuleHandlerContainer::class,
>
> // B) keep the default resolver, pre-register the DI-built handlers as instances
> RuleHandlerResolverInterface::class => static fn (
>     RecaptchaV2RuleHandler $v2, RecaptchaV3RuleHandler $v3,
> ): SimpleRuleHandlerContainer => new SimpleRuleHandlerContainer([
>     RecaptchaV2RuleHandler::class => $v2,
>     RecaptchaV3RuleHandler::class => $v3,
> ]),
> 

final class LoginRequest
{
    #[RecaptchaV3Rule(action: 'login', threshold: 0.5)]
    public string $recaptchaToken = '';
}

$result = $client->verifyV3($token);        // VerificationResult
if ($result->isTransportError()) { /* siteverify down — decide policy */ }
$score = $result->score;                     // apply your own score bands

use Rasuvaeff\Yii3Recaptcha\RecaptchaV2;
use Rasuvaeff\Yii3Recaptcha\RecaptchaV2Theme;
use Rasuvaeff\Yii3Recaptcha\RecaptchaV2Size;

// siteKey comes from DI config (RecaptchaConfig.siteKeyV2)
echo RecaptchaV2::widget()
    ->withTheme(RecaptchaV2Theme::Dark)
    ->withSize(RecaptchaV2Size::Normal);

use Rasuvaeff\Yii3Recaptcha\RecaptchaV2Rule;

class LoginForm
{
    #[RecaptchaV2Rule]
    public string $gRecaptchaResponse = '';
}

> <?= RecaptchaV2::widget()->withResponseFieldName('gRecaptchaResponse') 

> #[RecaptchaV2Rule]
> public string $gRecaptchaResponse = '';
> 

use Rasuvaeff\Yii3Recaptcha\RecaptchaV3;

// siteKey comes from DI config (RecaptchaConfig.siteKeyV3)
echo RecaptchaV3::widget();

echo RecaptchaV3::widget()
    ->withAction('login')
    ->withFieldName('recaptchaToken')   // hidden input name bound to the model attribute
    ->withFormId('login-form')          // optional: enable invisible-submit binding
    ->withBadge(RecaptchaV3Badge::Hidden); // optional: hide badge + render 

use Rasuvaeff\Yii3Recaptcha\RecaptchaV3Rule;

class LoginForm
{
    #[RecaptchaV3Rule(threshold: 0.5, action: 'login')]
    public string $recaptchaToken = '';
}

use Rasuvaeff\Yii3Recaptcha\Field\RecaptchaV3Field;

echo RecaptchaV3Field::field($formModel, 'recaptchaToken')
    ->siteKey($siteKeyV3)
    ->action('login')
    ->formId('login-form');   // optional invisible-submit binding

use Rasuvaeff\Yii3Recaptcha\Field\RecaptchaV2Field;

echo RecaptchaV2Field::field($formModel, 'recaptchaToken')
    ->siteKey($siteKeyV2)
    ->theme(RecaptchaV2Theme::Dark);

echo RecaptchaV3::widget()->withNonce($cspNonce);
echo RecaptchaV3Field::field($form, 'recaptchaToken')->siteKey($key)->nonce($cspNonce);

// config/common/di.php
ClientIpResolverInterface::class => static fn (MyIpDetector $d): ClientIpResolverInterface
    => new class ($d) implements ClientIpResolverInterface {
        public function __construct(private MyIpDetector $d) {}
        public function resolve(): ?string { return $this->d->detect(); }
    },

// config/params.php
return [
    'rasuvaeff/yii3-recaptcha' => [
        'siteKeyV2' => $_ENV['RECAPTCHA_SITE_KEY_V2'],
        'secretV2' => $_ENV['RECAPTCHA_SECRET_V2'],
        'siteKeyV3' => $_ENV['RECAPTCHA_SITE_KEY_V3'],
        'secretV3' => $_ENV['RECAPTCHA_SECRET_V3'],
        'sendRemoteIp' => true,
        'translation.category' => 'yii3-recaptcha',
    ],
];



declare(strict_types=1);

return [
    'The CAPTCHA verification failed.' => 'Your translated message.',
    'The CAPTCHA score is too low.' => 'Your translated message.',
    'The CAPTCHA action does not match.' => 'Your translated message.',
];

final readonly class RecaptchaConfig
{
    public function __construct(
        public string $siteKeyV2 = '',
        public string $secretV2 = '',
        public string $siteKeyV3 = '',
        public string $secretV3 = '',
        public string $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify',
        public bool $sendRemoteIp = false,
    ) {}
}

final readonly class RecaptchaClient
{
    public function verify(string $token, ?string $clientIp = null): VerificationResult;     // secretV2
    public function verifyV3(string $token, ?string $clientIp = null): VerificationResult;   // secretV3
    public function verifyWithSecret(string $token, string $secret, ?string $clientIp = null): VerificationResult;
}

final readonly class VerificationResult
{
    public bool $success;
    public array $errorCodes;   // string[]
    public ?float $score;       // v3 only
    public ?string $action;     // v3 only
    public ?string $hostname;
    public ?string $challengeTs;

    public const string TRANSPORT_ERROR = 'transport-error';
    public static function transportError(): self;  // failed result for an unreachable endpoint
    public function isTransportError(): bool;        // true on transport/HTTP/JSON failure (vs a real verdict)
}