<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Tekservix Developer Blog]]></title><description><![CDATA[Tekservix Developer Blog]]></description><link>https://tekservix.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6aec648042daf12ef7d43605/271787c7-099b-4cbb-a64b-9ac3f11c3d09.png</url><title>Tekservix Developer Blog</title><link>https://tekservix.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 21:15:40 GMT</lastBuildDate><atom:link href="https://tekservix.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[OTP Verification in Laravel With the SMS Gora SMS Gateway and a WAservix WhatsApp API Fallback]]></title><description><![CDATA[Build secure OTP verification in Laravel: SMS via the SMS Gora SMS Gateway with a WAservix WhatsApp API fallback, hashed codes and rate limits.]]></description><link>https://tekservix.hashnode.dev/otp-verification-in-laravel-with-the-sms-gora-sms-gateway-and-a-waservix-whatsapp-api-fallback</link><guid isPermaLink="true">https://tekservix.hashnode.dev/otp-verification-in-laravel-with-the-sms-gora-sms-gateway-and-a-waservix-whatsapp-api-fallback</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[whatsapp]]></category><category><![CDATA[sms]]></category><category><![CDATA[sms gateway]]></category><category><![CDATA[OTP]]></category><dc:creator><![CDATA[Tekservix]]></dc:creator><pubDate>Thu, 05 Nov 2026 11:31:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aec648042daf12ef7d43605/eb4df3f2-1b44-4166-9943-0ff6fb74b9a8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Phone verification is one of those features that looks like ten lines of code and turns into a week of edge cases: codes that never arrive, users who tap "resend" five times, bots hammering your endpoint, and an SMS bill that grows faster than your sign-ups.</p>
<p>In this guide we'll build OTP (one-time password) verification in Laravel that sends the code by SMS through the <a href="https://tekservix.com/smsgora"><strong>SMS Gora SMS Gateway</strong></a>, and lets the user switch to WhatsApp through the <a href="https://tekservix.com/waservix"><strong>WAservix WhatsApp API</strong></a> when the SMS doesn't arrive. Both send from numbers you own: SMS Gora through your own Android phones and SIM cards, WAservix from your own WhatsApp number.</p>
<blockquote>
<p><strong>Disclosure:</strong> this post is published by Tekservix, the company behind WAservix and SMS Gora. The API calls match our public docs; the OTP logic works with any provider.</p>
</blockquote>
<h2>What we're building</h2>
<ul>
<li><code>POST /api/otp/send</code> creates a 6-digit code and sends it by SMS (or WhatsApp if the user asks)</li>
<li><code>POST /api/otp/verify</code> checks the code</li>
<li>Codes are <strong>hashed</strong>, expire after <strong>5 minutes</strong>, allow <strong>5 attempts</strong>, and each phone can request <strong>3 codes per 10 minutes</strong></li>
<li>A new code always replaces the old one, so "resend" never leaves two valid codes around</li>
</ul>
<p>Requirements: Laravel 10+ and any cache driver (Redis recommended in production). No extra packages: we use Laravel's built-in HTTP client.</p>
<h2>1. Keys and config</h2>
<p>Create an API key in the SMS Gora dashboard (starts with <code>sgk_</code>) and one in WAservix (starts with <code>wpk_</code>). They stay on the server, never in your frontend or mobile app.</p>
<pre><code class="language-bash"># .env
SMSGORA_KEY=sgk_your_key
WASERVIX_KEY=wpk_your_key
</code></pre>
<pre><code class="language-php">// config/services.php
'smsgora' =&gt; ['key' =&gt; env('SMSGORA_KEY')],
'waservix' =&gt; ['key' =&gt; env('WASERVIX_KEY')],
</code></pre>
<h2>2. The OTP service</h2>
<pre><code class="language-php">&lt;?php
// app/Services/OtpService.php
namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;

class OtpService
{
    private const TTL_MINUTES = 5;
    private const MAX_TRIES = 5;

