Quick answer
To add phone-number login with an OTP SMS API in Flutter or iOS, the app never calls the SMS API directly. The app sends the mobile number to your backend, your backend generates the code and sends it through the SMSGatewayHub SendSMS endpoint, and the app later posts the typed code back to your backend for verification. On iOS, set the field's content type to .oneTimeCode so the keyboard offers the code from Messages; on Android, the SMS Retriever API fills it automatically. OTP SMS costs ₹0.185 to ₹0.245 per SMS + 18% GST, with typical delivery in 2-6 seconds.
Key takeaways
- Never ship the API key in the app. Anyone can unpack an APK or IPA and read it. All SendSMS calls happen on your server.
- Two backend endpoints are enough:
/otp/send and /otp/verify. The app only talks to these.
- Autofill saves sign-ups: iOS reads the code from Messages with
.oneTimeCode; Android uses the SMS Retriever API with an app hash.
- Write the SMS so autofill can find the code: put the digits early and clearly, for example "482913 is your OTP to log in to ABC App."
How does phone login work in a mobile app?
The same flow works for Flutter, native iOS, native Android and React Native. Only the screens differ.
| Step | Where it runs | What happens |
| 1. Enter number | App | User types the mobile number; the app calls POST /otp/send on your backend. |
| 2. Generate code | Your backend | Random 6-digit code, stored as a hash with a 5-minute expiry and an attempt counter. |
| 3. Send SMS | Your backend to SMSGatewayHub | One HTTPS GET to SendSMS with channel=OTP, DLT entity ID and template ID. |
| 4. Deliver | Operator | Transactional OTP route, 2-6 seconds typical, with automatic retry across operator routes. |
| 5. Autofill or type | App | iOS suggests the code above the keyboard; Android SMS Retriever passes it to the app. |
| 6. Verify | Your backend | App posts number + code to POST /otp/verify; backend compares hashes and returns a session token. |
What does the backend call to the OTP SMS API look like?
Your backend can be in any language. This is the request it sends; the full code for PHP, Python, Node.js, Java and .NET is in our language guides linked at the end.
GET https://www.smsgatewayhub.com/api/mt/SendSMS
?APIKey=YOUR_API_KEY&senderid=ABCDEF&channel=OTP&DCS=0&flashsms=0
&number=9198XXXXXXXX&route=1
&text=482913%20is%20your%20OTP%20to%20log%20in%20to%20ABC%20App.%20Do%20not%20share%20it.%20-%20ABC
&EntityId=YOUR_ENTITY_ID&dlttemplateid=YOUR_TEMPLATE_ID
Response:
{ "ErrorCode": "000", "ErrorMessage": "Success", "JobId": "20047",
"MessageData": [ { "Number": "9198XXXXXXXX", "MessageId": "..." } ] }
"000" means the OTP was accepted. Keep the JobId so you can check the live delivery reports if a user says the code never came. See the OTP SMS API page for parameters and pricing.
How do you build the OTP screen in Flutter?
Use the http package to call your own backend. The service class below has the two calls the app needs. Replace the base URL with your API.
import 'dart:convert';
import 'package:http/http.dart' as http;
class OtpApi {
static const _base = 'https://api.yourapp.com'; // YOUR backend, never the SMS API
static Future<bool> send(String phone) async {
final r = await http.post(Uri.parse('$_base/otp/send'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'phone': phone}));
return r.statusCode == 200;
}
static Future<String?> verify(String phone, String code) async {
final r = await http.post(Uri.parse('$_base/otp/verify'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'phone': phone, 'code': code}));
if (r.statusCode != 200) return null;
final data = jsonDecode(r.body) as Map<String, dynamic>;
return data['verified'] == true ? data['token'] as String? : null;
}
}
The screen needs a 6-digit field and a resend button that unlocks after 30 seconds:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class OtpScreen extends StatefulWidget {
final String phone;
const OtpScreen({super.key, required this.phone});
@override
State<OtpScreen> createState() => _OtpScreenState();
}
class _OtpScreenState extends State<OtpScreen> {
final _code = TextEditingController();
int _wait = 30;
Timer? _t;
@override
void initState() { super.initState(); _startTimer(); }
void _startTimer() {
_wait = 30;
_t?.cancel();
_t = Timer.periodic(const Duration(seconds: 1), (t) {
if (_wait == 0) { t.cancel(); } else { setState(() => _wait--); }
});
}
Future<void> _verify() async {
final token = await OtpApi.verify(widget.phone, _code.text);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(token != null ? 'Logged in' : 'Wrong or expired code')));
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Enter OTP')),
body: Padding(padding: const EdgeInsets.all(24), child: Column(children: [
TextField(
controller: _code, maxLength: 6, keyboardType: TextInputType.number,
autofillHints: const [AutofillHints.oneTimeCode],
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (v) { if (v.length == 6) _verify(); },
),
TextButton(
onPressed: _wait > 0 ? null : () async { await OtpApi.send(widget.phone); setState(_startTimer); },
child: Text(_wait > 0 ? 'Resend in $_wait s' : 'Resend OTP'),
),
])),
);
@override
void dispose() { _t?.cancel(); _code.dispose(); super.dispose(); }
}
ℹ️AutofillHints.oneTimeCode lets iOS offer the code from Messages above the keyboard in a Flutter app. On Android, add an SMS Retriever plugin (or a small platform channel) to read the code without the SMS permission. The Android side, including the app hash, is explained in our
Java and Android OTP guide.
How do you add OTP autofill in a native iOS app?
iOS does not need any permission to read the code. It looks at incoming messages and suggests the code when the focused field is marked as a one-time code field.
// UIKit
let codeField = UITextField()
codeField.keyboardType = .numberPad
codeField.textContentType = .oneTimeCode
// SwiftUI
TextField("6-digit code", text: $code)
.keyboardType(.numberPad)
.textContentType(.oneTimeCode)
Calling your backend with URLSession:
struct VerifyReply: Decodable { let verified: Bool; let token: String? }
func verifyOtp(phone: String, code: String) async throws -> String? {
var req = URLRequest(url: URL(string: "https://api.yourapp.com/otp/verify")!)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try JSONEncoder().encode(["phone": phone, "code": code])
let (data, resp) = try await URLSession.shared.data(for: req)
guard (resp as? HTTPURLResponse)?.statusCode == 200 else { return nil }
let reply = try JSONDecoder().decode(VerifyReply.self, from: data)
return reply.verified ? reply.token : nil
}
After a successful verify, store the session token in the Keychain, not in UserDefaults.
How should you write the OTP SMS so autofill works?
- Put the code first or very early: "482913 is your OTP to log in to ABC App. Do not share it. - ABC".
- Use the words "OTP" or "code" near the digits; iOS uses them to recognise the message.
- Keep only one number group in the message where you can, so autofill does not pick the wrong digits.
- For Android SMS Retriever, end the message with your 11-character app hash, and register that exact text as your DLT template.
- Keep it under 160 characters so it is one SMS and arrives as a single message.
✔Your DLT template must match the message word for word, with the code in a
{#numeric#} variable. Our team checks OTP templates and helps with
DLT registration free of cost.
What security rules matter most in a mobile OTP flow?
- Keep the API key on the server. The app holds no SMS credentials at all.
- Hash the code and expire it in 5 minutes. Delete it after one successful use.
- Limit attempts and resends. Five wrong tries end the code; allow a resend every 30 to 60 seconds and cap sends per number per day. See our verify and resend OTP guide.
- Rate-limit by device and IP on your backend to stop SMS pumping bots.
- Return a session token, not the code. The backend never sends the OTP back to the app.
Why build mobile OTP login on SMSGatewayHub?
- 2-6 second typical delivery with automatic retry and load balancing across operator routes.
- ₹0.185 to ₹0.245 per OTP SMS + 18% GST, DLT scrubbing included, pay only for delivered SMS. See OTP SMS pricing.
- 99.9% uptime SLA, ISO 27001 certified, trusted by businesses since 2009.
- One simple HTTPS API your backend can call from any language. Docs: developer API.
- No code to type at all? OneTap Verify logs users in with a tap on a link.
Start with 1,000 free SMS credits for your app's OTP login
No credit card. Free DLT help. Get your API key and test on your own phone today.
Create free account
Frequently asked questions
Can my Flutter app call the OTP SMS API directly?
It should not. The API key would be inside the app, where anyone can extract it. The Flutter app calls your backend, and your backend calls the SMSGatewayHub SendSMS endpoint.
How does OTP autofill work on iPhone?
Set the text field's content type to oneTimeCode (UIKit or SwiftUI) or use AutofillHints.oneTimeCode in Flutter. iOS reads the code from the incoming SMS and offers it above the keyboard, with no permission needed.
How do I auto-read the OTP on Android?
Use Google's SMS Retriever API. Add your app's 11-character hash at the end of the OTP message and register that text as your DLT template; the app then receives the code without the SMS read permission.
Who verifies the code in a mobile OTP flow?
Your backend. It stores a hash of the code with an expiry, compares it with what the user typed and returns a session token. SMSGatewayHub delivers the SMS; it does not verify codes.
How much does OTP SMS cost for app login?
OTP SMS costs ₹0.185 to ₹0.245 per SMS plus 18% GST depending on pack size, including DLT scrubbing. You pay only for delivered OTPs and get 1,000 free credits on sign-up.
Related reading: OTP SMS API, OTP REST API reference, OTP login with Node.js and React, OTP SMS API in Python, and OTP SMS API in .NET.
Sources: SMSGatewayHub OTP SMS API documentation and published OTP pricing (November 2026); Apple developer documentation for UITextContentType.oneTimeCode; Flutter AutofillHints documentation; Google SMS Retriever API documentation; TRAI DLT rules. Prices exclude 18% GST and can change; confirm your rate with sales.