PHP SDK для Yandex SmartCaptcha с полной поддержкой Laravel. Управление капчами, валидация пользователей, интеграция с Laravel.
tigusigalpa/yandex-smartcaptcha-php is a Laravel package for php sdk для yandex smartcaptcha с полной поддержкой laravel. управление капчами, валидация пользователей, интеграция с laravel..
It currently has 13 GitHub stars and 556 downloads on Packagist (latest version v1.0.0).
Install it with composer require tigusigalpa/yandex-smartcaptcha-php.
Discover more Laravel packages by tigusigalpa
or browse all Laravel packages to compare alternatives.
Last updated
PHP for Yandex SmartCaptcha with full Laravel support.
Install via Composer:
composer require tigusigalpa/yandex-smartcaptcha-php
Before you begin, you need to set up Yandex Cloud and create a captcha:
ACTIVE or TRIAL_ACTIVE statusexample.com)After creating the captcha:
To manage captchas via API, you need an OAuth token. The package will automatically exchange it for an IAM token and refresh it when needed.
Get OAuth Token:
Visit the following URL and authorize the application:
https://oauth.yandex.ru/authorize?response_type=token&client_id=1a6990aa636648e9b2ef855fa7bec2fb
After authorization, you'll receive an OAuth token. Copy it and use it in your application.
Note: The package uses tigusigalpa/yandex-cloud-client-php which handles:
Now you have:
use Tigusigalpa\YandexSmartCaptcha\SmartCaptchaClient;
// Create client with OAuth token
// The package will automatically exchange it for IAM token and refresh when needed
$client = new SmartCaptchaClient($oauthToken);
// Validate user token
$result = $client->validate(
token: $_POST['smart-token'],
secret: 'your-server-secret-key',
ip: $_SERVER['REMOTE_ADDR']
);
if ($result->isValid()) {
echo "✅ Human verified!";
} else {
echo "❌ Bot detected!";
}
php artisan vendor:publish --tag=smartcaptcha-config
Add to your .env:
YANDEX_SMARTCAPTCHA_OAUTH_TOKEN=your-oauth-token
YANDEX_SMARTCAPTCHA_SECRET_KEY=your-secret-key
YANDEX_SMARTCAPTCHA_CLIENT_KEY=your-client-key
YANDEX_SMARTCAPTCHA_FOLDER_ID=your-folder-id
Note: The package uses yandex-cloud-client-php for authentication. Your OAuth token will be automatically exchanged for an IAM token and refreshed when needed (IAM tokens expire after 12 hours).
use Tigusigalpa\YandexSmartCaptcha\Laravel\Facades\SmartCaptcha;
// Validate token
$result = SmartCaptcha::validate(
request()->input('smart-token'),
config('smartcaptcha.secret_key'),
request()->ip()
);
if ($result->isValid()) {
// User is verified
}
Validate user captcha token:
$result = $client->validate(
token: 'user-token',
secret: 'server-secret-key',
ip: '192.168.1.1' // optional but recommended
);
// Check result
if ($result->isValid()) {
echo "Status: {$result->status}";
echo "Host: {$result->host}";
}
Create a new captcha:
$captcha = $client->createCaptcha(
folderId: 'b1g0ijbfaqsn12345678',
name: 'my-captcha',
options: [
'allowedSites' => ['example.com'],
'complexity' => 'MEDIUM', // EASY, MEDIUM, HARD
'preCheckType' => 'CHECKBOX', // CHECKBOX, SLIDER
'challengeType' => 'IMAGE_TEXT',
]
);
echo "Captcha ID: {$captcha->id}";
echo "Client Key: {$captcha->clientKey}";
Get captcha information:
$captcha = $client->getCaptcha('captcha-id');
echo "Name: {$captcha->name}";
echo "Complexity: {$captcha->complexity}";
echo "Created: {$captcha->createdAt}";
List all captchas in folder:
$result = $client->listCaptchas(
folderId: 'b1g0ijbfaqsn12345678',
pageSize: 50
);
foreach ($result['captchas'] as $captcha) {
echo "- {$captcha->name} ({$captcha->id})\n";
}
// Pagination
if ($result['nextPageToken']) {
$nextPage = $client->listCaptchas(
folderId: 'b1g0ijbfaqsn12345678',
pageSize: 50,
pageToken: $result['nextPageToken']
);
}
Update captcha settings:
$captcha = $client->updateCaptcha(
captchaId: 'captcha-id',
updates: [
'name' => 'new-name',
'complexity' => 'HARD',
'allowedSites' => ['example.com', 'test.com'],
]
);
Delete a captcha:
$operation = $client->deleteCaptcha('captcha-id');
echo "Operation ID: {$operation['id']}";
Retrieve server secret key:
$secretKey = $client->getSecretKey('captcha-id');
echo "Secret Key: {$secretKey->serverKey}";
Add to your HTML:
<form method="POST">
<div id="captcha-container"></div>
<button type="submit">Submit</button>
</form>
<script src="https://smartcaptcha.yandexcloud.net/captcha.js" defer></script>
<script>
window.smartCaptcha = {
sitekey: 'your-client-key',
callback: function(token) {
console.log('Captcha passed!');
}
};
</script>
<div id="captcha-container"></div>
<script src="https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadFunction" defer></script>
<script>
function onloadFunction() {
if (window.smartCaptcha) {
const container = document.getElementById('captcha-container');
const widgetId = window.smartCaptcha.render(container, {
sitekey: 'your-client-key',
hl: 'en',
callback: function(token) {
console.log('Token:', token);
}
});
}
}
</script>
Create custom validation rule:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Tigusigalpa\YandexSmartCaptcha\Laravel\Facades\SmartCaptcha;
class SmartCaptchaRule implements Rule
{
public function passes($attribute, $value): bool
{
$result = SmartCaptcha::validate(
$value,
config('smartcaptcha.secret_key'),
request()->ip()
);
return $result->isValid();
}
public function message(): string
{
return 'Please complete the captcha verification.';
}
}
Use in controller:
$request->validate([
'smart-token' => ['required', new SmartCaptchaRule()],
'email' => 'required|email',
]);
All exceptions extend SmartCaptchaException:
use Tigusigalpa\YandexSmartCaptcha\Exceptions\{
SmartCaptchaException,
AuthenticationException,
ValidationException,
NotFoundException,
RateLimitException
};
try {
$result = $client->validate($token, $secret);
} catch (AuthenticationException $e) {
// Invalid IAM token or secret key
} catch (ValidationException $e) {
// Invalid request parameters
} catch (NotFoundException $e) {
// Captcha not found
} catch (RateLimitException $e) {
// Too many requests
} catch (SmartCaptchaException $e) {
// Other errors
}
Enable logging in Laravel:
// config/smartcaptcha.php
'logging' => [
'enabled' => true,
'channel' => 'stack',
],
Or pass PSR-3 logger in pure PHP:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('smartcaptcha');
$logger->pushHandler(new StreamHandler('path/to/smartcaptcha.log'));
$client = new SmartCaptchaClient($iamToken, null, $logger);
Run tests:
composer test
With coverage:
composer test-coverage
MIT License. See LICENSE for details.
Igor Sazonov
Contributions are welcome! Please feel free to submit a Pull Request.
git clone https://github.com/tigusigalpa/yandex-smartcaptcha-php.git
cd yandex-smartcaptcha-php
composer install
composer test
This project follows PSR-12 coding standards:
composer cs-check # Check coding standards
composer cs-fix # Fix coding standards
composer phpstan # Static analysis
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)Added: