PHP code example of one-studio / otp

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

    

one-studio / otp example snippets


'providers' => [
    // ...
    OneStudio\Otp\OtpServiceProvider::class,
],

'aliases' => [
    // ...
    'Otp' => OneStudio\Otp\Facades\Otp::class,
],

return [
    // Default channel for OTP delivery: 'phone' or 'email'
    'default_channel' => env('OTP_DEFAULT_CHANNEL', 'phone'),

    // Default provider for phone OTPs
    'default' => env('OTP_PROVIDER', 'twilio'),

    // SMS/Phone providers
    'providers' => [
        'twilio' => [
            'driver' => 'twilio',
            'account_sid' => env('TWILIO_ACCOUNT_SID'),
            'auth_token' => env('TWILIO_AUTH_TOKEN'),
            'service_type' => env('TWILIO_SERVICE_TYPE', 'sms'), // 'sms' or 'verify'
            'verification_sid' => env('TWILIO_VERIFICATION_SID'), // Required for 'verify' service
            'from' => env('TWILIO_FROM'), // Required for 'sms' service
        ],
        'unifonic' => [
            'driver' => 'unifonic',
            'app_sid' => env('UNIFONIC_APP_SID'),
            'sender_id' => env('UNIFONIC_SENDER_ID'),
        ],
    ],

    // Email provider configuration
    'email' => [
        'driver' => 'email',
        'from_address' => env('OTP_EMAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS', '[email protected]')),
        'from_name' => env('OTP_EMAIL_FROM_NAME', env('MAIL_FROM_NAME', 'OTP Service')),
        'subject' => env('OTP_EMAIL_SUBJECT', 'Your Verification Code'),
    ],

    'otp_length' => env('OTP_LENGTH', 4),
    'otp_expiry' => env('OTP_EXPIRY', 5), // minutes
    'max_attempts' => env('MAX_ATTEMPTS', 3),
    'resend_delay' => env('RESEND_DELAY', 60), // seconds
    'block_duration' => env('BLOCK_DURATION', 30), // minutes after max attempts

    // Rate limiting configuration
    'rate_limit' => [
        'enabled' => env('OTP_RATE_LIMIT_ENABLED', true),
        'max_requests_per_hour' => env('OTP_MAX_REQUESTS_PER_HOUR', 3), // per phone number or email
        'block_duration' => env('OTP_BLOCK_DURATION', 60), // minutes to block after limit exceeded
    ],

    // Test mode configuration
    'test_mode' => env('OTP_TEST_MODE', false),
    'test_otp' => env('OTP_TEST_CODE', '8888'),
    'test_numbers' => [
        '+1234567890',
        '+9876543210',
        // Add more test numbers as needed
    ],
    'test_emails' => [
        '[email protected]',
        '[email protected]',
        // Add more test emails as needed
    ],
];

use OneStudio\Otp\Facades\Otp;

// Send OTP to phone number (uses default channel: phone)
$result = Otp::generate('+1234567890');

// Or explicitly specify phone channel
$result = Otp::generate('+1234567890', 'phone');

if ($result['success']) {
    echo "OTP sent via SMS!";
    echo "Channel: " . $result['channel']; // 'phone'
}

use OneStudio\Otp\Facades\Otp;

// Send OTP to email address
$result = Otp::generate('[email protected]', 'email');

if ($result['success']) {
    echo "OTP sent via email!";
    echo "Channel: " . $result['channel']; // 'email'
}

// Verification works the same way for both channels
$phone = '+1234567890';
$verifyResult = Otp::verify($phone, '1234');

// Or for email
$email = '[email protected]';
$verifyResult = Otp::verify($email, '1234');

if ($verifyResult['success']) {
    echo "Verified successfully!";
}

public function sendOtp(Request $request)
{
    $recipient = $request->input('recipient'); // phone or email
    $channel = $request->input('channel', 'phone'); // default to phone
    
    $result = Otp::generate($recipient, $channel);
    
    return response()->json($result);
}

[
    'success' => true,
    'message' => 'OTP sent successfully.',
    'remaining_time' => 60,
    'type' => 'success',
    'channel' => 'email' // or 'phone'
]

'locale' => 'ar', // For Arabic
'locale' => 'en', // For English

App::setLocale('ar'); // Switch to Arabic
App::setLocale('en'); // Switch to English

[
    'success' => false,
    'message' => 'Rate limit exceeded. Maximum 3 requests per hour allowed. Blocked for 60 minutes.',
    'remaining_time' => 3600, // seconds until unblocked
    'type' => 'rate_limited'
]