    public function send(string $phone, string $channel = 'sms'): void
    {
        $limiter = 'otp-send:' . $phone;
        if (RateLimiter::tooManyAttempts($limiter, 3)) {
            abort(429, 'Too many codes requested. Please wait a few minutes.');
        }
        RateLimiter::hit($limiter, 600); // 3 codes per 10 minutes per phone

        $code = (string) random_int(100000, 999999);
        $expiresAt = now()-&gt;addMinutes(self::TTL_MINUTES);

        // Store only a hash. A new code overwrites the previous one.
        Cache::put($this-&gt;key($phone), [
            'hash' =&gt; Hash::make($code),
            'tries' =&gt; 0,
            'exp' =&gt; $expiresAt-&gt;getTimestamp(),
        ], $expiresAt);

        $text = "Your verification code is {$code}. It expires in " . self::TTL_MINUTES . " minutes. Never share it.";

        $channel === 'whatsapp'
            ? $this-&gt;viaWhatsApp($phone, $text)
            : $this-&gt;viaSms($phone, $text);
    }

    public function verify(string $phone, string $code): bool
    {
        $otp = Cache::get($this-&gt;key($phone));
        if (! $otp || $otp['tries'] &gt;= self::MAX_TRIES) {
            return false;
        }

        if (! Hash::check($code, $otp['hash'])) {
            $otp['tries']++;
            Cache::put($this-&gt;key($phone), $otp, now()-&gt;setTimestamp($otp['exp']));
            return false;
        }

        Cache::forget($this-&gt;key($phone)); // one-time: a used code is gone
        return true;
    }

    private function viaSms(string $phone, string $text): void
    {
        // SMS Gora SMS Gateway: picks your best online phone
        Http::withHeaders(['x-api-key' =&gt; config('services.smsgora.key')])
            -&gt;timeout(30)
            -&gt;post('https://tekservix.com/smsgora/api/v1/send-sms', [
                'recipients' =&gt; [$phone],
                'message' =&gt; $text,
            ])
            -&gt;throw();
    }

    private function viaWhatsApp(string $phone, string $text): void
    {
        // WAservix WhatsApp API: sends from your own WhatsApp number
        Http::withToken(config('services.waservix.key'))
            -&gt;timeout(30)
            -&gt;post('https://tekservix.com/waservix/api/send-message', [
                'to' =&gt; $phone,
                'text' =&gt; $text,
            ])
            -&gt;throw();
    }

