Laravel OTP login with Fast2SMS Smart OTP (starter kit)

This guide shows you how to add a Laravel OTP login page to your app with Fast2SMS Smart OTP. Our starter kit is a set of drop-in files: a controller, routes, Blade views, a service provider and a small Fast2SMS client. You copy them into your Laravel 10, 11 or 12 project, add two lines to .env, and users can log in with their mobile number.

What you build

A login page that works like this:

  1. The user types a mobile number and clicks Send OTP. Fast2SMS creates the code and sends it.
  2. The user types the code and clicks Verify. Fast2SMS checks it, and your app logs the user in.
  3. A Resend code button works after a short wait (30 seconds by default).

The kit uses Smart OTP, our recommended way to send OTPs. An OTP template sends on SMS or WhatsApp, with optional fallback to the other channel, on a priority route. Fast2SMS creates, stores and checks the code, so your app does not keep any OTP itself.

Download the ready-made starter kit (zip)fast2sms-smart-otp-php-laravel.zip · 27 KBDownload .zip

The Fast2SMS client in this kit (app/Services/Fast2sms) passed all 23 tests with PHP 8.4.22 against a local mock of the Fast2SMS API. The controller, routes, provider and Blade views were syntax-checked and reviewed by hand, but not run inside a Laravel app. Try the login page on a test copy of your app before you go live.

Before you start

  • A Fast2SMS account with wallet balance. Every OTP you send is charged.
  • For SMS OTP: an approved DLT entity, sender ID and OTP content template in DLT Manager. For WhatsApp OTP: a connected WhatsApp number with an approved authentication (or utility) template.
  • A Laravel 10, 11 or 12 app on PHP 8.1 or newer, with the curl extension.

Set up Laravel OTP login in 5 steps

  1. Create a Smart OTP template

    In the panel, open Smart OTP > OTP Template List and click Add OTP Template. On the SMS Channel tab, pick your entity, sender and approved DLT OTP template, then click the variable button that holds the code and click Assign OTP Template. For WhatsApp, use the WhatsApp Channel tab. You can also tick SET FALLBACK TEMPLATE to add the other channel as a fallback.

    Add OTP Template window on the SMS Channel tab with entity, sender and DLT template selected and the variable buttons below the preview
    Pick the entity, sender and DLT template, then choose which variable holds the OTP.
  2. Copy the OTP ID

    Your new template shows as a card in the OTP Template List. Copy its OTP ID with the copy icon. It is 10 characters long, for example a1b2c3d4e5.

    Smart OTP Template list with WhatsApp and SMS template cards, each showing its OTP ID with a copy icon
    Each card shows the OTP ID you put in your .env file.
  3. Copy your API key

    In the left menu under Utility, click API Key. Click View to see the full Authorization Key (the panel asks for an OTP sent to your registered mobile first) and copy it. Check that API Access is switched on.

    API Key page with the masked Authorization Key, View and Reset buttons and the API Access switch turned on
    Copy the Authorization Key. API Access must be on.
  4. Add the kit files and your keys

    Copy the folders app, config, resources and routes from the kit into your project. They only add new files. Then:

    • Register the provider. Laravel 11 and 12: add App\Providers\Fast2smsServiceProvider::class, to bootstrap/providers.php. Laravel 10: add the same line to the providers array in config/app.php.
    • At the end of routes/web.php, add require __DIR__.'/otp.php';. It must be inside web.php so sessions and CSRF protection work.
    • Add these lines to your .env, then run php artisan config:clear.
    FAST2SMS_API_KEY=YOUR_API_KEY
    FAST2SMS_OTP_ID=a1b2c3d4e5
    OTP_RESEND_WAIT_SECONDS=30

    Never commit .env to git; make sure your .gitignore lists it.

  5. Run it and log in

    Start the app and open the login page:

    php artisan serve

    Go to http://127.0.0.1:8000/otp, type your own mobile number and click Send OTP. Type the code and click Verify. You should see the welcome page.

How send, verify and resend work in the Laravel kit

Step Your app calls Fast2SMS endpoint Charged?
Send $client->send($mobile, $otpId) POST /dev/otp/send Yes
Verify $client->verify($mobile, $code) POST /dev/otp/verify No
Resend $client->resendOrSend($mobile, $otpId) POST /dev/otp/resend, falls back to send Yes

The service provider registers SmartOtpClient as a singleton, so you can type-hint it anywhere in your app. Settings come from config/fast2sms.php, which reads .env. Never put the key in the config file itself.

Send

The kit first cleans the number, so +91 98765-43210 becomes 9876543210. Anything that is not a 10-digit Indian mobile starting with 6 to 9 is refused before any API call, so it costs nothing. Then it sends the mobile and your OTP ID. Fast2SMS makes a 6-digit code that is valid for 15 minutes, unless you pass otp_length (4 to 10) or otp_expiry (1 to 10080 minutes).

“OTP sent successfully” means Fast2SMS accepted the request. It does not mean the phone has received it. Delivery shows in Smart OTP > Delivery Report and in the OTP webhook.

Verify

