A simple Laravel package for generating and verifying One-Time Passwords (OTPs) using TOTP (Time-based One-Time Password) and HOTP (HMAC-based One-Time Password) algorithms.
You can install the package via Composer:
composer require mkd/laravel-otp
Scan This QR Code using Authenticator app
Here's a simple example demonstrating how to generate and verify an OTP:
use MKD\LaravelOTP\LaravelOTP;
$secret = 'WSRNGQX4J57FL2POVHDAMBI6ZTK3CYUE'; // Base32 encoded secret
$otpService = LaravelOTP::make($secret);
// Generate current OTP
$currentOTP = $otpService->now();
echo "Current OTP: $currentOTP\n";
// Verify the OTP
$isValid = $otpService->verifyTOTP($currentOTP);
echo $isValid ? "OTP is valid!" : "OTP is invalid!";
You can create an instance of the LaravelOTP
class by providing a secret key:
use MKD\LaravelOTP\LaravelOTP;
$otpService = LaravelOTP::make('your-secret-key');
Returns the current TOTP for the current timeframe.
$otp = $otpService->now();
Returns the TOTP for the previous timeframe (30 seconds earlier).
$otp = $otpService->last();
Returns the TOTP for the next timeframe (30 seconds later).
$otp = $otpService->next();
Returns the TOTP for a custom timeframe based on the provided offset. An offset of 0
returns the current TOTP, -1
returns the last OTP, and 1
returns the next OTP.
$otp = $otpService->at(-1); // Last TOTP
$otp = $otpService->at(1); // Next TOTP
Generates a new secret key.
$secretKey = $otpService->generateSecretKey();
Returns the HOTP for a specific counter value.
$otp = $otpService->atCounter(1); // OTP for counter 1
Verifies a given TOTP against the current, previous, and next timeframes. If a secret key is provided, it overrides the current secret.
$isValid = $otpService->verifyTOTP('123456'); // Validate TOTP
Verifies a given HOTP against a specific counter. If a secret key is provided, it overrides the current secret.
$isValid = $otpService->verifyHOTP('123456', 1); // Validate HOTP for counter 1
Generates an OTP Auth URL for use in generating a QR code. This URL can be used by OTP apps like Google Authenticator.
- Parameters:
string $label
: A unique identifier for the OTP (usually the user's email or username).string $issuer
: The name of your application (used as the issuer for the OTP).string|null $secretKey
: An optional secret key. If not provided, the instance's secret key will be used.int|null $counter
: An optional counter for HOTP. If provided, the method will generate an HOTP URL instead of TOTP.
Usage Example:
$label = 'user@example.com';
$issuer = 'YourAppName';
$otpUrl = $otpService->generateUrl($label, $issuer);
echo "OTP Auth URL: $otpUrl" // otpauth://totp/Name?secret=WSRNGQX4J57FL2POVHDAMBI6ZTK3CYUE&issuer=APP;
This package is licensed under the MIT License. See the LICENSE file for more information.