In this post I will show how to generate and validate the OTP (One Time Password) using a simple Laravel package. https://github.com/seshac/otp-generator.
So, Let's start and follow below three simple steps.
- You can generate OTP using any unique identification (Prefer Mobile number or Email),
- Send to end user using any notification provider
- Finally, verify using the same unique identification.
Installation and Setup process :
Installation
You can install the package via composer:
composer require seshac/otp-generator
You can publish and run the migrations with:
php artisan vendor:publish --provider="Seshac\Otp\OtpServiceProvider" --tag="migrations"
php artisan migrate
You can publish the config file with:
php artisan vendor:publish --provider="Seshac\Otp\OtpServiceProvider" --tag="config"
Once you published you can configure all otp-generator.php config values based on your requirements.
Usage
use Seshac\Otp\Otp;
.
.
$otp = Otp::generate($identifier);
.
$verify = Otp::validate($identifier, $otp->token);
// response
{
"status": true
"message": "OTP is valid"
}
You have control to update the setting at otp-generator.php config file, but you control while generating also
Advance Usage
use Seshac\Otp\Otp;
.
.
$otp = Otp::setValidity(30) // otp validity time in mins
->setLength(4) // Lenght of the generated otp
->setMaximumOtpsAllowed(10) // Number of times allowed to regenerate otps
->setOnlyDigits(false) // generated otp contains mixed characters ex:ad2312
->setUseSameToken(true) // if you re-generate OTP, you will get same token
->generate($identifier);
.
$verify = Otp::setAllowedAttempts(10) // number of times they can allow to attempt with wrong token
->validate($identifier, $otp->token);
Here the GitHub repository https://github.com/seshac/otp-generator
If you find any issues, please, feel to free open an issue here.
https://github.com/seshac/otp-generator/issues
Top comments (7)
Is there a way to forcibly expire tokens after they are verified?
No, Please open a issue on github and we can work on that.
Is Laravel 8 supported?
Yes, it's
Love it
migration file is not generated
Please create an issue with details, we will fix soon!