OTP without DLT for Android and Flutter apps: a build guide

To add OTP without DLT to an Android or Flutter app, have the app call your own backend, and have the backend call DiOTP's send and verify API with the key kept on the server. The codes go out on DiOTP's registered header and pre-approved template, so you register nothing. On Android, the SMS User Consent API fills the code with one tap on that shared template; the SMS Retriever API needs a template of your own.

By , Founder, Diorbit TechnologiesUpdated Last checked

How should an Android or Flutter app send OTP without DLT?

Through your backend, always. OTP without DLT on DiOTP means your codes are sent under DiOTP's registered DLT entity, the DIORBT header and a pre-approved OTP template. The API that sends them needs your API key, and an API key inside an app is not a secret: anyone can unpack an APK or an iOS build and read it, then use it to send codes on your balance.

So the architecture has three parts:

  1. The app asks your backend for a code, with the user's mobile number.
  2. Your backend calls POST /v1/otp/send on DiOTP with the key from its own environment, and keeps the returned request_id in the user's server-side session.
  3. The user types (or autofills) the code. The app sends it to your backend, which calls POST /v1/otp/verify with the request_id and the code, then issues your own session token.

This also lets your backend add its own checks before spending a message, such as a captcha or a per-device limit, on top of the limits DiOTP enforces per phone number: one code every 30 seconds, three an hour and ten a day.

Steps to add OTP login to your app

  1. Create a DiOTP account and an API key. Put the key in your backend's environment as DIOTP_API_KEY. Never put it in the app.
  2. Add two backend routes: one that sends a code and stores the request_id, and one that verifies the code and returns your own session token.
  3. In the app, build a phone number screen that calls the first route, and a code screen that calls the second.
  4. Add autofill: SMS User Consent on Android, and the one-time-code content type on iOS.
  5. Test on the free test messages, which go only to the number you verified at sign-up. Then recharge your wallet to go live.

What does the backend look like?

Two small routes. They pass DiOTP's error code back to the app, so the app can show the right message, but never the key and never anything that reveals the code.

Backend: /auth/otp/start and /auth/otp/check

// Your backend (Node.js shown; any language works). The app calls these two routes.
// DIOTP_API_KEY lives only here, in the server's environment.
app.post("/auth/otp/start", async (req, res) => {
  const r = await fetch("https://api-diotp.diorbit.com/v1/otp/send", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.DIOTP_API_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": crypto.randomUUID(),
    },
    body: JSON.stringify({ to: req.body.phone, country_code: 91, channel: "sms", purpose: "login" }),
  });
  const body = await r.json();
  if (!r.ok) return res.status(400).json({ error: body.error.code });
  req.session.otpRequestId = body.request_id; // keep it on the server
  res.json({ ok: true });
});

app.post("/auth/otp/check", async (req, res) => {
  const r = await fetch("https://api-diotp.diorbit.com/v1/otp/verify", {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.DIOTP_API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ request_id: req.session.otpRequestId, code: String(req.body.code) }),
  });
  if (!r.ok) return res.status(400).json({ error: (await r.json()).error.code });
  res.json({ ok: true, token: issueYourOwnSessionToken(req) });
});

The Node.js OTP verification guide and the Python guide build these routes out with error handling and safe retries. Every field and error code is in the OTP SMS API reference.

Which Android autofill API works on the shared template?

Android offers two ways for an app to read an incoming OTP without the READ_SMS permission, and they have different rules.

SMS User Consent APISMS Retriever API
What the user doesTaps Allow on a system prompt that shows the messageNothing; the app reads the message silently
What the SMS must containA 4 to 10 character alphanumeric code with at least one numberThe code and your app's 11-character hash
Works on DiOTP's shared templateYesNo: the fixed wording has no place for your app hash
Works on your own templateYesYes, if the template includes the hash

The SMS Retriever API matches a message to your app by an 11-character hash computed from your package name and signing key, which must appear in the SMS. The shared template's wording is fixed on DLT: only the code and your company name change, and the company slot holds up to 30 characters for the name. There is nowhere to put a hash, so for silent autofill you need your own DLT template with the hash in it, sent from your own sender ID. You can add one under Sender IDs in the DiOTP dashboard later with no code changes on the backend.

The SMS User Consent API needs no hash. It watches for the next SMS that contains a one-time code, shows the user the message, and hands it to your app if they tap Allow. That works on the shared template today.

Kotlin: SMS User Consent for the shared template

Start listening just before your backend sends the code. The listener waits up to five minutes for one matching message. When it arrives, Android asks the user for permission to share that single message, and your app pulls out the digits.

OtpActivity.kt

// build.gradle: implementation("com.google.android.gms:play-services-auth-api-phone:<latest>")
class OtpActivity : AppCompatActivity() {