Verify needs only the mobile and the code the user typed, no OTP ID. Fast2SMS checks the latest unverified code for that mobile. Sending a new OTP cancels the older codes, so only the newest one works. The result is one of verified, invalid (wrong code, one try used), expired, max_attempts or not_found.

This is the verify action from OtpLoginController.php. On success it regenerates the session:

$r = $this->client()->verify($mobile, $otp);
if (!$r->ok) {
    $request->session()->put('otp_need_new_code', in_array($r->reason, ['expired', 'max_attempts', 'not_found'], true));
    return $this->back('error', self::VERIFY_MESSAGES[$r->reason] ?? 'Could not check the code: ' . $r->message);
}
// Logged in. A new session id stops session fixation.
// In a real app, find or create the user here and call Auth::login($user).
$request->session()->regenerate();
$request->session()->forget(['otp_pending_mobile', 'otp_sent_at', 'otp_need_new_code']);
$request->session()->put('otp_user_mobile', $mobile);

Resend

Resend sends the same code again and is charged like a new send. It works only within 10 minutes of the last send, and Fast2SMS allows at most 5 sends to one number in those 10 minutes, counting the first. So a user gets up to 4 resends. When there is nothing to resend (never sent, already verified, or the 10 minutes are over), the kit sends a new code instead:

public function resendOrSend(string $mobile, string $otpId, array $options = []): Result
{
    $r = $this->resend($mobile);
    if (in_array($r->reason, ['no_previous', 'already_verified', 'window_expired'], true)) {
        $r = $this->send($mobile, $otpId, $options);
        $r->sentNew = true;
    }
    return $r;
}

The API key goes in the authorization header as the bare key. Do not add Bearer in front: the OTP API refuses it.

'authorization: ' . $this->apiKey, // bare key, no "Bearer ", never in the URL

The kit never retries a send or resend on its own, because a retry after a timeout could send, and charge, twice. It retries once, after 1 second, only when the connection could not be opened or Fast2SMS answered 502, 503 or 504 with an error page.

Security notes

Never expose the API key

  • Call Fast2SMS only from your server. Never put the API key in JavaScript, a mobile app or a page the browser can download.
  • Keep the key in .env or environment variables, out of git. If it ever leaks, click Reset on the API Key page; the old key stops working.
  • Turn on API Security and whitelist your server’s public IP, so a stolen key does not work from anywhere else.
  • The kit never writes the OTP or the full key to its logs. Mobiles are logged as 98xxxxxx10.

Rate limits

Every send costs money, so limit who can press Send OTP. There are three layers:

  • The kit’s wait: the Resend button works only after OTP_RESEND_WAIT_SECONDS (30 by default). Clicks before that make no API call.
  • Fast2SMS limits: the SMS Resend / Time Limit in OTP Settings (10 seconds if not set, 0 to 3600) and the fixed cap of 5 sends per number in 10 minutes.
  • Your own limit: add a limit per IP address or a CAPTCHA on the Send button. Bots that try many different numbers are not stopped by per-number limits.

In routes/otp.php, the two routes that cost money already have Laravel’s throttle, 10 requests per minute per IP. Tighten it if your login page gets bot traffic:

// Send and resend cost money: allow at most 10 per minute per IP address.
Route::middleware('throttle:10,1')->group(function () {
    Route::post('/send', [OtpLoginController::class, 'send'])->name('send');
    Route::post('/resend', [OtpLoginController::class, 'resend'])->name('resend');
});

Verify attempts

Set Max Verify OTP Limit (Per SMS) in Smart OTP > OTP Settings. It can be 1 to 100 and is 10 if you never set it; 3 to 5 suits most login pages. When the limit is reached, the code stops working and the kit shows “Too many wrong tries” with a Send new code button.

OTP Settings page with Max Verify OTP Limit set to 5 and SMS Resend Time Limit set to 30 seconds
Five tries per code and a 30-second wait between sends.
After “Too many wrong tries” or “This code has expired”, give the user a fresh code with $client->send($mobile, $otpId). Do not re-send the old code. In the kit, the Send new code button calls $client->resendOrSend($mobile, $otpId); for a stricter setup, change it to call send when the last verify ended in max_attempts.

Every send and every resend is charged at your OTP rate; verify is free. A fallback message on the second channel is also charged. See the current rates on the OTP SMS page.

Sending in bulk? For high OTP volumes our team offers discounted rates. Talk to our team or see OTP pricing.

Use HTTPS on the live site. After a correct code the kit starts a new session (or sign-in cookie), which stops session fixation, and every form carries a CSRF token.

OTP over DLT SMS: the second Laravel kit

Smart OTP is the easier choice. If you would rather send OTPs through your own approved DLT OTP template with the DLT SMS API, use our “OTP over DLT” kit for the same stack. It has the same login page, but the work is split differently:

  • Your app makes the code with a secure random generator and keeps only an HMAC-SHA256 hash of it, with the expiry time and a try counter. The code is never stored, logged or shown.
  • Fast2SMS only delivers the SMS. In dlt mode the kit calls /dev/bulkV2 with route=dlt, your sender ID and the template’s Message ID. In dlt_manual mode it calls /dev/custom with route=dlt_manual, your Entity ID, the 19-digit DLT Template ID and the full text.
  • Verify happens in your app with a constant-time compare. No API call, no charge.
  • Resend sends a new code and the old one stops working.