    private function key(string $phone): string
    {
        return 'otp:' . hash('sha256', $phone);
    }
}
</code></pre>
<p>A few choices worth calling out:</p>
<ul>
<li><code>random_int</code><strong>, not</strong> <code>rand</code><strong>.</strong> <code>random_int</code> is cryptographically secure; <code>rand()</code> and <code>mt_rand()</code> are predictable.</li>
<li><strong>Hash the code.</strong> If your cache is ever dumped or logged, plain codes would be usable. <code>Hash::make</code> makes them worthless to an attacker.</li>
<li><strong>The expiry survives failed attempts.</strong> We store <code>exp</code> and reuse it, so wrong guesses don't extend the code's lifetime.</li>
<li><strong>No automatic retry on send.</strong> If the request times out, the SMS may still have gone out. Retrying blindly could deliver two codes, and the first would already be invalid. Let the user tap "resend" instead, which issues a fresh code.</li>
<li><strong>Never log the code</strong>, and don't return it in the API response, not even in development builds that might reach production.</li>
</ul>
<h2>3. Routes</h2>
<pre><code class="language-php">&lt;?php
// routes/api.php
use App\Services\OtpService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('throttle:10,1')-&gt;group(function () {
    Route::post('/otp/send', function (Request $request, OtpService $otp) {
        $data = $request-&gt;validate([
            'phone' =&gt; ['required', 'regex:/^\+[1-9]\d{7,14}$/'], // E.164, e.g. +447700900123
            'channel' =&gt; ['nullable', 'in:sms,whatsapp'],
        ]);

        $otp-&gt;send($data['phone'], $data['channel'] ?? 'sms');

        return response()-&gt;json(['sent' =&gt; true]);
    });

    Route::post('/otp/verify', function (Request $request, OtpService $otp) {
        $data = $request-&gt;validate([
            'phone' =&gt; ['required', 'regex:/^\+[1-9]\d{7,14}$/'],
            'code' =&gt; ['required', 'digits:6'],
        ]);

        abort_unless($otp-&gt;verify($data['phone'], $data['code']), 422, 'Invalid or expired code.');

        // Mark the phone as verified or sign the user in here.
        return response()-&gt;json(['verified' =&gt; true]);
    });
});
</code></pre>
<p><code>throttle:10,1</code> limits each IP to 10 requests a minute on top of the per-phone limit inside the service. Both matter: the IP limit slows down bots, the phone limit stops someone from flooding one victim's phone from many IPs.</p>
<h2>4. The WhatsApp fallback in the UI</h2>
<p>SMS delivery depends on the recipient's operator, signal and phone. Instead of silently sending through both channels (which doubles cost and confuses people), give the user the choice:</p>
<ol>
<li>Send by SMS first.</li>
<li>After 30 seconds, show <strong>"Didn't get it? Send via WhatsApp"</strong>.</li>
<li>That button calls <code>/api/otp/send</code> with <code>"channel": "whatsapp"</code>. The new code replaces the SMS one.</li>
</ol>
<pre><code class="language-javascript">async function sendCode(phone, channel = 'sms') {
  const res = await fetch('/api/otp/send', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
    body: JSON.stringify({ phone, channel }),
  });
  if (res.status === 429) throw new Error('Too many codes requested, please wait a few minutes.');
  if (!res.ok) throw new Error('Could not send the code.');
}
</code></pre>
<p>Many users read WhatsApp before SMS anyway, so some teams flip the order and offer SMS as the fallback. With both APIs behind the same service, that's a one-line change.</p>
<h2>5. Production checklist</h2>
<ul>
<li><input disabled type="checkbox" /> Redis (or another shared cache) so codes work across servers</li>
<li><input disabled type="checkbox" /> Per-phone and per-IP limits, as above</li>
<li><input disabled type="checkbox" /> Codes hashed, single-use, 5-minute expiry, 5 attempts</li>
<li><input disabled type="checkbox" /> Keys only in <code>.env</code>, never in JavaScript or a mobile app</li>
<li><input disabled type="checkbox" /> No codes in logs or error trackers</li>
<li><input disabled type="checkbox" /> Handle <code>429</code> from the messaging APIs too: they allow 300 requests a minute per key and send a <code>Retry-After</code> header</li>
<li><input disabled type="checkbox" /> Only message people who asked for a code</li>
</ul>
<h2>Why SMS Gora and WAservix for OTPs</h2>
<ul>
<li><strong>Your own sender.</strong> Codes come from your SIM cards (SMS Gora SMS Gateway) or your WhatsApp number (WAservix WhatsApp API), not an unknown short code.</li>
<li><strong>Predictable cost.</strong> A flat monthly plan, with SMS billed by your own operator like any text.</li>
<li><strong>Choose the SIM.</strong> Dual-SIM phone? Send OTPs from the SIM on the recipient's network with <code>devices/{id}/send-sms</code> and <code>sim_slot</code>.</li>
<li><strong>Same pattern in every stack.</strong> Guides exist for Laravel, PHP, Node.js, Python, Django, Java, Spring Boot, .NET, Go, Ruby on Rails and WordPress: <a href="https://tekservix.com/smsgora/docs/">SMS Gora SMS Gateway docs</a> · <a href="https://tekservix.com/waservix/docs">WAservix WhatsApp API docs</a>.</li>
</ul>
<p>Both have a 3-day free trial with no card on <a href="https://tekservix.com/pricing">tekservix.com</a>. If you're also building a mobile app for this, <a href="https://tekservix.com/mobile-apps">App Studio</a> turns a website into iOS and Android apps, and the <a href="https://tekservix.com/ai-sales-agent">AI Sales Agent</a> can take over the conversation after the customer verifies.</p>
<hr />
<p>How do you handle OTP delivery failures today: automatic fallback, user choice, or voice calls? I'd like to hear what works for you in the comments.</p>
]]></content:encoded></item></channel></rss>