PHP code example of litepie / otp

1. Go to this page and download the library: Download litepie/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/ */

    

litepie / otp example snippets


protected function schedule(Schedule $schedule)
{
    $schedule->command('otp:cleanup')->daily();
}

use Litepie\Otp\Facades\Otp;

// Generate and send OTP
$otp = Otp::generate()
    ->for('[email protected]')
    ->type('login')
    ->send();

// Verify OTP
$isValid = Otp::verify('123456', '[email protected]', 'login');

if ($isValid) {
    // OTP is valid, proceed with authentication
    return response()->json(['message' => 'Login successful']);
}

// Custom OTP with specific settings
$otp = Otp::generate()
    ->for('[email protected]')
    ->type('password_reset')
    ->length(8)                    // 8 digits
    ->format('alphanumeric')       // Letters and numbers
    ->expiresIn(900)              // 15 minutes
    ->via(['email', 'sms'])       // Multiple channels
    ->with(['user_id' => 123])    // Additional data
    ->send();

// Check if OTP exists before generating new one
if (!Otp::exists('[email protected]', 'login')) {
    $otp = Otp::generate()
        ->for('[email protected]')
        ->type('login')
        ->send();
}

// Invalidate existing OTP
Otp::invalidate('[email protected]', 'login');

use Litepie\Otp\Exceptions\TooManyAttemptsException;
use Litepie\Otp\Exceptions\RateLimitExceededException;

try {
    $isValid = Otp::verify($code, $email, 'login');
} catch (TooManyAttemptsException $e) {
    return response()->json(['error' => 'Too many failed attempts'], 429);
} catch (RateLimitExceededException $e) {
    return response()->json(['error' => 'Rate limit exceeded'], 429);
}

// config/otp.php
'types' => [
    'transaction_verify' => [
        'length' => 8,
        'format' => 'alphanumeric',
        'expires_in' => 600, // 10 minutes
        'max_attempts' => 3,
        'channels' => ['email', 'sms'],
        'rate_limit' => [
            'max_attempts' => 2,
            'decay_minutes' => 30,
        ],
    ],
],

Otp::generate()
    ->for('[email protected]')
    ->via('email')
    ->send();

Otp::generate()
    ->for('+1234567890')
    ->via('sms')
    ->send();

Otp::generate()
    ->for('[email protected]')
    ->via('database')
    ->send();

// Retrieve from database
$otpRecord = \Litepie\Otp\Otp::where('identifier', '[email protected]')
    ->where('type', 'login')
    ->valid()
    ->first();

Otp::generate()
    ->for('[email protected]')
    ->via(['email', 'sms', 'database'])
    ->send();

use Litepie\Otp\Contracts\OtpChannelInterface;

class SlackChannel implements OtpChannelInterface
{
    public function send(string $identifier, string $code, array $data = []): bool
    {
        // Implementation for Slack delivery
        return true;
    }

    public function canHandle(string $identifier): bool
    {
        return str_starts_with($identifier, '@slack:');
    }
}

// Register the custom channel
Otp::extend('slack', function () {
    return new SlackChannel();
});

// In EventServiceProvider
protected $listen = [
    \Litepie\Otp\Events\OtpGenerated::class => [
        \App\Listeners\LogOtpGenerated::class,
    ],
    \Litepie\Otp\Events\OtpVerified::class => [
        \App\Listeners\LogOtpVerified::class,
        \App\Listeners\SendWelcomeEmail::class,
    ],
    \Litepie\Otp\Events\OtpFailed::class => [
        \App\Listeners\LogFailedOtpAttempt::class,
    ],
];

class LogOtpGenerated
{
    public function handle(\Litepie\Otp\Events\OtpGenerated $event)
    {
        Log::info('OTP generated', [
            'identifier' => $event->otp->identifier,
            'type' => $event->otp->type,
            'expires_at' => $event->otp->expires_at,
        ]);
    }
}

use Litepie\Otp\Facades\Otp;
use Illuminate\Support\Facades\Mail;

public function test_otp_generation_and_verification()
{
    Mail::fake();

    // Generate OTP
    $otp = Otp::generate()
        ->for('[email protected]')
        ->type('login')
        ->send();

    // Verify OTP
    $this->assertTrue(
        Otp::verify($otp->code, '[email protected]', 'login')
    );

    // Assert mail was sent
    Mail::assertSent(\Litepie\Otp\Notifications\OtpNotification::class);
}
bash
php artisan vendor:publish --provider="Litepie\Otp\OtpServiceProvider" --tag="config"
bash
php artisan migrate
bash
# Clean up expired OTPs (default: 7 days)
php artisan otp:cleanup

# Clean up OTPs older than specific days
php artisan otp:cleanup --days=3

# Force cleanup without confirmation
php artisan otp:cleanup --force