💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging 💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging
Talk to Sales: India 1800 102 1822
OTP

Verify OTP and Resend OTP: The Secure Server-Side Flow (with Code)

SMSGatewayHub 7 views
Quick answer

To verify an OTP, your own server compares the code the user types with a hashed copy it stored when the OTP was sent, checks that it has not expired, counts wrong attempts and deletes the code after one successful use. To resend an OTP, your server creates a new code and sends it through the same SendSMS call, after a cooldown of 30-60 seconds and within a per-number limit. With the SMSGatewayHub OTP SMS API there is no separate hosted verify endpoint: the API delivers the code, and verification stays inside your system, which is the safer design.

Key takeaways

  • Verify on your server: hash the code, set an expiry of 3-10 minutes, allow about 5 attempts, delete on success.
  • Resend = new code: never resend the old one. Invalidate it and send a fresh code with the same SendSMS request.
  • Cooldown and caps: 30-60 seconds between sends and a few sends per number per hour stop SMS pumping and brute force.
  • We retry for you: automatic retry with load balancing across operator routes, so you do not need aggressive resends.
  • Switch channel, not just retry: after two failed SMS attempts, offer WhatsApp, voice or missed call verification.

Who verifies the OTP: the API or your server?

Your server. Some providers offer a "verify" endpoint where they store the code for you. We do not, on purpose. When your server generates and checks the code, the OTP never travels to a third party for checking, you control expiry and attempt rules, and one provider outage cannot block logins that are already in progress.

The OTP SMS API does one job well: it delivers the code on a priority transactional route in 2-6 seconds typical, reaches DND numbers 24x7 and gives you a delivery report for every message. The request format is in our OTP REST API reference.

What does a secure verify OTP flow look like?

  1. Request. The user enters a mobile number. Your server validates the format and checks resend limits.
  2. Generate. Create a random 6-digit code with a cryptographic random function.
  3. Store. Save a hash of the code, the expiry time, an attempt counter and the send time, keyed by the number (or a request ID).
  4. Send. Call SendSMS with channel=OTP. Save the JobId for the delivery report.
  5. Verify. When the user submits a code, load the record, reject if expired or locked, compare hashes in constant time, add one to the attempt count on a miss.
  6. Consume. On a match, delete the record and mark the number verified. A code can never be used twice.
RuleRecommended valueWhy
Code length6 digits1 in a million guess chance per try; easy to type.
Expiry3-10 minutes (say it in the SMS)Short life limits the value of a stolen code.
Wrong attempts5, then lock the codeStops brute force on the 6 digits.
Resend cooldown30-60 secondsGives the first SMS time to arrive (typical 2-6 seconds).
Sends per number3-5 per hourStops SMS pumping fraud and bill shock.
StorageHash only (bcrypt/argon2 or HMAC)A database leak does not reveal live codes.

How do you build the verify OTP endpoint? (PHP)

This example uses the PHP session for clarity. In production, store the record in Redis or a database table keyed by the mobile number, so it works across servers.

<?php
// send-otp.php : called by your app with the user's number
session_start();
$number = preg_replace('/\D/', '', $_POST['number'] ?? '');
if (!preg_match('/^91[6-9]\d{9}$/', $number)) { http_response_code(422); exit('Invalid number'); }

$now = time();
$rec = $_SESSION['otp'][$number] ?? null;
if ($rec && $now - $rec['sent_at'] < 45) { http_response_code(429); exit('Please wait before resending'); }

$otp = (string) random_int(100000, 999999);
$_SESSION['otp'][$number] = [
  'hash' => password_hash($otp, PASSWORD_DEFAULT),
  'exp' => $now + 300, 'tries' => 0, 'sent_at' => $now,
];

$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);
if (($res['ErrorCode'] ?? '') !== '000') { error_log('OTP send: ' . ($res['ErrorMessage'] ?? 'no reply')); http_response_code(502); exit('Could not send the code'); }
echo 'sent';
<?php
// verify-otp.php : the user submits the code
session_start();
$number = preg_replace('/\D/', '', $_POST['number'] ?? '');
$code   = preg_replace('/\D/', '', $_POST['otp'] ?? '');
$rec = $_SESSION['otp'][$number] ?? null;

if (!$rec || time() > $rec['exp']) { unset($_SESSION['otp'][$number]); exit('Code expired, request a new one'); }
if ($rec['tries'] >= 5) { unset($_SESSION['otp'][$number]); exit('Too many attempts, request a new code'); }

if (password_verify($code, $rec['hash'])) {
  unset($_SESSION['otp'][$number]);        // one use only
  $_SESSION['verified_number'] = $number;
  echo 'verified';
} else {
  $_SESSION['otp'][$number]['tries']++;
  echo 'Wrong code';
}

How do you build the verify OTP endpoint? (Node.js)

The same flow in Express, with an in-memory Map for the demo. Swap the Map for Redis with a TTL in production.

const crypto = require('crypto');
const express = require('express');
const app = express(); app.use(express.json());
const store = new Map();                        // number -> { hash, exp, tries, sentAt }
const sha = s => crypto.createHmac('sha256', process.env.OTP_SECRET).update(s).digest('hex');

