PHP code example of rasuvaeff / yii3-turnstile

1. Go to this page and download the library: Download rasuvaeff/yii3-turnstile 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-turnstile example snippets


use Rasuvaeff\Yii3Turnstile\Turnstile;
use Rasuvaeff\Yii3Turnstile\TurnstileTheme;
use Rasuvaeff\Yii3Turnstile\TurnstileSize;

// siteKey comes from DI config (TurnstileConfig)
echo Turnstile::widget()
    ->withTheme(TurnstileTheme::Light)
    ->withSize(TurnstileSize::Normal)
    ->withResponseFieldName('turnstileResponse'); // match your FormModel property name

use Rasuvaeff\Yii3Turnstile\TurnstileRule;
use Yiisoft\Validator\Validator;

class LoginForm
{
    #[TurnstileRule]
    public string $turnstileResponse = '';
}

> echo Turnstile::widget()->withResponseFieldName('turnstileResponse');
> 

> #[TurnstileRule]
> public string $turnstileResponse = '';

$result = (new Validator())->validate($loginForm);

// config/params.php
return [
    'rasuvaeff/yii3-turnstile' => [
        'siteKey' => $_ENV['TURNSTILE_SITE_KEY'],
        'secret' => $_ENV['TURNSTILE_SECRET'],
        'verifyUrl' => 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
        'sendRemoteIp' => true,
        'translation.category' => 'yii3-turnstile',
    ],
];



declare(strict_types=1);

return [
    'The CAPTCHA verification failed.' => 'Your translated message.',
];

final readonly class TurnstileConfig
{
    public function __construct(
        public string $siteKey,
        public string $secret,
        public string $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
        public bool $sendRemoteIp = false,
    ) {}
}

final readonly class TurnstileClient
{
    public function __construct(
        private TurnstileConfig $config,
        private ClientInterface $httpClient,
        private RequestFactoryInterface $requestFactory,
        private StreamFactoryInterface $streamFactory,
    ) {}

    public function verify(string $token, ?string $clientIp = null, ?string $idempotencyKey = null): VerificationResult;
    public function verifyWithSecret(string $token, string $secret, ?string $clientIp = null, ?string $idempotencyKey = null): VerificationResult;
}

final readonly class VerificationResult
{
    public function __construct(
        public bool $success,
        public array $errorCodes = [],
        public ?string $hostname = null,
        public ?string $action = null,
        public ?string $challengeTs = null,
    ) {}
}

#[TurnstileRule(
    message: 'Custom error message',
    sendRemoteIp: true,
)]
public string $captcha = '';