unrulynatives/laravel-otp-manager
Composer 安装命令:
composer require unrulynatives/laravel-otp-manager
包简介
Laravel OTP manager
README 文档
README
Laravel OTP Manager
The OtpManager class is responsible for sending and verifying one-time passwords (OTPs). It provides a comprehensive set of methods to generate, send, verify, and manage OTPs. It also integrates with Laravel cache system to throttle OTP sending and provides a layer of security by tracking OTP requests.
Features
- Main Features
- Generate OTP codes
- Send OTPs via mobile numbers
- Resend OTPs with built-in throttling
- Verify OTP codes
- Track OTP requests
- Security
- Rate limiting of OTP generation attempts (
OtpRateLimitermiddleware) - Otp Invalidation after multiple failed verifications
- Automatic deletion of OTP codes after successful verification
- Rate limiting of OTP generation attempts (
- Configuration
- Customize rate-limiting thresholds, max allowed attempts, and auto-delete
- Flexibility
- Supports multiple OTP types using enums
- Customizable mobile number validation
Requirements
PHP: ^8.1Laravel framework: ^9
| Version | L9 | L10 | L11 |
|---|---|---|---|
| 1.5 | ✅ | ✅ | ✅ |
Installation
To install the package, you can run the following command:
composer require salehhashemi/laravel-otp-manager
Usage
Sending OTP
use Salehhashemi\OtpManager\Facade\OtpManager; $sentOtp = OtpManager::send("1234567890");
Resending OTP
The sendAndRetryCheck method will throw a ValidationException if you try to resend the OTP before the waiting time expires.
$sentOtp = OtpManager::sendAndRetryCheck("1234567890");
Verifying OTP
$isVerified = OtpManager::verify("1234567890", 123456, "uuid-string");
Deleting Verification Code
$isDeleted = OtpManager::deleteVerifyCode("1234567890");
Handling and Listening to the OtpPrepared Event
The OtpManager package emits an OtpPrepared event whenever a new OTP is generated. You can listen to this event and execute custom logic, such as sending the OTP via SMS or email.
Here's how to set up an event listener:
Step 1: Register the Event and Listener
First, you need to register the OtpPrepared event and its corresponding listener. Open your EventServiceProvider file, usually located at app/Providers/EventServiceProvider.php, and add the event and listener to the $listen array.
protected $listen = [ \Salehhashemi\OtpManager\Events\OtpPrepared::class => [ \App\Listeners\SendOtpNotification::class, ], ];
Step 2: Create the Listener
If the listener does not exist, you can generate it using the following Artisan command:
php artisan make:listener SendOtpNotification
Step 3: Implement the Listener
Now open the generated SendOtpNotification listener file, typically located at app/Listeners/. You'll see a handle method, where you can add your custom logic for sending the OTP.
Here's a sample implementation:
use Salehhashemi\OtpManager\Events\OtpPrepared; class SendOtpNotification { public function handle(OtpPrepared $event) { $mobile = $event->mobile; $otpCode = $event->code; // Send the OTP code to the mobile number // You can use your preferred SMS service here. } }
Step 4: Test the Event Listener
Once you've set up the listener, generate a new OTP through the OtpManager package to make sure the OtpPrepared event is being caught and the corresponding listener logic is being executed.
That's it! You've successfully set up an event listener for the OtpPrepared event in the OtpManager package.
Using Enums for OTP Types
You can take advantage of enums to define your OTP types. Enums provide a more expressive way to manage different categories of OTPs.
How to Define an OTP Enum
use Salehhashemi\OtpManager\Contracts\OtpTypeInterface; enum MyOtpEnum: string implements OtpTypeInterface { case SIGNUP = 'signup'; case RESET_PASSWORD = 'reset_password'; public function identifier(): string { return $this->value; } }
Usage
After defining your enum, you can use it just like any other OTP type:
OtpManager::send('1234567890', MyOtpEnum::SIGNUP); OtpManager::verify('1234567890', $otpCode, $trackingCode, MyOtpEnum::SIGNUP);
Configuration
To publish the config file, run the following command:
php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="config"
To publish the language files, run:
php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="lang"
After publishing, make sure to clear the config cache to apply your changes:
php artisan config:clear
Then, you can adjust the waiting_time, code_min, and code_max in the config/otp.php
Middleware Protection
The OtpManager package includes built-in middleware (OtpRateLimiter) to protect your application routes from excessive OTP requests. This helps prevent potential abuse.
To apply the middleware:
Register the middleware: Add \Salehhashemi\OtpManager\Middleware\OtpRateLimiter::class to the middlewareAliases array in your app\Http\Kernel.php file.
Assign the middleware to routes: You can apply it to specific routes or route groups where you want to implement rate limiting.
Example:
Route::middleware('otp-rate-limiter')->group(function () { // Routes that require OTP rate limiting go here });
Custom Mobile Number Validation
The package comes with a default mobile number validator, but you can easily use your own.
Here's how you can do it:
- Create a Custom Validator Class
First, create a class that implements
MobileValidatorInterface. This interface expects you to define a validate method.use Salehhashemi\OtpManager\Contracts\MobileValidatorInterface; class CustomMobileValidator implements MobileValidatorInterface { public function validate(string $mobile): void { // Your validation logic here } }
- Update Configuration
Next, open your OTP configuration file and update the
mobile_validation_classoption to use your custom validator class:'mobile_validation_class' => CustomMobileValidator::class,
Exceptions
\InvalidArgumentExceptionwill be thrown if the mobile number is empty.\Exceptionwill be thrown for general exceptions, like OTP generation failures.\Illuminate\Validation\ValidationExceptionwill be thrown for throttle restrictions.\Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpExceptionwill be thrown for throttled requests.
Docker Setup
This project uses Docker for local development and testing. Make sure you have Docker and Docker Compose installed on your system before proceeding.
Build the Docker images
docker-compose build
Start the services
docker-compose up -d
To access the PHP container, you can use:
docker-compose exec php bash
Testing
composer test
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Credits
License
The MIT License (MIT). Please see License File for more information.
unrulynatives/laravel-otp-manager 适用场景与选型建议
unrulynatives/laravel-otp-manager 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 02 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「security」 「Authentication」 「sms」 「two-factor」 「laravel」 「otp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 unrulynatives/laravel-otp-manager 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 unrulynatives/laravel-otp-manager 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 unrulynatives/laravel-otp-manager 相关的其它包
同方向 / 同关键字的高下载量 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.
Provide a way to secure accesses to all routes of an symfony application.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
It's a barebone security class written on PHP
Email Toolkit Plugin for CakePHP
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-02-08
