PHP code example of mkd / laravel-advanced-otp

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

    

mkd / laravel-advanced-otp example snippets


// Generate OTP and send it via email
$otp = \LaravelAdvancedOTP::handle(LoginOTP::class, [
    'secret' => 'secret_key',  // Required to hash and verify OTP
    'email' => '[email protected]',  // Email of the recipient
]);

// Get the hashed token for verification
$token = $otp->getHashedKey();

// Send OTP to user's email
$otp->send('[email protected]');

// Return the hashed token for later verification
return response()->json(['token' => $token]);

// Generate and send OTP without hashed token
\LaravelAdvancedOTP::handle(LoginOTP::class)->send('[email protected]');

$otp = request('otp');
$hashedToken = request('token');  // Token returned when sending OTP

$signature = [
    'secret' => 'secret_key',  // Same secret used during OTP generation
    'email' => '[email protected]',
];

// Verify the OTP using the hashed token
$otpStatus = \LaravelAdvancedOTP::verify(LoginOTP::class, $otp, $signature, $hashedToken);

if ($otpStatus == OTPStatusEnum::NOT_VERIFIED) {
    // OTP is invalid
}

if ($otpStatus == OTPStatusEnum::VERIFIED) {
    // OTP is valid
}

if ($otpStatus == OTPStatusEnum::EXPIRED) {
    // OTP has expired
}

$otp = request('otp');
$email = request('email');

// Custom validation for OTP
$otpVerified = \LaravelAdvancedOTP::validate(LoginOTP::class, $otp, $email);

if ($otpVerified) {
    // OTP is valid
} else {
    // OTP is invalid or expired
}

class LoginOTP extends MagicOTP
{
    protected int $timeout = 120;  // Timeout in seconds
    protected int $otpLength = 5;  // Length of the OTP

    public function send($email)
    {
        $otp = $this->getOTP();
        // Logic to send OTP via email
    }

    public function validate($otp, $email)
    {
        // Logic to validate OTP for the email
    }
}
bash
php artisan magic-otp:make LoginOTP