1. Go to this page and download the library: Download fouladgar/laravel-otp library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
fouladgar / laravel-otp example snippets
use Fouladgar\OTP\Facades\OTP;
OTP::send('+98900000000');
use Fouladgar\OTP\Contracts\AbstractTokenGenerator;
class MyTokenGenerator extends AbstractTokenGenerator
{
public function generate(int $length): string
{
// (random_int/random_bytes) — never rand() or mt_rand().
}
}
use Fouladgar\OTP\Facades\OTP;
OTP::purpose('login_')->send('+98900000000');
OTP::purpose('password_reset_')->send('+98900000000');
// This does not affect the still-pending "login_" token.
OTP::purpose('password_reset_')->validate('+98900000000', 'token_123');
use Fouladgar\OTP\Facades\OTP;
OTP::withNotify(false)->send('98900000000');
'with_notify' => false,
use Fouladgar\OTP\Events\TokenCreated;
use Illuminate\Support\Facades\Event;
// e.g. in App\Providers\EventServiceProvider::boot()
Event::listen(TokenCreated::class, function (TokenCreated $event) {
// publish to your notification microservice, e.g.:
// NotificationServiceClient::send($event->recipient, $event->token);
});
use Fouladgar\OTP\Enums\OTPExceptionReason;
use Fouladgar\OTP\Exceptions\OTPException;
use Fouladgar\OTP\Facades\OTP;
try {
OTP::validate('+98900000000', $request->string('token'));
} catch (OTPException $e) {
return match ($e->reason) {
OTPExceptionReason::InvalidToken => back()->withErrors(['token' => $e->getMessage()]),
OTPExceptionReason::TooManyAttempts => back()->withErrors(['token' => $e->getMessage()]),
default => throw $e,
};
}
use Fouladgar\OTP\Notifications\OTPNotification;
use Fouladgar\OTP\Notifications\Messages\OTPMessage;
use Illuminate\Notifications\Messages\MailMessage;
public function boot()
{
OTPNotification::toSMSUsing(fn ($recipient, $token) => (new OTPMessage())
->to($recipient)
->content('Your OTP Token is: '.$token)
->template('OTP_TEMPLATE'));
OTPNotification::toMailUsing(fn ($recipient, $token) => (new MailMessage)
->subject('OTP Request')
->line('Your OTP Token is: '.$token));
}
// resources/lang/vendor/OTP/en/otp.php
return [
'otp_token' => 'Your OTP Token is: :token.',
'otp_subject' => 'OTP request',
'too_many_attempts' => 'Too many attempts. Please try again later.',
];
use Fouladgar\OTP\Facades\OTP;
// Generate and store a random token, then use the returned value in your test.
$token = OTP::fake('98900000000');
// Or force a specific value if your test needs to assert on it:
$token = OTP::fake('98900000000', '12345');
// Pass a purpose directly if you are not using the default one.
$token = OTP::fake('98900000000', '12345', 'login_');
$this->postJson('/login-otp', [
'mobile' => '98900000000',
'token' => $token,
]);