Quick answer
To use an OTP SMS API in PHP or Laravel, generate the code with random_int(), store only a hash of it with an expiry, and send it with one GET request to https://www.smsgatewayhub.com/api/mt/SendSMS (channel=OTP, route=1, plus your API key, DLT entity ID and template ID). In Laravel, put the keys in .env, wrap the call in an OtpService that uses the Http facade, keep the hashed code in the Cache with a 5-minute TTL, and protect the routes with RateLimiter. Verify on your own server with Hash::check(). OTP SMS costs ₹0.185 to ₹0.245 per SMS + 18% GST.
Key takeaways
- One HTTP call sends the OTP. No package is needed; Laravel's Http facade or plain PHP is enough.
- Secrets live in .env and config/services.php, never in Blade, JavaScript or the mobile app.
- Cache, not session: store the hashed code under a key per number with a TTL so it works across servers.
- RateLimiter blocks resend abuse; an attempt counter blocks brute force.
- Verification is yours: Hash::check(), then Cache::forget() so a code works once.
New to the API? Our earlier guide shows how to send OTP SMS from plain PHP and Python. This article goes further and builds a production-ready OTP login in Laravel. For every request parameter and the JSON reply, keep the OTP REST API reference open.
What do you need before you start?
- A free SMSGatewayHub account and API key. Sign up and get 1,000 free SMS credits, no credit card.
- A DLT entity ID, a transactional sender ID and an approved OTP template with the code in a variable. Our team helps with DLT registration free of cost.
- PHP 8.1+ and, for the Laravel part, Laravel 10 or 11 with a cache store (Redis recommended, file or database works for testing).
How do you send and verify an OTP in plain PHP?
If you are not on a framework, this is the smallest secure version. It uses the session for the stored hash.
<?php
session_start();
function send_otp(string $number): bool {
$otp = (string) random_int(100000, 999999);
$_SESSION['otp'] = ['n' => $number, 'hash' => password_hash($otp, PASSWORD_DEFAULT),
'exp' => time() + 300, 'tries' => 0];
$q = http_build_query([
'APIKey' => getenv('SGH_API_KEY'), 'senderid' => 'ABCDEF', 'channel' => 'OTP',
'DCS' => '0', 'flashsms' => '0', 'number' => $number, 'route' => '1',
'text' => "$otp is your OTP to log in to ABC App. Do not share it. - ABC",
'EntityId' => getenv('SGH_ENTITY_ID'), 'dlttemplateid' => getenv('SGH_OTP_TEMPLATE_ID'),
]);
$res = json_decode(file_get_contents("https://www.smsgatewayhub.com/api/mt/SendSMS?$q"), true);
return ($res['ErrorCode'] ?? '') === '000';
}
function verify_otp(string $number, string $code): bool {
$r = $_SESSION['otp'] ?? null;
if (!$r || $r['n'] !== $number || time() > $r['exp'] || $r['tries'] >= 5) { unset($_SESSION['otp']); return false; }
if (!password_verify($code, $r['hash'])) { $_SESSION['otp']['tries']++; return false; }
unset($_SESSION['otp']); // one use only
return true;
}
How do you set up the OTP SMS API in Laravel?
Step 1: add the keys to .env
SGH_API_KEY=your_api_key
SGH_SENDER_ID=ABCDEF
SGH_ENTITY_ID=your_dlt_entity_id
SGH_OTP_TEMPLATE_ID=your_dlt_template_id
Step 2: map them in config/services.php
'smsgatewayhub' => [
'key' => env('SGH_API_KEY'),
'sender' => env('SGH_SENDER_ID'),
'entity' => env('SGH_ENTITY_ID'),
'otp_template'=> env('SGH_OTP_TEMPLATE_ID'),
'url' => 'https://www.smsgatewayhub.com/api/mt/SendSMS',
],
Reading values through config() keeps them working after php artisan config:cache.
Step 3: create app/Services/OtpService.php
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class OtpService
{
private const TTL = 300; // seconds a code stays valid
private const MAX_TRIES = 5;
private function key(string $number): string { return 'otp:' . $number; }
public function send(string $number): bool
{
$otp = (string) random_int(100000, 999999);
Cache::put($this->key($number), ['hash' => Hash::make($otp), 'tries' => 0], self::TTL);
$c = config('services.smsgatewayhub');
$res = Http::timeout(10)->get($c['url'], [
'APIKey' => $c['key'],
'senderid' => $c['sender'],
'channel' => 'OTP',
'DCS' => '0',
'flashsms' => '0',
'number' => $number,
'text' => "{$otp} is your OTP to log in to ABC App. Do not share it. - ABC",
'route' => '1',
'EntityId' => $c['entity'],
'dlttemplateid' => $c['otp_template'],
]);
if ($res->json('ErrorCode') !== '000') {
Log::warning('OTP send failed', ['number' => $number, 'reply' => $res->json('ErrorMessage')]);
Cache::forget($this->key($number));
return false;
}
Log::info('OTP sent', ['number' => $number, 'job' => $res->json('JobId')]);
return true;
}
public function verify(string $number, string $code): bool
{
$rec = Cache::get($this->key($number));
if (!$rec || $rec['tries'] >= self::MAX_TRIES) { Cache::forget($this->key($number)); return false; }
if (!Hash::check($code, $rec['hash'])) {
$rec['tries']++;
Cache::put($this->key($number), $rec, self::TTL); // simple: TTL restarts on a miss
return false;
}
Cache::forget($this->key($number)); // one use only
return true;
}
}
The text must match your DLT template exactly. Only the code changes. If your approved template says "valid for 5 minutes", put that phrase in the text too.
Step 4: create app/Http/Controllers/OtpController.php
<?php
namespace App\Http\Controllers;
use App\Services\OtpService;
use Illuminate\Http\Request;
class OtpController extends Controller
{
public function __construct(private OtpService $otp) {}
public function send(Request $request)
{
$data = $request->validate(['number' => ['required', 'regex:/^91[6-9]\d{9}$/']]);
if (!$this->otp->send($data['number'])) {
return response()->json(['message' => 'Could not send the code. Please try again.'], 502);
}
return response()->json(['message' => 'Code sent']);
}
public function verify(Request $request)
{
$data = $request->validate([
'number' => ['required', 'regex:/^91[6-9]\d{9}$/'],
'otp' => ['required', 'digits:6'],
]);
if (!$this->otp->verify($data['number'], $data['otp'])) {
return response()->json(['message' => 'Wrong or expired code'], 422);
}
// log the user in or mark the number verified here
return response()->json(['message' => 'Verified']);
}
}
Step 5: add rate limits and routes
Define the limiters in AppServiceProvider::boot() (Laravel 11) or RouteServiceProvider (Laravel 10):
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Http\Request;
RateLimiter::for('otp-send', function (Request $request) {
$number = (string) $request->input('number');
return [
Limit::perMinute(1)->by('otp-n:' . $number), // cooldown per number
Limit::perHour(5)->by('otp-h:' . $number), // cap per number
Limit::perHour(20)->by('otp-ip:' . $request->ip()),
];
});
RateLimiter::for('otp-verify', fn (Request $r) => Limit::perMinute(10)->by($r->ip()));
// routes/api.php
use App\Http\Controllers\OtpController;
Route::post('/otp/send', [OtpController::class, 'send'])->middleware('throttle:otp-send');
Route::post('/otp/verify', [OtpController::class, 'verify'])->middleware('throttle:otp-verify');
A user who presses "Resend code" just calls /otp/send again. The new code replaces the old one in the cache, so the old code stops working at once. The limiter returns HTTP 429 if they try too soon. More on resend rules in our guide to verify and resend OTP securely.
ℹ️Use a shared cache store such as Redis in production. With the file driver on several servers, a code stored by one server cannot be checked by another.
How do you test the Laravel OTP flow?
Laravel's Http::fake() lets you test without sending a real SMS:
use Illuminate\Support\Facades\Http;
public function test_send_otp(): void
{
Http::fake(['www.smsgatewayhub.com/*' => Http::response(
['ErrorCode' => '000', 'ErrorMessage' => 'Success', 'JobId' => '1', 'MessageData' => []], 200)]);
$this->postJson('/api/otp/send', ['number' => '919812345678'])->assertOk();
Http::assertSent(fn ($req) => $req['channel'] === 'OTP' && $req['route'] === '1');
}
When the fake tests pass, send one real OTP to your own phone using your free credits and check the status in the panel's delivery report. Our OTP API testing guide covers Postman checks too.
What errors do PHP developers hit most often?
| Symptom | Likely cause | Fix |
| ErrorCode is not "000" | Wrong key, sender ID, template or text | Read ErrorMessage; check the text matches the DLT template word for word. |
| Accepted but the SMS never arrives | Template mismatch caught at DLT scrubbing, or an invalid number | Check the delivery report in the panel for the reason. |
| Comparison fails with the right code | Comparing ErrorCode or OTP as integers | Compare ErrorCode as the string "000"; keep the OTP a string so a leading zero is not lost. |
| Verify fails on a second server | File cache or session not shared | Use Redis or a database cache store. |
| Config values are null in production | Calling env() outside config files after config:cache | Read values with config('services.smsgatewayhub'). |
Why use SMSGatewayHub for OTP in PHP apps?
- 2-6 second typical delivery on priority transactional routes that reach DND numbers 24x7.
- Automatic retry with load balancing across operator routes, plus a 99.9% uptime SLA.
- Pay only for delivered OTPs: ₹0.185 to ₹0.245 per SMS + 18% GST, DLT scrubbing included. See OTP SMS pricing.
- Free DLT help to register your entity, sender ID and OTP template.
- Fallback channels from one account: WhatsApp OTP, voice OTP, missed call and OneTap Verify links.
- ISO 27001 certified, trusted by businesses since 2009.
Get your API key and 1,000 free SMS credits
No credit card. Free DLT registration help. Ship OTP login in Laravel today.
Create free account
Frequently asked questions
Do I need a Composer package to send OTP SMS from Laravel?
No. The OTP SMS API is a single HTTPS GET request, so Laravel's built-in Http facade is enough. Plain PHP can use file_get_contents or cURL.
Where should I store the OTP in Laravel?
Store a hash of the code in the Cache, keyed by the mobile number, with a TTL of about 5 minutes and an attempt counter. Use Redis in production so every server sees the same record.
How do I limit OTP resends in Laravel?
Define a RateLimiter with one send per minute and about five per hour per number, plus a per-IP limit, and attach it to the send route with the throttle middleware.
Does SMSGatewayHub verify the OTP for my PHP app?
No. Your PHP or Laravel code checks the code with password_verify or Hash::check and then deletes it. The API only delivers the code, which keeps it inside your system.
How much does each OTP cost?
OTP SMS costs ₹0.185 to ₹0.245 per SMS plus 18% GST depending on pack size, with DLT scrubbing included. You pay only for delivered SMS, and new accounts get 1,000 free credits.
Related reading: send OTP SMS via HTTP API in PHP and Python, OTP REST API reference, OTP SMS API in Python, and OTP SMS API.
Sources: SMSGatewayHub OTP SMS API page and developer API documentation (November 2026); Laravel documentation for the HTTP client, cache, hashing and rate limiting; TRAI DLT rules for transactional templates. Prices exclude 18% GST and can change; confirm your rate with sales before purchase.