OTP verification in Ruby on Rails: send, verify and handle errors
Written by Vivek SinghReviewed by the DiOTP team Published 3 December 2026Last updated 3 December 2026
10 min read
OTP verification in Ruby on Rails needs one service object and one controller with two actions: create asks DiOTP to text a code and keeps the request_id in the session, and verify sends that request_id with the typed code to DiOTP and signs the user in on a 200. DiOTP generates, stores and checks the code, so it never touches your database. This guide uses Net::HTTP from the standard library, maps every DiOTP error code, handles 429 limits and the 30 second resend cooldown, and tests the flow with WebMock.
How the flow works
DiOTP has two endpoints. POST /v1/otp/send takes a mobile number and returns a request_id. POST /v1/otp/verify takes the request_id and the code the user typed, and returns 200 when it matches. Codes expire after 5 minutes and allow 5 attempts. Both calls use your API key as a Bearer token.
- The browser posts a phone number to POST /otp/send.
- The create action validates it, calls DiOTP and stores the request_id in session.
- The browser posts the typed code to POST /otp/verify.
- The verify action reads the request_id from the session, calls DiOTP and, on success, resets the session and signs the user in.
The API key stays on the server, in an environment variable. Never render it into a view, a Stimulus controller or a mobile app.
On DiOTP you can start without your own DLT registration: codes go out on DiOTP's registered header and pre-approved OTP template, as explained on the OTP without DLT page. The Rails code below does not change when you later move to your own sender ID.
Build it step by step
- Use Rails 7.2 or newer, which added rate_limit to controllers. On older versions, use Rack::Attack for the per-IP limit instead.
- Sign up for DiOTP, create an API key and set it as DIOTP_API_KEY in your server's environment.
- Add the DiotpClient service object in app/services.
- Add OtpController and the two routes.
- Add webmock to the test group of your Gemfile, run the tests, then try the flow on your own number.
ENV.fetch("DIOTP_API_KEY") raises KeyError when the variable is missing, so a misconfigured server fails on the first call instead of silently sending an empty key. If you prefer, read it in an initializer so the app refuses to boot without it.
A DiOTP client with Net::HTTP
The service object adds the Bearer key, JSON headers and timeouts, and raises DiotpClient::Error with the HTTP status and the stable error code from DiOTP's envelope, {"error":{"code":"...","message":"..."}}. Network failures become the same error with the code network_error, so callers deal with one exception class.
app/services/diotp_client.rb
# app/services/diotp_client.rb: plain Net::HTTP, no gem needed.
require "net/http"
require "json"
require "securerandom"
class DiotpClient
BASE = "https://api-diotp.diorbit.com/v1"
# An error reply from DiOTP. Branch on #code, never on the message text.
class Error < StandardError
attr_reader :status, :code
def initialize(status, code, message = "")
super("#{status} #{code}: #{message}")
@status = status
@code = code
end
end
NETWORK_ERRORS = [Net::OpenTimeout, Net::ReadTimeout, SocketError,
Errno::ECONNREFUSED, Errno::ECONNRESET, OpenSSL::SSL::SSLError].freeze
def initialize(api_key: ENV.fetch("DIOTP_API_KEY"))
@api_key = api_key
end
# Sends a code to a 10-digit Indian number. Returns request_id and expires_at.
def send_otp(phone, purpose: "login")
body = { to: phone, country_code: 91, channel: "sms", purpose: purpose }
key = SecureRandom.uuid # one key per user action, reused only for its retry
attempts = 0
begin
attempts += 1
post("/otp/send", body, idempotency_key: key)
rescue Error => e
# A timeout or a 503 is safe to retry once with the SAME key: DiOTP
# returns the first result instead of sending a second code.
raise unless attempts < 2 && %w[network_error sending_unavailable].include?(e.code)
sleep 1.5
retry
end
end
def verify_otp(request_id, code)
post("/otp/verify", { request_id: request_id, code: code.to_s })
end
private
def post(path, body, idempotency_key: nil)
uri = URI("#{BASE}#{path}")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{@api_key}"
req["Content-Type"] = "application/json"
req["Idempotency-Key"] = idempotency_key if idempotency_key
req.body = JSON.generate(body)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 10) do |http|
http.request(req)
end
data = begin
JSON.parse(res.body.to_s)
rescue JSON::ParserError
{}
end
return data if res.code.to_i < 400
err = data["error"] || {}
raise Error.new(res.code.to_i, err["code"] || "unknown", err["message"].to_s)
rescue *NETWORK_ERRORS => e
raise Error.new(0, "network_error", e.message)
end
endThe send body uses to as digits only, the 10-digit number without +91, and country_code as the integer 91. Each send gets a fresh Idempotency-Key. On a network error or a 503 sending_unavailable it retries once with the same key; DiOTP sees the same key and body, returns the first result and sends nothing new. Field details are on the send OTP reference and the verify OTP reference.
The controller and routes
One controller holds both steps. The pending request lives in session[:otp] with string keys, because the cookie store serialises the session as JSON and symbols would come back as strings anyway.
app/controllers/otp_controller.rb
# app/controllers/otp_controller.rb (Rails 7.2 or newer, for rate_limit)
class OtpController < ApplicationController
COOLDOWN = 30 # seconds, the same as DiOTP's resend cooldown
# code => [HTTP status, message, seconds to wait or nil]
USER_ERRORS = {
"resend_cooldown" => [429, "Please wait 30 seconds before asking for another code.", 30],
"phone_hourly_limit" => [429, "Too many codes for this number. Try again in an hour.", 3600],
"phone_daily_limit" => [429, "Too many codes for this number today. Try tomorrow.", nil],
"api_key_minute_limit" => [429, "We are busy right now. Please try again in a minute.", 60],
"rate_limited" => [429, "We are busy right now. Please try again in a minute.", 60],
"invalid_code" => [400, "That code is not right. Check the SMS and try again.", nil],
"expired" => [410, "This code has expired. Ask for a new one.", nil],
"not_pending" => [409, "This code is no longer valid. Ask for a new one.", nil],
"not_found" => [404, "We could not find that code. Ask for a new one.", nil],
"too_many_attempts" => [429, "Too many wrong tries. Ask for a new code.", nil],
"invalid_request" => [400, "Enter a valid 10-digit mobile number.", nil]
}.freeze
# After these verify errors the request_id can no longer be used.
FINISHED = %w[expired not_pending too_many_attempts not_found].freeze
# Per-IP limit on sending, in front of DiOTP's per-number limits.
rate_limit to: 10, within: 15.minutes, only: :create,
with: -> { render json: { error: "too_many_requests", message: "Too many requests. Try again later." }, status: :too_many_requests }
rescue_from DiotpClient::Error, with: :render_otp_error
# POST /otp/send
def create
phone = normalize(params[:phone])
unless phone.match?(/\A[6-9]\d{9}\z/)
return render json: { error: "invalid_phone", message: "Enter a 10-digit mobile number." }, status: :bad_request
end
# Mirror DiOTP's 30 second cooldown: an instant 429, no API call.
pending = session[:otp]
if pending && pending["phone"] == phone
waited = Time.now.to_i - pending["sent_at"]
if waited < COOLDOWN
response.set_header("Retry-After", (COOLDOWN - waited).to_s)
return render json: { error: "resend_cooldown", retry_after: COOLDOWN - waited }, status: :too_many_requests
end
end
result = diotp.send_otp(phone, purpose: "login")
session[:otp] = { "request_id" => result["request_id"], "phone" => phone, "sent_at" => Time.now.to_i }
render json: { sent: true, expires_at: result["expires_at"], resend_in: COOLDOWN }
end
# POST /otp/verify
def verify
pending = session[:otp]
return render json: { error: "no_pending_code", message: "Ask for a code first." }, status: :bad_request unless pending
code = params[:code].to_s.strip
unless code.match?(/\A\d{4,10}\z/)
return render json: { error: "invalid_code", message: "Enter the code from the SMS." }, status: :bad_request
end
begin
diotp.verify_otp(pending["request_id"], code)
rescue DiotpClient::Error => e
raise unless e.code == "already_verified" # a double tap counts as success
end
reset_session # a new session at login: no session fixation
session[:verified_phone] = pending["phone"] # sign the user in here
render json: { verified: true }
end
private
def diotp
@diotp ||= DiotpClient.new
end
def normalize(raw)
digits = raw.to_s.gsub(/\D/, "")
digits = digits.delete_prefix("91") if digits.length == 12
digits = digits.delete_prefix("0") if digits.length == 11
digits
end
def render_otp_error(e)
session.delete(:otp) if FINISHED.include?(e.code)
status, message, wait = USER_ERRORS[e.code]
unless status
# unauthorized, trial_restricted, trial_used_up, insufficient_balance,
# account_suspended, channel_not_enabled, test_limit, sending_unavailable ...
Rails.logger.error("DiOTP error status=#{e.status} code=#{e.code}") # never log the key
return render json: { error: "otp_unavailable", message: "We could not send a code right now. Please try again shortly." },
status: :service_unavailable
end
body = { error: e.code, message: message }
if wait
response.set_header("Retry-After", wait.to_s)
body[:retry_after] = wait
end
render json: body, status: status
end
endconfig/routes.rb
# config/routes.rb
Rails.application.routes.draw do
post "otp/send", to: "otp#create", as: :otp_send
post "otp/verify", to: "otp#verify", as: :otp_verify
endcreate keeps its own copy of the 30 second cooldown: a second tap within 30 seconds gets an instant 429 with a Retry-After header and no API call. DiOTP enforces the real limit for every device and tab, so this is only a convenience. verify treats already_verified as success, since it usually means a double submit. reset_session at login issues a new session id, which prevents session fixation; replace the verified_phone line with however your app signs a user in.
These are JSON actions called from your own pages, so keep CSRF protection on and send the token from csrf_meta_tags in the X-CSRF-Token header. The session holds only an id and a phone number, so the default cookie store is fine; it is encrypted and signed.
Map every error code to a reply
rescue_from sends every DiotpClient::Error to render_otp_error. Codes the visitor can act on pass through with a plain message, and the rate limits add Retry-After. Setup and account problems are logged with their status and code, never the key, and hidden behind otp_unavailable.
| Code | Status | What the action returns |
|---|---|---|
| resend_cooldown | 429 | Retry-After: 30. Keep the resend button disabled. |
| phone_hourly_limit | 429 | Retry-After: 3600. Come back in an hour. |
| phone_daily_limit | 429 | Try tomorrow; 10 codes per number per day. |
| api_key_minute_limit, rate_limited | 429 | Retry-After: 60. Alert yourself if it repeats. |
| invalid_code | 400 | Try again, up to 5 attempts. |
| expired | 410 | Offer a new code; codes last 5 minutes. |
| too_many_attempts | 429 | Start over with a new code. |
| unauthorized, trial_restricted, trial_used_up, insufficient_balance, test_limit | 401, 402, 403, 429 | Logged; generic reply. |
A 429 from DiOTP means nothing was sent and nothing was charged. The complete list is on the error codes page.
Rate limits: DiOTP's and your own
DiOTP limits each number to one code every 30 seconds, 3 an hour and 10 a day, and each API key to 30 sends a minute. Those protect each phone, but a script that sends to a new number each time gets past them; that is how SMS pumping drains a wallet. The rate_limit line in the controller adds a per-IP limit of 10 sends in 15 minutes.
rate_limit counts in Rails.cache, so use a shared cache such as Redis or Solid Cache in production; a per-process memory store counts each Puma worker separately. Behind a proxy, configure trusted proxies so request.remote_ip is the visitor's address. Add a bot check on public sign-up forms as well. The SMS pumping protection guide covers the wider defence.
Test it without sending an SMS
WebMock stubs DiOTP at the HTTP level, so the real client, controller and session run in the test. The tests check the request body, the full send and verify flow, the 429 with Retry-After and the hiding of account errors.
test/integration/otp_flow_test.rb
# test/integration/otp_flow_test.rb (gem "webmock", group: :test)
require "test_helper"
require "webmock/minitest"
class OtpFlowTest < ActionDispatch::IntegrationTest
BASE = "https://api-diotp.diorbit.com/v1"
JSON_HEADERS = { "Content-Type" => "application/json" }.freeze
setup { ENV["DIOTP_API_KEY"] = "test_key" }
test "send then verify signs the number in" do
stub_request(:post, "#{BASE}/otp/send")
.with(headers: { "Authorization" => "Bearer test_key" },
body: hash_including("to" => "9876543210", "country_code" => 91))
.to_return(status: 200, headers: JSON_HEADERS,
body: { request_id: "req_1", channel: "sms", expires_at: "2026-12-03T10:05:00+00:00" }.to_json)
stub_request(:post, "#{BASE}/otp/verify")
.with(body: { request_id: "req_1", code: "482913" }.to_json)
.to_return(status: 200, headers: JSON_HEADERS,
body: { request_id: "req_1", verified: true, verified_at: "2026-12-03T10:01:00+00:00" }.to_json)
post "/otp/send", params: { phone: "+91 98765 43210" }, as: :json
assert_response :success
post "/otp/verify", params: { code: "482913" }, as: :json
assert_equal({ "verified" => true }, response.parsed_body)
end
test "a cooldown from DiOTP becomes 429 with Retry-After" do
stub_request(:post, "#{BASE}/otp/send")
.to_return(status: 429, headers: JSON_HEADERS,
body: { error: { code: "resend_cooldown", message: "wait" } }.to_json)
post "/otp/send", params: { phone: "9876543210" }, as: :json
assert_response :too_many_requests
assert_equal "30", response.headers["Retry-After"]
end
test "account problems are hidden from the visitor" do
stub_request(:post, "#{BASE}/otp/send")
.to_return(status: 402, headers: JSON_HEADERS,
body: { error: { code: "insufficient_balance", message: "recharge" } }.to_json)
post "/otp/send", params: { phone: "9876543210" }, as: :json
assert_equal "otp_unavailable", response.parsed_body["error"]
end
endThen try it for real. A new DiOTP account has 10 free test messages, sent only to the mobile number you verified at sign-up; other numbers return 403 trial_restricted. Ask twice within 30 seconds to see resend_cooldown, and wait more than 5 minutes before verifying to see expired. Recharge your wallet from ₹100 and the same key sends to any Indian mobile number at ₹0.26 to ₹0.40 per OTP plus 18% GST.
