PHP code example of aslnbxrz / simple-otp

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

    

aslnbxrz / simple-otp example snippets


// config/simple-otp.php
return [
    'default' => env('SIMPLE_OTP_STORAGE', 'cache'),
    
    'drivers' => [
        'cache' => [
            'driver' => 'cache',
            'store' => env('SIMPLE_OTP_CACHE_STORE', null), // null means use default cache store
        ],
        
        'database' => [
            'driver' => 'database',
            'table' => 'simple_otp_codes',
            'connection' => env('SIMPLE_OTP_DB_CONNECTION', null),
        ],
        
        'redis' => [
            'driver' => 'redis',
            'connection' => env('SIMPLE_OTP_REDIS_CONNECTION', 'default'),
            'prefix' => env('SIMPLE_OTP_REDIS_PREFIX', 'simple_otp:'),
        ],
    ],
];

'delivery' => [
    'default' => env('SIMPLE_OTP_DELIVERY', 'log'),
    
    'drivers' => [
        'sms' => [
            'driver' => 'sms',
            'provider' => env('SIMPLE_OTP_SMS_PROVIDER', 'twilio'),
            'config' => [
                'twilio' => [
                    'account_sid' => env('TWILIO_ACCOUNT_SID'),
                    'auth_token' => env('TWILIO_AUTH_TOKEN'),
                    'from' => env('TWILIO_FROM_NUMBER'),
                ],
                'nexmo' => [
                    'api_key' => env('NEXMO_API_KEY'),
                    'api_secret' => env('NEXMO_API_SECRET'),
                    'from' => env('NEXMO_FROM_NUMBER'),
                ],
                    'eskiz' => [
                        'email' => env('ESKIZ_EMAIL'),
                        'password' => env('ESKIZ_PASSWORD'),
                        'from' => env('ESKIZ_FROM', '4546'),
                        'base_url' => env('ESKIZ_BASE_URL', 'https://notify.eskiz.uz/api'),
                    ],
                    'telegram' => [
                        'bot_token' => env('TELEGRAM_BOT_TOKEN'),
                        'parse_mode' => env('TELEGRAM_PARSE_MODE', 'HTML'),
                        'disable_web_page_preview' => env('TELEGRAM_DISABLE_PREVIEW', true),
                    ],
            ],
        ],
        
        'email' => [
            'driver' => 'email',
            'mailable' => \Aslnbxrz\SimpleOTP\Mail\OTPMailable::class,
            'from' => [
                'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
                'name' => env('MAIL_FROM_NAME', 'Example'),
            ],
        ],
    ],
],

'otp' => [
    'type' => env('SIMPLE_OTP_TYPE', 'numeric'), // numeric, alphanumeric, alpha
    'length' => (int) env('SIMPLE_OTP_LENGTH', 6),
    'ttl' => (int) env('SIMPLE_OTP_TTL', 5), // minutes
    'max_attempts' => (int) env('SIMPLE_OTP_MAX_ATTEMPTS', 3),
    
    'rate_limit' => [
        'enabled' => env('SIMPLE_OTP_RATE_LIMIT_ENABLED', true),
        'max_attempts' => (int) env('SIMPLE_OTP_RATE_LIMIT_ATTEMPTS', 5),
        'decay_minutes' => (int) env('SIMPLE_OTP_RATE_LIMIT_DECAY', 60),
    ],
],

use Aslnbxrz\SimpleOTP\Facades\SimpleOTP;

// Generate and send OTP
$result = SimpleOTP::generate('user-123', '[email protected]');
// Returns: ['success' => true, 'message' => 'OTP code has been sent successfully.', ...]

// Verify OTP
$verified = SimpleOTP::verify('user-123', '123456');
// Returns: true or throws OTPException

// Check if OTP exists
$exists = SimpleOTP::exists('user-123');
// Returns: true/false

// Get OTP information
$info = SimpleOTP::info('user-123');
// Returns: ['identifier' => 'user-123', 'recipient' => '[email protected]', ...]

// Resend OTP
$result = SimpleOTP::resend('user-123', '[email protected]');

// Delete OTP
$deleted = SimpleOTP::delete('user-123');



namespace App\Http\Controllers;

use Aslnbxrz\SimpleOTP\Facades\SimpleOTP;
use Aslnbxrz\SimpleOTP\Exceptions\OTPException;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function sendOTP(Request $request)
    {
        try {
            $identifier = 'user-' . $request->user()->id;
            $recipient = $request->user()->phone; // or email
            
            $result = SimpleOTP::generate($identifier, $recipient);
            
            return response()->json([
                'success' => true,
                'message' => $result['message'],
                'expires_at' => $result['expires_at'],
            ]);
        } catch (OTPException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
    
    public function verifyOTP(Request $request)
    {
        try {
            $identifier = 'user-' . $request->user()->id;
            $code = $request->input('code');
            
            $verified = SimpleOTP::verify($identifier, $code);
            
            if ($verified) {
                // Mark user as verified or perform other actions
                $request->user()->markAsVerified();
                
                return response()->json([
                    'success' => true,
                    'message' => 'Phone number verified successfully.',
                ]);
            }
        } catch (OTPException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}

// Custom SMS message
$result = SimpleOTP::generate('user-123', '+1234567890', [
    'message' => 'Your verification code for MyApp is: {code}'
]);

// Custom email subject and message
$result = SimpleOTP::generate('user-123', '[email protected]', [
    'subject' => 'Verify Your Account',
    'message' => 'Please use the following code to verify your account: {code}'
]);

'rate_limit' => [
    'enabled' => true,
    'max_attempts' => 5, // Max OTP requests per time window
    'decay_minutes' => 60, // Time window in minutes
],

// Numeric (default): 123456
'type' => 'numeric'

// Alphanumeric: A1B2C3
'type' => 'alphanumeric'

// Alpha only: ABCDEF
'type' => 'alpha'

'cleanup' => [
    'enabled' => true,
    'interval_hours' => 24, // Run cleanup every 24 hours
],

use Aslnbxrz\SimpleOTP\Exceptions\OTPException;
use Aslnbxrz\SimpleOTP\Exceptions\OTPDeliveryException;

try {
    SimpleOTP::generate('user-123', '[email protected]');
} catch (OTPDeliveryException $e) {
    // Handle delivery failure (SMS/Email service down, etc.)
    Log::error('OTP delivery failed: ' . $e->getMessage());
} catch (OTPException $e) {
    // Handle other OTP-related errors
    Log::error('OTP error: ' . $e->getMessage());
}
bash
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-config"
bash
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-migrations"
php artisan migrate
bash
php artisan vendor:publish --provider="Aslnbxrz\\SimpleOTP\\SimpleOTPServiceProvider" --tag="simple-otp-views"