PHP code example of fouladgar / laravel-otp

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');

OTP::channel('mail')->send('[email protected]');

OTP::channel(['mail', \App\Channels\CustomChannel::class])
    ->send('+98900000000');

OTP::validate('+98900000000', 'token_123'); // returns bool

use Fouladgar\OTP\Facades\OTP;

OTP::send('+98900000000');
$token = OTP::getToken();

OTP::revoke('+98900000000');



namespace App\Channels;

use Fouladgar\OTP\Notifications\OTPNotification;
use Fouladgar\OTP\Notifications\Messages\OTPMessage;
use Fouladgar\OTP\Notifications\Messages\MessagePayload;

class MySMSChannel
{
    public function send($notifiable, OTPNotification $notification): void
    {
        $message = $notification->toSMS($notifiable);

        // $message->getPayload()->to()      → recipient
        // $message->getPayload()->content() → token message
    }
}

// config/otp.php

return [
    // ...

    'channel' => \App\Channels\MySMSChannel::class,
];

// config/otp.php

return [
    /*
    |--------------------------------------------------------------------------
    | Supported drivers: "cache", "database"
    |--------------------------------------------------------------------------
    */
    'token_storage' => 'cache',
];

// config/otp.php

return [
    'token_table' => 'otp_token',

    // ...
];

// routes/console.php

Schedule::command('otp:prune')->daily();

// config/otp.php

return [
    'token_lifetime' => env('OTP_TOKEN_LIFE_TIME', 2),

    // ...
];

// config/otp.php

return [
    // ...

    'token_length' => env('OTP_TOKEN_LENGTH', 5),

    // ...
];

// config/otp.php

return [
    // ...

    'token_generator' => Fouladgar\OTP\Token\Generators\NumericAbstractTokenGenerator::class,

    // ...
];

'token_generator' => Fouladgar\OTP\Token\Generators\AlphanumericAbstractTokenGenerator::class,

use Fouladgar\OTP\Contracts\AbstractTokenGenerator;

class MyTokenGenerator extends AbstractTokenGenerator
{
    public function generate(int $length): string
    {
        // (random_int/random_bytes) — never rand() or mt_rand().
    }
}

// config/otp.php

return [
    // ...

    'rate_limit' => [
        'max_attempts'  => env('OTP_RATE_LIMIT_MAX_ATTEMPTS', 5),
        'decay_seconds' => env('OTP_RATE_LIMIT_DECAY_SECONDS', 60),
    ],

    // ...
];

'rate_limit' => [
    'max_attempts'  => null,
    'decay_seconds' => 60,
],

// config/otp.php

return [
    // ...

    'validation_timebox_microseconds' => env('OTP_VALIDATION_TIMEBOX_MICROSECONDS', 200_000),

    // ...
];

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,
]);

php artisan vendor:publish --provider="Fouladgar\OTP\ServiceProvider" --tag="config"

php artisan migrate

php artisan vendor:publish --provider="Fouladgar\OTP\ServiceProvider" --tag="lang"