PHPackages                             tigusigalpa/yandex-smartcaptcha-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. tigusigalpa/yandex-smartcaptcha-php

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

tigusigalpa/yandex-smartcaptcha-php
===================================

PHP SDK для Yandex SmartCaptcha с полной поддержкой Laravel. Управление капчами, валидация пользователей, интеграция с Laravel.

v1.0.0(7mo ago)5524↓73.8%1MITPHPPHP ^8.0

Since Nov 29Pushed 7mo agoCompare

[ Source](https://github.com/tigusigalpa/yandex-smartcaptcha-php)[ Packagist](https://packagist.org/packages/tigusigalpa/yandex-smartcaptcha-php)[ Docs](https://github.com/tigusigalpa/yandex-smartcaptcha-php)[ RSS](/packages/tigusigalpa-yandex-smartcaptcha-php/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (1)Dependencies (8)Versions (2)Used By (1)

Yandex SmartCaptcha PHP
=======================

[](#yandex-smartcaptcha-php)

[![Yandex SmartCaptcha PHP](https://private-user-images.githubusercontent.com/2721390/520382512-ebcc5fd5-5000-455c-a155-212f368efc37.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3ODI5OTk5MDcsIm5iZiI6MTc4Mjk5OTYwNywicGF0aCI6Ii8yNzIxMzkwLzUyMDM4MjUxMi1lYmNjNWZkNS01MDAwLTQ1NWMtYTE1NS0yMTJmMzY4ZWZjMzcucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFN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Y29udGVudC10eXBlPWltYWdlJTJGcG5nIn0.p2CodcFOkmMpBb2Y-_IMxXUNOsFhrIIs2pPWhY-t0Lc)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/2f6f9af2e917cbf5786673e8e4ed8d0d9b29be6131327a992063e69136a93411/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e302532422d626c7565)](https://www.php.net/)

PHP for [Yandex SmartCaptcha](https://yandex.cloud/en/services/smartcaptcha) with full Laravel support.

[Русская версия](README-ru.md)

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Getting Started with Yandex SmartCaptcha](#getting-started-with-yandex-smartcaptcha)
    - [Prerequisites](#prerequisites)
    - [Create Yandex Cloud Account](#1-create-yandex-cloud-account)
    - [Create Captcha in Console](#2-create-captcha-in-console)
    - [Get Captcha Keys](#3-get-captcha-keys)
    - [Get IAM Token](#4-get-iam-token-for-api-management)
- [Quick Start](#quick-start)
- [API Methods](#api-methods)
- [Frontend Integration](#frontend-integration)
- [Laravel Validation Rule](#laravel-validation-rule)
- [Error Handling](#error-handling)
- [Logging](#logging)
- [Testing](#testing)
- [Contributing](#contributing)
- [Changelog](#changelog)
- [Support](#support)

Features
--------

[](#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
------------

[](#requirements)

- PHP 8.0 or higher
- Guzzle HTTP client 7.0+
- Laravel 8.0+ (optional, for Laravel integration)

Installation
------------

[](#installation)

Install via Composer:

```
composer require tigusigalpa/yandex-smartcaptcha-php
```

Getting Started with Yandex SmartCaptcha
----------------------------------------

[](#getting-started-with-yandex-smartcaptcha)

### Prerequisites

[](#prerequisites)

Before you begin, you need to set up Yandex Cloud and create a captcha:

#### 1. Create Yandex Cloud Account

[](#1-create-yandex-cloud-account)

1. Go to [Yandex Cloud Console](https://console.yandex.cloud)
2. Sign in to Yandex Cloud or register if you haven't already
3. On the [Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts) page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` status
4. If you don't have a billing account, [create one](https://yandex.cloud/en/docs/billing/quickstart/)

#### 2. Create Captcha in Console

[](#2-create-captcha-in-console)

1. In the [management console](https://console.yandex.cloud), select your folder
2. Select **Yandex SmartCaptcha** service
3. Click **Create captcha**
4. 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
5. (Optional) Disable domain name verification if needed
6. Specify the list of sites where the captcha will be placed (e.g., `example.com`)
7. Leave the appearance as standard
8. 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
9. (Optional) Enable or disable the use of HTTP request information for ML model training
10. Click **Create**

#### 3. Get Captcha Keys

[](#3-get-captcha-keys)

After creating the captcha:

1. In the [management console](https://console.yandex.cloud), select your folder
2. Select **Yandex SmartCaptcha** service
3. Click on the captcha name
4. On the **Overview** tab, copy:
    - **Client Key** (for frontend widget)
    - **Server Key** (for backend validation)

#### 4. Get OAuth Token (for API management)

[](#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
-----------

[](#quick-start)

### Basic Usage (Pure PHP)

[](#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

[](#laravel-usage)

#### 1. Publish Configuration

[](#1-publish-configuration)

```
php artisan vendor:publish --tag=smartcaptcha-config
```

#### 2. Configure Environment

[](#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

[](#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
-----------

[](#api-methods)

### Token Validation

[](#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-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)

Get captcha information:

```
$captcha = $client->getCaptcha('captcha-id');

echo "Name: {$captcha->name}";
echo "Complexity: {$captcha->complexity}";
echo "Created: {$captcha->createdAt}";
```

### List Captchas

[](#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)

Update captcha settings:

```
$captcha = $client->updateCaptcha(
    captchaId: 'captcha-id',
    updates: [
        'name' => 'new-name',
        'complexity' => 'HARD',
        'allowedSites' => ['example.com', 'test.com'],
    ]
);
```

### Delete Captcha

[](#delete-captcha)

Delete a captcha:

```
$operation = $client->deleteCaptcha('captcha-id');
echo "Operation ID: {$operation['id']}";
```

### Get Secret Key

[](#get-secret-key)

Retrieve server secret key:

```
$secretKey = $client->getSecretKey('captcha-id');
echo "Secret Key: {$secretKey->serverKey}";
```

Frontend Integration
--------------------

[](#frontend-integration)

### Basic Widget

[](#basic-widget)

Add to your HTML:

```

    Submit

    window.smartCaptcha = {
        sitekey: 'your-client-key',
        callback: function(token) {
            console.log('Captcha passed!');
        }
    };

```

### Advanced Widget

[](#advanced-widget)

```

    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);
                }
            });
        }
    }

```

Laravel Validation Rule
-----------------------

[](#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
--------------

[](#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
-------

[](#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
-------

[](#testing)

Run tests:

```
composer test
```

With coverage:

```
composer test-coverage
```

Documentation
-------------

[](#documentation)

- [Yandex SmartCaptcha Documentation](https://yandex.cloud/en/docs/smartcaptcha/)
- [API Reference](https://yandex.cloud/en/docs/smartcaptcha/api-ref/)
- [Quick Start Guide](https://yandex.cloud/en/docs/smartcaptcha/quickstart)

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Author
------

[](#author)

**Igor Sazonov**

- GitHub: [@tigusigalpa](https://github.com/tigusigalpa)
- Email:

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

### Development Setup

[](#development-setup)

1. Clone the repository:

```
git clone https://github.com/tigusigalpa/yandex-smartcaptcha-php.git
cd yandex-smartcaptcha-php
```

2. Install dependencies:

```
composer install
```

3. Run tests:

```
composer test
```

### Coding Standards

[](#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

[](#pull-request-process)

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

Changelog
---------

[](#changelog)

### \[1.0.0\] - 2024-11-29

[](#100---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

Support
-------

[](#support)

- [GitHub Issues](https://github.com/tigusigalpa/yandex-smartcaptcha-php/issues)
- [Yandex Cloud Support](https://yandex.cloud/en/support)

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance64

Regular maintenance activity

Popularity21

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

216d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2721390?v=4)[Igor Sazonov](/maintainers/tigusigalpa)[@tigusigalpa](https://github.com/tigusigalpa)

---

Top Contributors

[![tigusigalpa](https://avatars.githubusercontent.com/u/2721390?v=4)](https://github.com/tigusigalpa "tigusigalpa (2 commits)")

---

Tags

captchalaravelphpsmartcaptchayandex-cloudyandexcloudphplaravelvalidationsdksecuritycaptchayandexsmartcaptcha

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tigusigalpa-yandex-smartcaptcha-php/health.svg)

```
[![Health](https://phpackages.com/badges/tigusigalpa-yandex-smartcaptcha-php/health.svg)](https://phpackages.com/packages/tigusigalpa-yandex-smartcaptcha-php)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[aporat/store-receipt-validator

PHP receipt validator for Apple App Store and Amazon Appstore

6544.0M13](/packages/aporat-store-receipt-validator)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
