aslnbxrz/simple-otp
Composer 安装命令:
composer require aslnbxrz/simple-otp
包简介
A simple and flexible OTP (One-Time Password) management package for Laravel with multiple storage drivers and delivery methods
README 文档
README
A simple, flexible, and production-ready OTP (One-Time Password) management package for Laravel applications. This package provides multiple storage drivers (Cache, Database, Redis) and delivery methods (SMS, Email, Log) with comprehensive configuration options.
Features
- 🚀 Multiple Storage Drivers: Cache, Database, Redis
- 📱 Multiple Delivery Methods: SMS (Twilio, Nexmo), Email, Log
- ⚡ High Performance: Optimized for production use
- 🔒 Security Features: Rate limiting, attempt tracking, automatic cleanup
- 🎨 Flexible Configuration: Customizable code types, lengths, TTL, and messages
- 🧪 Well Tested: Comprehensive test coverage
- 📦 Laravel Integration: Service provider, facades, and artisan commands
Installation
Via Composer
composer require aslnbxrz/simple-otp
Publish Configuration
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-config"
Publish Migrations (for database storage)
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-migrations" php artisan migrate
Publish Email Views (optional)
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-views"
Configuration
The package configuration file will be published to config/simple-otp.php. Here's an overview of the main configuration options:
Storage Configuration
// config/simple-otp.php return [ 'default' => env('SIMPLE_OTP_STORAGE', 'cache'), 'drivers' => [ 'cache' => [ 'driver' => 'cache', 'store' => env('SIMPLE_OTP_CACHE_STORE', null), // null means use default cache store ], 'database' => [ 'driver' => 'database', 'table' => 'simple_otp_codes', 'connection' => env('SIMPLE_OTP_DB_CONNECTION', null), ], 'redis' => [ 'driver' => 'redis', 'connection' => env('SIMPLE_OTP_REDIS_CONNECTION', 'default'), 'prefix' => env('SIMPLE_OTP_REDIS_PREFIX', 'simple_otp:'), ], ], ];
Delivery Configuration
'delivery' => [ 'default' => env('SIMPLE_OTP_DELIVERY', 'log'), 'drivers' => [ 'sms' => [ 'driver' => 'sms', 'provider' => env('SIMPLE_OTP_SMS_PROVIDER', 'twilio'), 'config' => [ 'twilio' => [ 'account_sid' => env('TWILIO_ACCOUNT_SID'), 'auth_token' => env('TWILIO_AUTH_TOKEN'), 'from' => env('TWILIO_FROM_NUMBER'), ], 'nexmo' => [ 'api_key' => env('NEXMO_API_KEY'), 'api_secret' => env('NEXMO_API_SECRET'), 'from' => env('NEXMO_FROM_NUMBER'), ], 'eskiz' => [ 'email' => env('ESKIZ_EMAIL'), 'password' => env('ESKIZ_PASSWORD'), 'from' => env('ESKIZ_FROM', '4546'), 'base_url' => env('ESKIZ_BASE_URL', 'https://notify.eskiz.uz/api'), ], 'telegram' => [ 'bot_token' => env('TELEGRAM_BOT_TOKEN'), 'parse_mode' => env('TELEGRAM_PARSE_MODE', 'HTML'), 'disable_web_page_preview' => env('TELEGRAM_DISABLE_PREVIEW', true), ], ], ], 'email' => [ 'driver' => 'email', 'mailable' => \Aslnbxrz\SimpleOTP\Mail\OTPMailable::class, 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], ], ], ],
OTP Configuration
'otp' => [ 'type' => env('SIMPLE_OTP_TYPE', 'numeric'), // numeric, alphanumeric, alpha 'length' => (int) env('SIMPLE_OTP_LENGTH', 6), 'ttl' => (int) env('SIMPLE_OTP_TTL', 5), // minutes 'max_attempts' => (int) env('SIMPLE_OTP_MAX_ATTEMPTS', 3), 'rate_limit' => [ 'enabled' => env('SIMPLE_OTP_RATE_LIMIT_ENABLED', true), 'max_attempts' => (int) env('SIMPLE_OTP_RATE_LIMIT_ATTEMPTS', 5), 'decay_minutes' => (int) env('SIMPLE_OTP_RATE_LIMIT_DECAY', 60), ], ],
Environment Variables
Add these variables to your .env file:
# Storage Configuration SIMPLE_OTP_STORAGE=cache SIMPLE_OTP_CACHE_STORE=null SIMPLE_OTP_DB_CONNECTION=mysql SIMPLE_OTP_REDIS_CONNECTION=default SIMPLE_OTP_REDIS_PREFIX=simple_otp: # Delivery Configuration SIMPLE_OTP_DELIVERY=log SIMPLE_OTP_SMS_PROVIDER=twilio # Twilio Configuration TWILIO_ACCOUNT_SID=your_account_sid TWILIO_AUTH_TOKEN=your_auth_token TWILIO_FROM_NUMBER=+1234567890 # Nexmo Configuration (alternative) NEXMO_API_KEY=your_api_key NEXMO_API_SECRET=your_api_secret NEXMO_FROM_NUMBER=1234567890 # Eskiz Configuration (Uzbekistan) ESKIZ_EMAIL=your_email ESKIZ_PASSWORD=your_password ESKIZ_FROM=4546 ESKIZ_BASE_URL=https://notify.eskiz.uz/api # Telegram Configuration TELEGRAM_BOT_TOKEN=your_bot_token TELEGRAM_PARSE_MODE=HTML TELEGRAM_DISABLE_PREVIEW=true # OTP Configuration SIMPLE_OTP_TYPE=numeric SIMPLE_OTP_LENGTH=6 SIMPLE_OTP_TTL=5 SIMPLE_OTP_MAX_ATTEMPTS=3 SIMPLE_OTP_RATE_LIMIT_ENABLED=true SIMPLE_OTP_RATE_LIMIT_ATTEMPTS=5 SIMPLE_OTP_RATE_LIMIT_DECAY=60
Usage
Basic Usage with Facade
use Aslnbxrz\SimpleOTP\Facades\SimpleOTP; // Generate and send OTP $result = SimpleOTP::generate('user-123', 'user@example.com'); // Returns: ['success' => true, 'message' => 'OTP code has been sent successfully.', ...] // Verify OTP $verified = SimpleOTP::verify('user-123', '123456'); // Returns: true or throws OTPException // Check if OTP exists $exists = SimpleOTP::exists('user-123'); // Returns: true/false // Get OTP information $info = SimpleOTP::info('user-123'); // Returns: ['identifier' => 'user-123', 'recipient' => 'user@example.com', ...] // Resend OTP $result = SimpleOTP::resend('user-123', 'user@example.com'); // Delete OTP $deleted = SimpleOTP::delete('user-123');
Usage in Controllers
<?php namespace App\Http\Controllers; use Aslnbxrz\SimpleOTP\Facades\SimpleOTP; use Aslnbxrz\SimpleOTP\Exceptions\OTPException; use Illuminate\Http\Request; class AuthController extends Controller { public function sendOTP(Request $request) { try { $identifier = 'user-' . $request->user()->id; $recipient = $request->user()->phone; // or email $result = SimpleOTP::generate($identifier, $recipient); return response()->json([ 'success' => true, 'message' => $result['message'], 'expires_at' => $result['expires_at'], ]); } catch (OTPException $e) { return response()->json([ 'success' => false, 'message' => $e->getMessage(), ], 400); } } public function verifyOTP(Request $request) { try { $identifier = 'user-' . $request->user()->id; $code = $request->input('code'); $verified = SimpleOTP::verify($identifier, $code); if ($verified) { // Mark user as verified or perform other actions $request->user()->markAsVerified(); return response()->json([ 'success' => true, 'message' => 'Phone number verified successfully.', ]); } } catch (OTPException $e) { return response()->json([ 'success' => false, 'message' => $e->getMessage(), ], 400); } } }
Custom SMS/Email Messages
// Custom SMS message $result = SimpleOTP::generate('user-123', '+1234567890', [ 'message' => 'Your verification code for MyApp is: {code}' ]); // Custom email subject and message $result = SimpleOTP::generate('user-123', 'user@example.com', [ 'subject' => 'Verify Your Account', 'message' => 'Please use the following code to verify your account: {code}' ]);
Storage Drivers
Cache Storage (Default)
- Uses Laravel's cache system
- Automatic expiration
- High performance
- Suitable for most applications
Database Storage
- Persistent storage
- Better for distributed applications
- Requires migration
- Automatic cleanup available
Redis Storage
- High performance
- Distributed caching
- Automatic expiration
- Best for high-traffic applications
Delivery Drivers
SMS Driver
Currently supports:
- Twilio: Popular SMS service provider
- Nexmo (Vonage): International SMS service
- Eskiz: Uzbekistan SMS service provider (using native cURL)
- Telegram: Telegram Bot API for instant messaging
Email Driver
- Uses Laravel's mail system
- Customizable templates
- HTML and text versions
Log Driver
- For development and testing
- Logs OTP codes to Laravel logs
- No external dependencies
Advanced Features
Rate Limiting
The package includes built-in rate limiting to prevent abuse:
'rate_limit' => [ 'enabled' => true, 'max_attempts' => 5, // Max OTP requests per time window 'decay_minutes' => 60, // Time window in minutes ],
Custom Code Types
Generate different types of OTP codes:
// Numeric (default): 123456 'type' => 'numeric' // Alphanumeric: A1B2C3 'type' => 'alphanumeric' // Alpha only: ABCDEF 'type' => 'alpha'
Automatic Cleanup
Expired OTP codes are automatically cleaned up based on configuration:
'cleanup' => [ 'enabled' => true, 'interval_hours' => 24, // Run cleanup every 24 hours ],
Testing
The package includes comprehensive tests. To run them:
composer test
Error Handling
The package throws specific exceptions that you can catch and handle:
use Aslnbxrz\SimpleOTP\Exceptions\OTPException; use Aslnbxrz\SimpleOTP\Exceptions\OTPDeliveryException; try { SimpleOTP::generate('user-123', 'user@example.com'); } catch (OTPDeliveryException $e) { // Handle delivery failure (SMS/Email service down, etc.) Log::error('OTP delivery failed: ' . $e->getMessage()); } catch (OTPException $e) { // Handle other OTP-related errors Log::error('OTP error: ' . $e->getMessage()); }
Security Considerations
- Rate Limiting: Always enable rate limiting in production
- TTL: Use appropriate TTL values (5-10 minutes recommended)
- Max Attempts: Limit verification attempts (3-5 recommended)
- Storage: Use Redis or Database for production (not cache)
- HTTPS: Always use HTTPS in production
- Cleanup: Enable automatic cleanup of expired codes
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for your changes
- Run the test suite
- Submit a pull request
License
This package is open-sourced software licensed under the MIT license.
Support
For support, please open an issue on the GitHub repository.
Changelog
v1.0.0
- Initial release
- Multiple storage drivers (Cache, Database, Redis)
- Multiple delivery methods (SMS, Email, Log)
- Rate limiting and security features
- Comprehensive test coverage
- Laravel integration with facades and service providers
aslnbxrz/simple-otp 适用场景与选型建议
aslnbxrz/simple-otp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 10 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Authentication」 「email」 「sms」 「laravel」 「otp」 「verification」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 aslnbxrz/simple-otp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 aslnbxrz/simple-otp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 aslnbxrz/simple-otp 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
Email Toolkit Plugin for CakePHP
SDK for payment gateway PlatbaMobilom.sk for PHP7.0
Extensible library for building notifications and sending them via different delivery channels.
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 11
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-09