The two calls are $otp->sendOtp($mobile) and $otp->verifyOtp($mobile, $code) in app/Services/Fast2sms/OtpService.php. These are the DLT settings in its .env, next to the API key and an OTP_HASH_SECRET (a long random string; the app will not start without it):

# How to send: dlt (DLT SMS, default) or dlt_manual (DLT Manual).
OTP_SEND_MODE=dlt

# Your approved DLT sender ID, exactly as in DLT Manager (case matters).
FAST2SMS_SENDER_ID=FSTSMS

# DLT SMS: the "Message ID" from the template card in DLT Manager. NOT the 19-digit DLT Template ID.
FAST2SMS_DLT_MESSAGE_ID=111111
FAST2SMS_DLT_VARIABLES={otp}

# DLT Manual: the full approved DLT text, with {otp} where the code goes.
FAST2SMS_DLT_MANUAL_TEXT=Your OTP is {otp} for Login. -Demo
FAST2SMS_DLT_ENTITY_ID=1101234567890123456
FAST2SMS_DLT_TEMPLATE_ID=1107123456789012345
Rule Default Setting
Code length 6 digits (4 to 6 allowed) OTP_LENGTH
Code expires after 5 minutes OTP_EXPIRY_MINUTES
Wrong tries per code 5, then the code is deleted OTP_MAX_ATTEMPTS
Wait between sends to one number 30 seconds OTP_RESEND_WAIT_SECONDS
Sends per number per hour 5 OTP_MAX_SENDS_PER_HOUR
Use the Message ID from the template card in DLT Manager, not the 19-digit DLT Template ID. The sender ID is case-sensitive. In DLT Manual mode, Fast2SMS does not check your text against the template: if it does not match exactly, the SMS fails at the operator and is not refunded.

OTP records live in Laravel’s cache through CacheStore. Use a shared cache driver such as Redis or the database if you run more than one server. The client and OTP service passed 20 of 20 tests (plain PHP, with an in-memory store standing in for the cache). The controller, routes, provider and views were syntax-checked and reviewed, not run inside Laravel.

Download the OTP over DLT starter kit (zip)fast2sms-otp-dlt-php-laravel.zip · 31 KBDownload .zip

Common problems and fixes

What you see Why Fix
“SMS login is not set up correctly” and Invalid authorization key in the log Wrong key, or Bearer in front of it Copy the key again from API Key and send it bare.
Authorization Key Disabled (413) in the log API Access is off Switch on API Access on the API Key page.
IP is blacklisted (414) in the log API Security is on and your server IP is not listed Add the server’s public IP in API Security.
“Could not send the code: Invalid OTP ID” The OTP ID is wrong, deleted or from another account Copy it from OTP Template List, in the same account as the key.
“Please wait N seconds before asking for a new code.” Fast2SMS cooldown for this number Wait, or change the time in OTP Settings.
“Could not send the code: Insufficient wallet balance” Low balance Recharge with Add Amount.
“Maximum resend limit (5 times) reached” 5 sends to this number in 10 minutes Wait and try later.
“Could not reach the SMS service.” Network problem, or Fast2SMS was busy Try again in a minute.

Test without sending SMS

Each kit has a fake Fast2SMS server in its mock folder (it needs Python 3). It never sends an SMS, and with it the correct code is always 123456. Start it, then run the tests in a second terminal:

python mock/mock_fast2sms.py
FAST2SMS_BASE_URL=http://127.0.0.1:4010 php tests/run_tests.php

To click through the login page with the mock, set FAST2SMS_API_KEY=TEST_KEY_OK and FAST2SMS_BASE_URL=http://127.0.0.1:4010 in .env. Remove FAST2SMS_BASE_URL before you go live.

Frequently asked questions

Which Laravel versions does the kit support?

Laravel 10, 11 and 12 on PHP 8.1 or newer. It uses only standard Laravel features: sessions, CSRF, the throttle middleware, the cache and the log.

Does the kit replace Laravel’s own login?

No. It adds a separate page under /otp and stores the verified mobile in the session. Connect it to your users table by finding or creating the user after a correct code and calling Auth::login().

Is the starter kit free?

Yes. The kit is free under the MIT license. You pay only for the OTPs you send from your Fast2SMS wallet.

Can the same code send the OTP on WhatsApp?

Yes. The code only knows the OTP ID. If that OTP ID uses a WhatsApp authentication template, or has a WhatsApp fallback, Fast2SMS handles the channel and your code stays the same.

The page says the code was sent, but no SMS arrived. Why?

“OTP sent successfully” means Fast2SMS accepted the request. Check the status in Smart OTP > Delivery Report. If the message failed and you set a fallback, the same OTP goes out once on the other channel.

How many times can a user resend the OTP?

Up to 4 times: Fast2SMS allows 5 sends of one OTP ID to a number in 10 minutes, counting the first. The wait between sends comes from your OTP Settings and the kit’s 30-second Resend wait.