[
    'success' => false,
    'message' => 'Phone number is blocked due to rate limiting. Try again in 45 minutes.',
    'remaining_time' => 2700, // seconds remaining
    'type' => 'rate_limited'
]

// In config/otp.php
'test_numbers' => [
    '+1234567890',
    '+9876543210',
    '+201120305686', // Your test number
],

[
    'success' => true,
    'message' => 'OTP sent successfully.',
    'remaining_time' => 60,
    'type' => 'success'
]

use OneStudio\Otp\Facades\Otp;

// Generate OTP
$result = Otp::generate('+1234567890');

if ($result['success']) {
    echo "OTP sent successfully!";
    echo "Expires in: " . $result['expires_in'] . " seconds";
} else {
    echo "Failed to send OTP: " . $result['message'];
}

// Verify OTP
$verifyResult = Otp::verify('+1234567890', '1234');

if ($verifyResult['success']) {
    echo "OTP verified successfully!";
} else {
    echo "Verification failed: " . $verifyResult['message'];
    if (isset($verifyResult['remaining_attempts'])) {
        echo "Remaining attempts: " . $verifyResult['remaining_attempts'];
    }
}

use OneStudio\Otp\OtpService;

class AuthController extends Controller
{
    protected $otpService;

f
    public function __construct(OtpService $otpService)
    {
        $this->otpService = $otpService;
    }

    public function sendOtp(Request $request)
    {
        $phone = $request->input('phone');
        $result = $this->otpService->generate($phone);

        return response()->json($result);
    }
f
    public function verifyOtp(Request $request)
    {
        $phone = $request->input('phone');
        $code = $request->input('code');
        
        $result = $this->otpService->verify($phone, $code);

        return response()->json($result);
    }
}

use OneStudio\Otp\OtpManager;

$manager = app(OtpManager::class);
$provider = $manager->driver(); // Gets the default provider
$result = $provider->send('+1234567890', 'Your OTP is: 1234');

use OneStudio\Otp\Facades\Otp;

// Configure .env for Verify service
// TWILIO_SERVICE_TYPE=verify
// TWILIO_VERIFICATION_SID=VAxxxxxxxxxxxxx

// Generate and send OTP using Verify API
$result = Otp::generate('+1234567890');

if ($result['success']) {
    // OTP sent via Twilio Verify with custom code
    echo "Verification code sent!";
    echo "User will receive SMS from Twilio Verify service";
} else {
    echo "Error: " . $result['message'];
}

// The package handles verification automatically
$verifyResult = Otp::verify('+1234567890', '1234');

if ($verifyResult['success']) {
    // OTP verified successfully
    // User can proceed with registration/login
    echo "Phone number verified!";
} else {
    echo "Invalid code: " . $verifyResult['message'];
}

[
    'success' => bool,
    'message' => string,
    'expires_in' => int, // seconds
    'remaining_time' => int, // if resend delay active
    'blocked_until' => Carbon, // if blocked
]

[
    'success' => bool,
    'message' => string,
    'remaining_attempts' => int, // if verification failed
]

// Rate limiting
[
    'success' => false,
    'message' => 'Please wait 45 seconds before requesting a new OTP.',
    'remaining_time' => 45
]

// Blocked phone
[
    'success' => false,
    'message' => 'Too many attempts. Please try again later.',
    'blocked_until' => Carbon::now()->addMinutes(30)
]

// Invalid OTP
[
    'success' => false,
    'message' => 'Invalid OTP.',
    'remaining_attempts' => 2
]

// Expired OTP
[
    'success' => false,
    'message' => 'OTP expired or not found.'
]

// Rate limiting
[
    'success' => false,
    'message' => 'يرجى الانتظار 45 ثانية قبل طلب رمز تحقق جديد.',
    'remaining_time' => 45
]

// Blocked phone
[
    'success' => false,
    'message' => 'محاولات كثيرة جداً. يرجى المحاولة مرة أخرى لاحقاً.',
    'blocked_until' => Carbon::now()->addMinutes(30)
]

// Invalid OTP
[
    'success' => false,
    'message' => 'رمز التحقق غير صحيح.',
    'remaining_attempts' => 2
]

// Expired OTP
[
    'success' => false,
    'message' => 'انتهت صلاحية رمز التحقق أو لم يتم العثور عليه.'
]
bash
php artisan vendor:publish --provider="OneStudio\Otp\OtpServiceProvider" --tag="otp-config"
bash
php artisan vendor:publish --provider="OneStudio\Otp\OtpServiceProvider" --tag="otp-translations"
bash
php artisan vendor:publish --provider="OneStudio\Otp\OtpServiceProvider" --tag="otp-views"