app.post('/otp/send', async (req, res) => {
  const number = String(req.body.number || '').replace(/\D/g, '');
  if (!/^91[6-9]\d{9}$/.test(number)) return res.status(422).send('Invalid number');
  const rec = store.get(number), now = Date.now();
  if (rec && now - rec.sentAt < 45000) return res.status(429).send('Please wait before resending');
  const otp = String(crypto.randomInt(100000, 1000000));
  store.set(number, { hash: sha(otp), exp: now + 300000, tries: 0, sentAt: now });
  const p = new URLSearchParams({ APIKey: process.env.SGH_API_KEY, senderid: 'ABCDEF', channel: 'OTP',
    DCS: '0', flashsms: '0', number, route: '1',
    text: `${otp} is your OTP to log in to ABC App. Do not share it. - ABC`,
    EntityId: process.env.SGH_ENTITY_ID, dlttemplateid: process.env.SGH_OTP_TEMPLATE_ID });
  const data = await (await fetch(`https://www.smsgatewayhub.com/api/mt/SendSMS?${p}`)).json();
  if (data.ErrorCode !== '000') return res.status(502).send('Could not send the code');
  res.send('sent');
});

app.post('/otp/verify', (req, res) => {
  const number = String(req.body.number || '').replace(/\D/g, '');
  const rec = store.get(number);
  if (!rec || Date.now() > rec.exp) { store.delete(number); return res.status(400).send('Code expired'); }
  if (rec.tries >= 5) { store.delete(number); return res.status(429).send('Too many attempts'); }
  const ok = crypto.timingSafeEqual(Buffer.from(rec.hash), Buffer.from(sha(String(req.body.otp || ''))));
  if (!ok) { rec.tries++; return res.status(400).send('Wrong code'); }
  store.delete(number);                         // one use only
  res.send('verified');
});
ℹ️
Keep the API key, entity ID and template ID in environment variables on the server. Your app or website never sees them, and never sees the code itself except in the SMS.

How should a resend OTP API work?

A resend is simply a new send. In the code above, calling /otp/send again replaces the old record, so the old code stops working the moment a new one goes out. Add three rules around it:

  • Cooldown. Show a countdown of 30-60 seconds before the "Resend code" button becomes active. Most OTPs arrive in 2-6 seconds, so a user who waits rarely needs a resend at all.
  • Cap. Allow 3-5 sends per number per hour and a daily limit per IP address. This blocks SMS pumping, where bots trigger thousands of OTPs to premium numbers to run up your bill.
  • Escalate. On the second or third attempt, offer another channel instead of another SMS.

You do not need to resend because of a temporary operator problem. The platform already applies automatic retry with load balancing across operator routes. A resend should be the user's choice, not a reflex of your code.

When should you switch from SMS to another channel?

Some users are on weak networks, have full inboxes or use a number that cannot receive SMS. If two SMS codes do not get verified, offer one of these from the same account:

ChannelBest for
WhatsApp OTPUsers on Wi-Fi or with patchy SMS, copy-code button
Voice OTPLandlines, feature phones, users who cannot read SMS
Missed call verificationProving number ownership with no code typed
OneTap VerifyPasswordless login links: the user taps instead of typing

How do you stop OTP fraud and SMS pumping?

  • Rate-limit by number, IP and device on the send endpoint, not only on verify.
  • Add a CAPTCHA or a proof-of-work check before the first send on public sign-up forms.
  • Allow only the countries you serve. For an India-only app, reject anything that is not a valid +91 mobile number.
  • Watch your send-to-verify ratio. If many codes go out and few are verified, something is abusing the form.
  • Never reveal whether a number is registered in the error text of the send endpoint.
  • Log JobIds and compare them with delivery reports in the panel to spot failures by operator or region.

What does each verification attempt cost?

Each OTP SMS costs ₹0.185 to ₹0.245 + 18% GST by pack size, DLT scrubbing included, and you pay only for delivered SMS. Good resend rules matter for cost too: a cooldown and a cap mean you pay for codes people use, not for codes bots trigger. See OTP SMS pricing.

✔
Building in a specific language? Full send and verify code: PHP and Laravel, Python, Node.js and React, Java and Android, .NET, Flutter and iOS.
Start with 1,000 free SMS credits
No credit card. Free DLT registration help. Test send, verify and resend today.
Create free account

Frequently asked questions

Is there a hosted verify OTP API?

No. With SMSGatewayHub your server generates the code, stores a hash with an expiry and checks the code the user enters. The OTP SMS API delivers the code. This keeps the OTP inside your own system.

How do I resend an OTP?

Generate a new code, replace the stored hash so the old code stops working, and call the same SendSMS request again. Apply a 30-60 second cooldown and a limit of a few sends per number per hour.

How long should an OTP be valid?

Between 3 and 10 minutes. Say the validity in the SMS text, and lock the code after about 5 wrong attempts.

Should I store the OTP in my database?

Store only a hash of the code, never the plain code, together with the expiry time and an attempt counter. Delete the record as soon as the code is verified.

What if the user still does not get the OTP?

The platform already retries automatically with load balancing across operator routes. If two SMS codes are not verified, offer WhatsApp OTP, voice OTP or missed call verification from the same account.

Related reading: OTP REST API reference, OTP SMS not received: common reasons, test your OTP API with Postman, and OTP SMS API.

Sources: SMSGatewayHub OTP SMS API page and developer API documentation (November 2026); OWASP guidance on authentication, rate limiting and brute-force protection; TRAI DLT rules for transactional templates. Prices exclude 18% GST and can change; confirm your rate with sales before purchase.