mortogo321/laravel-cloudflare-turnstile
Composer 安装命令:
composer require mortogo321/laravel-cloudflare-turnstile
包简介
Laravel wrapper package for Cloudflare Turnstile with invisible mode, button disabling, and auto-refresh
README 文档
README
A Laravel wrapper package for Cloudflare Turnstile with invisible mode by default, automatic submit button disabling until verification is complete, and refresh button on failure.
Features
- Invisible Mode by Default: Uses
executeappearance mode for seamless user experience - Auto-disable Submit Button: Automatically disables submit buttons until Turnstile is ready
- Refresh on Failure: Shows a refresh button when verification fails or times out
- Easy Integration: Simple Blade component for quick integration
- Flexible Validation: Multiple validation methods (rule class, validation rule string, manual verification)
- Customizable: Override all settings per widget or globally
- Controller-Friendly: Easy to use in any Laravel controller
Installation
Install the package via Composer:
composer require mortogo321/laravel-cloudflare-turnstile
Publish the configuration file:
php artisan vendor:publish --tag=turnstile-config
Optionally, publish the views if you want to customize them:
php artisan vendor:publish --tag=turnstile-views
Configuration
Add your Cloudflare Turnstile keys to your .env file:
TURNSTILE_SITE_KEY=your-site-key TURNSTILE_SECRET_KEY=your-secret-key TURNSTILE_APPEARANCE=execute TURNSTILE_THEME=auto
Get your Turnstile keys from: https://dash.cloudflare.com/?to=/:account/turnstile
Configuration Options
The package provides several configuration options in config/turnstile.php:
site_key: Your Turnstile site keysecret_key: Your Turnstile secret keyappearance: Widget appearance mode (always,execute,interaction-only) - default:executetheme: Widget theme (light,dark,auto) - default:autosize: Widget size (normal,compact) - default:normallanguage: Widget language (default:auto)retry: Retry behavior (auto,never) - default:autoretry_interval: Time between retries in milliseconds - default:8000timeout: Verification timeout in seconds - default:30show_refresh_button: Show refresh button on failure - default:truedisable_submit_until_ready: Disable submit button until ready - default:true
Usage
Basic Usage in Blade Views
Add the Turnstile widget to your form:
<form method="POST" action="/submit"> @csrf <input type="email" name="email" required> <input type="password" name="password" required> <!-- Add Turnstile widget --> <x-turnstile /> <!-- Add data-turnstile-button to your submit button --> <button type="submit" data-turnstile-button>Submit</button> </form>
Controller Validation
Option 1: Using the Validation Rule Class (Recommended)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mortogo321\LaravelCloudflareTurnstile\Rules\TurnstileRule; class FormController extends Controller { public function submit(Request $request) { $validated = $request->validate([ 'email' => 'required|email', 'password' => 'required|min:8', 'cf-turnstile-response' => ['required', new TurnstileRule()], ]); // Process the form return response()->json(['success' => true]); } }
Option 2: Using the String Validation Rule
public function submit(Request $request) { $validated = $request->validate([ 'email' => 'required|email', 'password' => 'required|min:8', 'cf-turnstile-response' => 'required|turnstile', ]); // Process the form return response()->json(['success' => true]); }
Option 3: Manual Verification with Facade
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mortogo321\LaravelCloudflareTurnstile\Facades\Turnstile; class FormController extends Controller { public function submit(Request $request) { $token = $request->input('cf-turnstile-response'); $result = Turnstile::verify($token, $request->ip()); if (!$result['success']) { return back()->withErrors([ 'turnstile' => 'Verification failed. Please try again.' ]); } // Process the form return response()->json(['success' => true]); } }
Option 4: Manual Verification with Service
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Mortogo321\LaravelCloudflareTurnstile\Services\TurnstileService; class FormController extends Controller { public function submit(Request $request, TurnstileService $turnstile) { $token = $request->input('cf-turnstile-response'); $result = $turnstile->verify($token, $request->ip()); if (!$result['success']) { return back()->withErrors([ 'turnstile' => 'Verification failed. Please try again.' ]); } // Process the form return response()->json(['success' => true]); } }
Customizing the Widget
You can customize the widget behavior using component attributes:
<x-turnstile :appearance="'interaction-only'" :theme="'dark'" :size="'compact'" :show-refresh="true" :disable-submit="true" :button-selector="'.my-submit-btn'" :action="'login'" :c-data="json_encode(['user_id' => auth()->id()])" />
Custom Submit Button Selector
By default, the package looks for buttons with the data-turnstile-button attribute. You can customize this:
<!-- Using data attribute (default) --> <button type="submit" data-turnstile-button>Submit</button> <!-- Or specify a custom selector --> <x-turnstile :button-selector="'#my-custom-button'" /> <button type="submit" id="my-custom-button">Submit</button> <!-- Or use a class --> <x-turnstile :button-selector="'.submit-btn'" /> <button type="submit" class="submit-btn">Submit</button>
Displaying Validation Errors
Display validation errors in your Blade views:
@error('cf-turnstile-response') <div class="alert alert-danger">{{ $message }}</div> @enderror
How It Works
- Widget Loading: The Turnstile widget loads in invisible mode (
executeappearance) - Button Disabling: Submit buttons with
data-turnstile-buttonattribute are automatically disabled - Verification: Turnstile runs automatically when the form is ready
- Button Enabling: Once verification succeeds, submit buttons are re-enabled
- Refresh on Failure: If verification fails or times out, a refresh button appears
- Form Submission: The form submits with the
cf-turnstile-responsetoken - Server Validation: Your controller validates the token with Cloudflare
API Reference
TurnstileService Methods
// Verify a token $result = Turnstile::verify(string $token, ?string $remoteIp = null): array; // Get the site key $siteKey = Turnstile::getSiteKey(): string; // Check if Turnstile is enabled $enabled = Turnstile::isEnabled(): bool;
Verification Response
The verify() method returns an array with the following structure:
[
'success' => true|false,
'error-codes' => [], // Array of error codes if success is false
'challenge_ts' => '2024-01-01T00:00:00Z', // Timestamp of the challenge
'hostname' => 'example.com', // Hostname where the challenge was solved
]
Testing
For testing purposes, you can use Cloudflare's test keys:
- Site Key:
1x00000000000000000000AA(Always passes) - Site Key:
2x00000000000000000000AB(Always blocks) - Site Key:
3x00000000000000000000FF(Forces interactive challenge)
Troubleshooting
Submit button remains disabled
- Ensure your button has the
data-turnstile-buttonattribute or matches your custom selector - Check browser console for JavaScript errors
- Verify your site key is correct
Verification fails in controller
- Ensure the
cf-turnstile-responsefield is present in the request - Verify your secret key is correct in
.env - Check that the token hasn't expired (tokens are valid for a limited time)
Widget doesn't appear
- Check that your site key is set in
.env - Verify the Cloudflare Turnstile script is loading (check browser network tab)
- Check browser console for errors
Security
- Never expose your secret key in client-side code
- Always validate on the server side
- Tokens can only be used once and expire after a short time
- Consider rate limiting your forms for additional protection
License
MIT License
Credits
- Cloudflare Turnstile
- Built for Laravel
Support
For issues, questions, or contributions, please visit the GitHub repository.
mortogo321/laravel-cloudflare-turnstile 适用场景与选型建议
mortogo321/laravel-cloudflare-turnstile 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 10 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「security」 「captcha」 「laravel」 「cloudflare」 「turnstile」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mortogo321/laravel-cloudflare-turnstile 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mortogo321/laravel-cloudflare-turnstile 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mortogo321/laravel-cloudflare-turnstile 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Diese Contao 4 Erweiterung stellt Google reCAPTCHA V2 in Form eines neuen Formularfeldes im Formulargenerator bereit. This extension provides Google reCAPTCHA V2 in the form of a new form field in the form generator of Contao Open Source CMS.
Provide a way to secure accesses to all routes of an symfony application.
Two Captcha
It's a barebone security class written on PHP
Laravel 5 Securimage helper
Contao CMS integrity check for some files
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 23
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-10