    private val consentLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val sms = result.data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE).orEmpty()
                // The shared template starts with the code, so the first run of digits is the OTP.
                Regex("\\d{4,10}").find(sms)?.value?.let { otpInput.setText(it) }
            }
            // RESULT_CANCELED: the user said no. Let them type the code.
        }

    private val smsReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action != SmsRetriever.SMS_RETRIEVED_ACTION) return
            val extras = intent.extras ?: return
            val status = extras.get(SmsRetriever.EXTRA_STATUS) as Status
            if (status.statusCode == CommonStatusCodes.SUCCESS) {
                val consent = extras.getParcelable<Intent>(SmsRetriever.EXTRA_CONSENT_INTENT)
                consent?.let { consentLauncher.launch(it) }
            }
            // TIMEOUT: no SMS arrived while listening. The user types the code.
        }
    }

    /** Call this right before you ask your backend to send the code. */
    private fun listenForOtp() {
        // null: accept the SMS from any sender (the shared template comes from an operator-prefixed DIORBT).
        SmsRetriever.getClient(this).startSmsUserConsent(null)
        ContextCompat.registerReceiver(
            this, smsReceiver, IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION),
            SmsRetriever.SEND_PERMISSION, null, ContextCompat.RECEIVER_EXPORTED,
        )
    }

    override fun onDestroy() {
        runCatching { unregisterReceiver(smsReceiver) }
        super.onDestroy()
    }
}

Because the shared template starts with the code ("482913 is your login OTP for Acme..."), the first run of digits is the OTP. If your company name contains digits, that still holds, because the code always comes first. If the user taps Deny or nothing arrives, the code field stays editable, so they can type it.

Text message

VM-DIORBT

482913 is your login OTP for Acme. Do not share it with anyone. Powered by Diorbit Technologies!

The message the consent prompt shows: the code comes first, which makes it easy to extract.

Flutter: calling your backend and filling the code

In Flutter, the app talks only to your backend, with the http package. Keep DiOTP's error codes as the contract between backend and app, and map them to friendly words in the app.

otp_api.dart

// pubspec.yaml: http
import 'dart:convert';
import 'package:http/http.dart' as http;

// YOUR backend. The app never calls DiOTP and never holds the API key.
const backend = 'https://api.yourapp.example';

class OtpException implements Exception {
  OtpException(this.code);
  final String code; // DiOTP's error code, passed through by your backend
}

Future<void> requestOtp(String phone) async {
  final res = await http.post(
    Uri.parse('$backend/auth/otp/start'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({'phone': phone}),
  );
  if (res.statusCode != 200) {
    throw OtpException(jsonDecode(res.body)['error'] ?? 'unknown');
  }
}

Future<String> checkOtp(String code) async {
  final res = await http.post(
    Uri.parse('$backend/auth/otp/check'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({'code': code}),
  );
  final body = jsonDecode(res.body);
  if (res.statusCode != 200) throw OtpException(body['error'] ?? 'unknown');
  return body['token']; // your own session token
}

String messageFor(OtpException e) => switch (e.code) {
      'resend_cooldown' => 'Please wait 30 seconds before asking again.',
      'phone_hourly_limit' || 'phone_daily_limit' => 'Too many codes for this number. Try later.',
      'invalid_code' => 'That code is not right. Try again.',
      'expired' || 'not_pending' || 'too_many_attempts' => 'Please ask for a new code.',
      _ => 'Something went wrong. Please try again.',
    };

For the code field, set the one-time-code autofill hint. On iOS this lets the keyboard offer the code from the SMS, and it works with the shared template because iOS reads the code from any message that contains it.

The code field

// iOS reads the code from the SMS and offers it above the keyboard.
TextField(
  keyboardType: TextInputType.number,
  autofillHints: const [AutofillHints.oneTimeCode],
  maxLength: 10,
  decoration: const InputDecoration(labelText: 'Enter the code'),
)

For Android autofill in Flutter, community plugins wrap the same two Android APIs: some expose the SMS User Consent API, some the SMS Retriever API, and some both. With the shared template, choose the User Consent option. A plugin's Retriever mode, or its "get app signature" helper, only matters once you have your own template with the hash in it. Check each plugin's documentation for which API it calls, because the names vary.

What about React Native, iOS and testing?

React Native follows the same pattern. The React Native SMS Retriever guide shows the native side; remember that its Retriever flow needs your own template, while a consent-based approach works on the shared one. For the full comparison of iOS, Android and web autofill, and what to check when the code does not fill, see the OTP autofill reference for Android and iOS.

To test, sign up and verify your own mobile number. A new account gets 10 free test messages, sent only to that number, so run the whole flow on your own phone: request a code, accept the consent prompt, and confirm your backend's verify call succeeds. A send to any other number returns 403 trial_restricted until you recharge. A recharge makes the account live, and the price is ₹0.26 to ₹0.40 per OTP plus 18% GST. The code expires after five minutes and allows five attempts, so build a resend button with a 30 second timer.

Questions and answers

Can I put the DiOTP API key in my Android or Flutter app?

No. Anyone can extract a key from an app build and spend your balance. Keep the key on your backend and have the app call your backend.

Does Android OTP autofill work without DLT registration?

Yes, with the SMS User Consent API, which needs no app hash and works on DiOTP's shared template. The user taps Allow once and the code fills.

Why does the SMS Retriever API not work on the shared template?

It needs your app's 11-character hash inside the SMS. The shared template has fixed wording with no place for it, so silent autofill needs your own DLT template.

Does iOS autofill work on the shared template?

Yes. Set the one-time-code content type on the code field. iOS reads the code from any SMS that contains it and offers it above the keyboard.

Which Flutter package should I use for SMS autofill?

Any well-maintained plugin that wraps the Android SMS User Consent API works on the shared template. Use a plugin's SMS Retriever mode only after you have your own template with the app hash.

Do I need to change the app when I move to my own sender ID?

No change is needed for the send and verify flow. You only add code if you switch Android autofill to the SMS Retriever API, which needs the app hash in your new template.

Send your first OTP today.

Free test credits on sign-up, API keys in a minute, and a team that picks up the phone.