tigusigalpa / yandex-smartcaptcha-php
PHP SDK для Yandex SmartCaptcha с полной поддержкой Laravel. Управление капчами, валидация пользователей, интеграция с Laravel.
Installs: 0
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/tigusigalpa/yandex-smartcaptcha-php
Requires
- php: ^8.0
- ext-json: *
- guzzlehttp/guzzle: ^7.0|^8.0
- psr/log: ^1.0|^2.0|^3.0
- tigusigalpa/yandex-cloud-client-php: ^1.0
Requires (Dev)
- mockery/mockery: ^1.5
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.0|^10.0|^11.0
- squizlabs/php_codesniffer: ^3.6
Suggests
- illuminate/support: Required for Laravel integration (^8.0|^9.0|^10.0|^11.0|^12.0)
- tigusigalpa/yandex-cloud-client-php: Required for IAM token management (^1.0)
README
PHP for Yandex SmartCaptcha with full Laravel support.
Table of Contents
- Features
- Requirements
- Installation
- Getting Started with Yandex SmartCaptcha
- Quick Start
- API Methods
- Frontend Integration
- Laravel Validation Rule
- Error Handling
- Logging
- Testing
- Contributing
- Changelog
- Support
Features
- ✅ Complete API Coverage: All SmartCaptcha API methods
- 🔐 Token Validation: Validate user captcha tokens
- 📦 Captcha Management: Create, update, delete, and list captchas
- 🔑 Secret Key Retrieval: Get server secret keys
- 🎨 Laravel Integration: Service provider, facade, and config
- 📝 Type Safety: Full PHP 8.0+ type hints and strict types
- 🪵 PSR-3 Logging: Optional logging support
- 🧪 Well Tested: Comprehensive test coverage
- 📖 Well Documented: Detailed documentation and examples
Requirements
- PHP 8.0 or higher
- Guzzle HTTP client 7.0+
- Laravel 8.0+ (optional, for Laravel integration)
Installation
Install via Composer:
composer require tigusigalpa/yandex-smartcaptcha-php
Getting Started with Yandex SmartCaptcha
Prerequisites
Before you begin, you need to set up Yandex Cloud and create a captcha:
1. Create Yandex Cloud Account
- Go to Yandex Cloud Console
- Sign in to Yandex Cloud or register if you haven't already
- On the Yandex Cloud Billing page, make sure you have a billing account linked and it has the
ACTIVEorTRIAL_ACTIVEstatus - If you don't have a billing account, create one
2. Create Captcha in Console
- In the management console, select your folder
- Select Yandex SmartCaptcha service
- Click Create captcha
- Enter a captcha name. Naming requirements:
- Length: 2 to 63 characters
- Can contain lowercase Latin letters, numbers, and hyphens
- First character must be a letter, last character cannot be a hyphen
- (Optional) Disable domain name verification if needed
- Specify the list of sites where the captcha will be placed (e.g.,
example.com) - Leave the appearance as standard
- Configure the default captcha:
- Select the pre-check type (checkbox or slider)
- Select the challenge type (image-text task)
- Choose complexity: Easy, Medium, or Hard
- (Optional) Enable or disable the use of HTTP request information for ML model training
- Click Create
3. Get Captcha Keys
After creating the captcha:
- In the management console, select your folder
- Select Yandex SmartCaptcha service
- Click on the captcha name
- On the Overview tab, copy:
- Client Key (for frontend widget)
- Server Key (for backend validation)
4. Get OAuth Token (for API management)
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:
- Automatic OAuth to IAM token exchange
- IAM token caching (valid for 12 hours)
- Automatic token refresh when expired
Now you have:
- ✅ Client Key (for frontend)
- ✅ Server Secret Key (for validation)
- ✅ OAuth Token (for API management - will be auto-exchanged to IAM)
- ✅ Folder ID (from console)
Quick Start
Basic Usage (Pure PHP)
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!"; }
Laravel Usage
1. Publish Configuration
php artisan vendor:publish --tag=smartcaptcha-config
2. Configure Environment
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).
3. Use Facade
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 }
API Methods
Token Validation
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 Captcha
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
Get captcha information:
$captcha = $client->getCaptcha('captcha-id'); echo "Name: {$captcha->name}"; echo "Complexity: {$captcha->complexity}"; echo "Created: {$captcha->createdAt}";
List Captchas
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
Update captcha settings:
$captcha = $client->updateCaptcha( captchaId: 'captcha-id', updates: [ 'name' => 'new-name', 'complexity' => 'HARD', 'allowedSites' => ['example.com', 'test.com'], ] );
Delete Captcha
Delete a captcha:
$operation = $client->deleteCaptcha('captcha-id'); echo "Operation ID: {$operation['id']}";
Get Secret Key
Retrieve server secret key:
$secretKey = $client->getSecretKey('captcha-id'); echo "Secret Key: {$secretKey->serverKey}";
Frontend Integration
Basic Widget
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>
Advanced Widget
<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>
Laravel Validation Rule
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', ]);
Error Handling
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 }
Logging
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);
Testing
Run tests:
composer test
With coverage:
composer test-coverage
Documentation
License
MIT License. See LICENSE for details.
Author
Igor Sazonov
- GitHub: @tigusigalpa
- Email: sovletig@gmail.com
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
- Clone the repository:
git clone https://github.com/tigusigalpa/yandex-smartcaptcha-php.git
cd yandex-smartcaptcha-php
- Install dependencies:
composer install
- Run tests:
composer test
Coding Standards
This project follows PSR-12 coding standards:
composer cs-check # Check coding standards composer cs-fix # Fix coding standards composer phpstan # Static analysis
Pull Request Process
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Changelog
[1.0.0] - 2024-11-29
Added:
- Initial release
- SmartCaptcha client with full API support
- Token validation
- Captcha management (create, read, update, delete, list)
- Secret key retrieval
- Laravel integration (service provider, facade, config)
- PSR-3 logging support
- Comprehensive documentation (EN/RU)
- DTO classes for type safety
- Exception handling
- PHP 8.0+ support with strict types