One-time passcodes

Send verification codes for sign-in, sign-up, and sensitive actions.

A one-time passcode (OTP) is a short-lived code you text to a user to prove they hold the phone. It's the backbone of phone-number sign-up, two-factor sign-in, and "confirm it's really you" checks before sensitive actions.

EZ Texting delivers the message. You generate the code, store it, and verify it.

When to use this guide

Use it when…Use something else when…
You need to confirm a user holds a phone number: sign-up, two-factor sign-in, or a check before a sensitive action.The message is a notification, not a check → Order & shipping notifications

What you'll build

  1. Generate a code, store a keyed hash of it with an expiry, and send it.
  2. Verify the code the user types, with attempt counting and single-use redemption in one atomic step.
  3. Throttle requests per number and per IP so your account can't be abused to send large volumes of codes.

Design decisions first

DecisionRecommendation
Code format6 digits, generated with a cryptographic RNG. Digits only (easier to type, and iOS/Android autofill recognizes them).
Lifetime5–10 minutes. Store the expiry with the code.
StorageStore HMAC-SHA256(pepper, code), not the code and not a plain hash. A six-digit code has only a million values; a plain SHA-256 of it can be brute-forced from a leaked table in seconds. The pepper is a server-side secret kept separately from the database (an environment variable or secrets manager).
Attempts and single useAllow 3–5 wrong guesses, then invalidate. Count attempts and consume the code in the same database statement so two concurrent requests can't both succeed or both get a free try.
ResendAllow a resend after 30–60 seconds, and cap resends per hour. A resend is a new code with a new row; never re-send an old one.
Message copyShort, no links, name your app, state the lifetime. Autofill works best when the code sits near the start: Your Acme code is 482913. It expires in 10 minutes.
ValidationKeep strictValidation at its default (true). A bad number should be a 400 you can show the user, not a silent skip that leaves them staring at an empty inbox.
Message typePass messageType: "SMS" explicitly. You never want a passcode delivered as an MMS, which can be slower on some carriers.

Step 1: Generate and send

Set OTP_PEPPER to a long random secret, stored apart from your database.

curl -X POST https://a.eztexting.com/v1/messages \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d '{
    "toNumbers": ["15551234567"],
    "message": "Your Acme code is 482913. It expires in 10 minutes.",
    "messageType": "SMS",
    "strictValidation": true
  }'
import os, secrets, hmac, hashlib, time
import requests

auth = (os.environ["EZTEXTING_USERNAME"], os.environ["EZTEXTING_PASSWORD"])
# separate secret, not in the database
PEPPER = os.environ["OTP_PEPPER"].encode()
CODE_TTL_SECONDS = 600

def code_mac(code: str) -> str:
    return hmac.new(PEPPER, code.encode(), hashlib.sha256).hexdigest()

def send_otp(phone: str) -> None:
    # "482913"
    code = f"{secrets.randbelow(10**6):06d}"
    db.execute(
        "INSERT INTO otp (phone, mac, expires_at, attempts, consumed) VALUES (%s, %s, %s, 0, false) "
        "ON CONFLICT (phone) DO UPDATE SET mac = EXCLUDED.mac, expires_at = EXCLUDED.expires_at, attempts = 0, consumed = false",
        (phone, code_mac(code), time.time() + CODE_TTL_SECONDS),
    )

    resp = requests.post(
        "https://a.eztexting.com/v1/messages",
        auth=auth,
        json={
            "toNumbers": [phone],
            "message": f"Your Acme code is {code}. It expires in 10 minutes.",
            "messageType": "SMS",
            "strictValidation": True,
        },
        timeout=30,
    )
    if resp.status_code == 400:
        db.execute("DELETE FROM otp WHERE phone = %s", (phone,))
        # the body's errors[].message says why; only some of these are the user's to fix
        reason = resp.text
        if "opted out" in reason:
            # they replied STOP earlier: they can text JOIN to your number to opt back in
            raise PhoneOptedOut(phone)
        if "phone number" in reason.lower():
            raise InvalidPhoneNumber(phone)
        # out of credits, account not verified, ...: not the user's to fix
        raise RuntimeError(f"EZ Texting 400: {reason}")
    resp.raise_for_status()
import crypto from "node:crypto";

const credentials = Buffer.from(
  `${process.env.EZTEXTING_USERNAME}:${process.env.EZTEXTING_PASSWORD}`
).toString("base64");
// separate secret, not in the database
const PEPPER = process.env.OTP_PEPPER;
const CODE_TTL_MS = 10 * 60 * 1000;

const codeMac = (code) => crypto.createHmac("sha256", PEPPER).update(code).digest("hex");

async function sendOtp(phone) {
  // "482913"
  const code = crypto.randomInt(0, 1_000_000).toString().padStart(6, "0");
  await db.query(
    `INSERT INTO otp (phone, mac, expires_at, attempts, consumed) VALUES ($1, $2, $3, 0, false)
     ON CONFLICT (phone) DO UPDATE SET mac = EXCLUDED.mac, expires_at = EXCLUDED.expires_at, attempts = 0, consumed = false`,
    [phone, codeMac(code), Date.now() + CODE_TTL_MS]);

  const res = await fetch("https://a.eztexting.com/v1/messages", {
    method: "POST",
    headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      toNumbers: [phone],
      message: `Your Acme code is ${code}. It expires in 10 minutes.`,
      messageType: "SMS",
      strictValidation: true,
    }),
  });
  if (res.status === 400) {
    await db.query("DELETE FROM otp WHERE phone = $1", [phone]);
    // the body's errors[].message says why; only some of these are the user's to fix
    const reason = await res.text();
    // they replied STOP earlier: they can text JOIN to your number to opt back in
    if (reason.includes("opted out")) throw new PhoneOptedOut(phone);
    if (/phone number/i.test(reason)) throw new InvalidPhoneNumber(phone);
    // out of credits, account not verified, ...: not the user's to fix
    throw new Error(`EZ Texting 400: ${reason}`);
  }
  if (!res.ok) throw new Error(`EZ Texting ${res.status}`);
}
<?php
// separate secret, not in the database
$pepper = getenv("OTP_PEPPER");

function sendOtp(string $phone): void {
    global $pepper, $pdo;
    // "482913"
    $code = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    $mac = hash_hmac('sha256', $code, $pepper);
    $pdo->prepare("INSERT INTO otp (phone, mac, expires_at, attempts, consumed) VALUES (?, ?, ?, 0, 0)
                   ON CONFLICT (phone) DO UPDATE SET mac = excluded.mac, expires_at = excluded.expires_at, attempts = 0, consumed = 0")
        ->execute([$phone, $mac, time() + 600]);

    $ch = curl_init("https://a.eztexting.com/v1/messages");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode([
            "toNumbers" => [$phone],
            "message" => "Your Acme code is $code. It expires in 10 minutes.",
            "messageType" => "SMS",
            "strictValidation" => true,
        ]),
    ]);
    $reason = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status === 400) {
        $pdo->prepare("DELETE FROM otp WHERE phone = ?")->execute([$phone]);
        // the body's errors[].message says why; only some of these are the user's to fix
        // they replied STOP earlier: they can text JOIN to your number to opt back in
        if (str_contains($reason, "opted out")) throw new PhoneOptedOut($phone);
        if (stripos($reason, "phone number") !== false) throw new InvalidPhoneNumber($phone);
        // out of credits, account not verified, ...: not the user's to fix
        throw new RuntimeException("EZ Texting 400: $reason");
    }
    if ($status !== 201) { throw new RuntimeException("EZ Texting $status"); }
}
require "securerandom"
require "openssl"

# separate secret, not in the database
PEPPER = ENV.fetch("OTP_PEPPER")
code_mac = ->(code) { OpenSSL::HMAC.hexdigest("SHA256", PEPPER, code) }

def send_otp(phone)
  # "482913"
  code = format("%06d", SecureRandom.random_number(10**6))
  DB.exec_params("INSERT INTO otp (phone, mac, expires_at, attempts, consumed) VALUES ($1, $2, $3, 0, false)
                  ON CONFLICT (phone) DO UPDATE SET mac = EXCLUDED.mac, expires_at = EXCLUDED.expires_at, attempts = 0, consumed = false",
                 [phone, OpenSSL::HMAC.hexdigest("SHA256", PEPPER, code), Time.now.to_i + 600])

  uri = URI("https://a.eztexting.com/v1/messages")
  req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
  req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
  req.body = {
    toNumbers: [phone],
    message: "Your Acme code is #{code}. It expires in 10 minutes.",
    messageType: "SMS",
    strictValidation: true
  }.to_json

  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
  if res.code == "400"
    DB.exec_params("DELETE FROM otp WHERE phone = $1", [phone])
    # the body's errors[].message says why; only some of these are the user's to fix
    reason = res.body
    # they replied STOP earlier: they can text JOIN to your number to opt back in
    raise PhoneOptedOut, phone if reason.include?("opted out")
    raise InvalidPhoneNumber, phone if reason.match?(/phone number/i)
    # out of credits, account not verified, ...: not the user's to fix
    raise "EZ Texting 400: #{reason}"
  end
  raise "EZ Texting #{res.code}" unless res.code == "201"
end
// separate secret
static final byte[] PEPPER = System.getenv("OTP_PEPPER").getBytes(StandardCharsets.UTF_8);

static String codeMac(String code) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(PEPPER, "HmacSHA256"));
    return HexFormat.of().formatHex(mac.doFinal(code.getBytes(StandardCharsets.UTF_8)));
}

void sendOtp(String phone) throws Exception {
    // "482913"
    String code = String.format("%06d", new SecureRandom().nextInt(1_000_000));
    // attempts = 0, consumed = false
    otpStore.upsert(phone, codeMac(code), Instant.now().plusSeconds(600));

    String json = """
        {"toNumbers": ["%s"], "message": "Your Acme code is %s. It expires in 10 minutes.",
         "messageType": "SMS", "strictValidation": true}
        """.formatted(phone, code);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://a.eztexting.com/v1/messages"))
        .header("Authorization", "Basic " + basicAuth)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    if (response.statusCode() == 400) {
        otpStore.delete(phone);
        // the body's errors[].message says why; only some of these are the user's to fix
        String reason = response.body();
        // they replied STOP earlier: they can text JOIN to your number to opt back in
        if (reason.contains("opted out")) throw new PhoneOptedOut(phone);
        if (reason.toLowerCase().contains("phone number")) throw new InvalidPhoneNumber(phone);
        // out of credits, account not verified, ...: not the user's to fix
        throw new RuntimeException("EZ Texting 400: " + reason);
    }
    if (response.statusCode() != 201) throw new RuntimeException("EZ Texting " + response.statusCode());
}
// separate secret
static readonly byte[] Pepper = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("OTP_PEPPER")!);

static string CodeMac(string code) => Convert.ToHexString(HMACSHA256.HashData(Pepper, Encoding.UTF8.GetBytes(code)));

async Task SendOtpAsync(string phone)
{
    // "482913"
    var code = RandomNumberGenerator.GetInt32(1_000_000).ToString("D6");
    // attempts = 0, consumed = false
    await otpStore.UpsertAsync(phone, CodeMac(code), DateTimeOffset.UtcNow.AddMinutes(10));

    var payload = new
    {
        toNumbers = new[] { phone },
        message = $"Your Acme code is {code}. It expires in 10 minutes.",
        messageType = "SMS",
        strictValidation = true
    };

    var res = await client.PostAsJsonAsync("https://a.eztexting.com/v1/messages", payload);
    if (res.StatusCode == HttpStatusCode.BadRequest)
    {
        await otpStore.DeleteAsync(phone);
        // the body's errors[].message says why; only some of these are the user's to fix
        var reason = await res.Content.ReadAsStringAsync();
        // they replied STOP earlier: they can text JOIN to your number to opt back in
        if (reason.Contains("opted out")) throw new PhoneOptedOut(phone);
        if (reason.Contains("phone number", StringComparison.OrdinalIgnoreCase)) throw new InvalidPhoneNumber(phone);
        // out of credits, account not verified, ...: not the user's to fix
        throw new InvalidOperationException($"EZ Texting 400: {reason}");
    }
    res.EnsureSuccessStatusCode();
}
// separate secret, not in the database
var pepper = []byte(os.Getenv("OTP_PEPPER"))

func codeMAC(code string) string {
	m := hmac.New(sha256.New, pepper)
	m.Write([]byte(code))
	return hex.EncodeToString(m.Sum(nil))
}

func sendOTP(phone string) error {
	n, _ := rand.Int(rand.Reader, big.NewInt(1_000_000))
	// "482913"
	code := fmt.Sprintf("%06d", n.Int64())
	// attempts = 0, consumed = false
	otpStore.Upsert(phone, codeMAC(code), time.Now().Add(10*time.Minute))

	body, _ := json.Marshal(map[string]any{
		"toNumbers":        []string{phone},
		"message":          fmt.Sprintf("Your Acme code is %s. It expires in 10 minutes.", code),
		"messageType":      "SMS",
		"strictValidation": true,
	})
	req, _ := http.NewRequest("POST", "https://a.eztexting.com/v1/messages", bytes.NewReader(body))
	req.SetBasicAuth(os.Getenv("EZTEXTING_USERNAME"), os.Getenv("EZTEXTING_PASSWORD"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	switch resp.StatusCode {
	case 201:
		return nil
	case 400:
		otpStore.Delete(phone)
		// the body's errors[].message says why; only some of these are the user's to fix
		b, _ := io.ReadAll(resp.Body)
		reason := string(b)
		switch {
		// they replied STOP earlier: they can text JOIN to your number to opt back in
		case strings.Contains(reason, "opted out"):
			return ErrOptedOut
		case strings.Contains(strings.ToLower(reason), "phone number"):
			return ErrInvalidPhoneNumber
		}
		// out of credits, account not verified, ...: not the user's to fix
		return fmt.Errorf("EZ Texting 400: %s", reason)
	default:
		return fmt.Errorf("EZ Texting %d", resp.StatusCode)
	}
}
{
  "id": "128452310003"
}

Step 2: Verify the code

Verification never touches the API. The key is making "count the attempt, check the code, consume it" a single atomic operation so two concurrent submissions can't both succeed, and a wrong guess can't sneak in without being counted. Two statements do it, each conditional on the row's current state:

  1. Charge the attempt with a conditional UPDATE … RETURNING mac that only matches an unexpired, unconsumed row with attempts remaining. No row → fail (expired, consumed, or locked out).
  2. Compare in constant time, then consume with UPDATE … WHERE consumed = false and treat exactly one row updated as success. A second concurrent request that passed step 1 with the right code gets zero rows here and fails.
MAX_ATTEMPTS = 5

def verify_otp(phone: str, submitted: str) -> bool:
    # 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
    row = db.one(
        "UPDATE otp SET attempts = attempts + 1 "
        "WHERE phone = %s AND consumed = false AND expires_at > %s AND attempts < %s "
        "RETURNING mac",
        (phone, time.time(), MAX_ATTEMPTS),
    )
    if row is None:
        # expired, already used, locked out, or never sent
        return False

    # 2. Compare in constant time; consume on success — exactly one row must change.
    if not hmac.compare_digest(row.mac, code_mac(submitted.strip())):
        return False
    consumed = db.execute(
        "UPDATE otp SET consumed = true WHERE phone = %s AND mac = %s AND consumed = false", (phone, row.mac)
    ).rowcount
    return consumed == 1
const MAX_ATTEMPTS = 5;

async function verifyOtp(phone, submitted) {
  // 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
  const { rows } = await db.query(
    `UPDATE otp SET attempts = attempts + 1
     WHERE phone = $1 AND consumed = false AND expires_at > $2 AND attempts < $3
     RETURNING mac`,
    [phone, Date.now(), MAX_ATTEMPTS]);
  // expired, already used, locked out, or never sent
  if (rows.length === 0) return false;

  // 2. Compare in constant time; consume on success — exactly one row must change.
  const given = Buffer.from(codeMac(submitted.trim()), "hex");
  const stored = Buffer.from(rows[0].mac, "hex");
  if (given.length !== stored.length || !crypto.timingSafeEqual(given, stored)) return false;

  const consumed = await db.query(
    "UPDATE otp SET consumed = true WHERE phone = $1 AND mac = $2 AND consumed = false", [phone, rows[0].mac]);
  return consumed.rowCount === 1;
}
<?php
const MAX_ATTEMPTS = 5;

function verifyOtp(string $phone, string $submitted): bool {
    global $pdo, $pepper;
    // 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
    $charge = $pdo->prepare("UPDATE otp SET attempts = attempts + 1
                             WHERE phone = ? AND consumed = 0 AND expires_at > ? AND attempts < ?
                             RETURNING mac");
    $charge->execute([$phone, time(), MAX_ATTEMPTS]);
    $mac = $charge->fetchColumn();
    // expired, already used, locked out, or never sent
    if ($mac === false) return false;

    // 2. Compare in constant time; consume on success — exactly one row must change.
    if (!hash_equals($mac, hash_hmac('sha256', trim($submitted), $pepper))) return false;
    $consume = $pdo->prepare("UPDATE otp SET consumed = 1 WHERE phone = ? AND mac = ? AND consumed = 0");
    $consume->execute([$phone, $mac]);
    return $consume->rowCount() === 1;
}
MAX_ATTEMPTS = 5

def verify_otp(phone, submitted)
  # 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
  row = DB.exec_params(
    "UPDATE otp SET attempts = attempts + 1
     WHERE phone = $1 AND consumed = false AND expires_at > $2 AND attempts < $3
     RETURNING mac",
    [phone, Time.now.to_i, MAX_ATTEMPTS]
  ).first
  # expired, already used, locked out, or never sent
  return false unless row

  # 2. Compare in constant time; consume on success — exactly one row must change.
  given = OpenSSL::HMAC.hexdigest("SHA256", PEPPER, submitted.strip)
  return false unless OpenSSL.secure_compare(row["mac"], given)

  DB.exec_params("UPDATE otp SET consumed = true WHERE phone = $1 AND mac = $2 AND consumed = false", [phone, row["mac"]]).cmd_tuples == 1
end
static final int MAX_ATTEMPTS = 5;

boolean verifyOtp(String phone, String submitted) throws Exception {
    try (Connection conn = dataSource.getConnection()) {
        // 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
        String mac;
        try (PreparedStatement charge = conn.prepareStatement(
                "UPDATE otp SET attempts = attempts + 1 " +
                "WHERE phone = ? AND consumed = false AND expires_at > ? AND attempts < ? RETURNING mac")) {
            charge.setString(1, phone);
            charge.setLong(2, Instant.now().getEpochSecond());
            charge.setInt(3, MAX_ATTEMPTS);
            ResultSet rs = charge.executeQuery();
            // expired, already used, locked out, or never sent
            if (!rs.next()) return false;
            mac = rs.getString("mac");
        }

        // 2. Compare in constant time; consume on success — exactly one row must change.
        if (!MessageDigest.isEqual(mac.getBytes(StandardCharsets.UTF_8),
                                   codeMac(submitted.strip()).getBytes(StandardCharsets.UTF_8))) return false;
        try (PreparedStatement consume = conn.prepareStatement(
                "UPDATE otp SET consumed = true WHERE phone = ? AND mac = ? AND consumed = false")) {
            consume.setString(1, phone);
            consume.setString(2, mac);
            return consume.executeUpdate() == 1;
        }
    }
}
const int MaxAttempts = 5;

async Task<bool> VerifyOtpAsync(string phone, string submitted)
{
    // NpgsqlDataSource
    await using var conn = await dataSource.OpenConnectionAsync();

    // 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
    await using var charge = new NpgsqlCommand(
        "UPDATE otp SET attempts = attempts + 1 " +
        "WHERE phone = $1 AND consumed = false AND expires_at > $2 AND attempts < $3 RETURNING mac", conn);
    charge.Parameters.Add(new() { Value = phone });
    charge.Parameters.Add(new() { Value = DateTimeOffset.UtcNow.ToUnixTimeSeconds() });
    charge.Parameters.Add(new() { Value = MaxAttempts });
    // expired, already used, locked out, or never sent
    if (await charge.ExecuteScalarAsync() is not string mac) return false;

    // 2. Compare in constant time; consume on success — exactly one row must change.
    if (!CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(mac), Encoding.UTF8.GetBytes(CodeMac(submitted.Trim()))))
        return false;
    await using var consume = new NpgsqlCommand(
        "UPDATE otp SET consumed = true WHERE phone = $1 AND mac = $2 AND consumed = false", conn);
    consume.Parameters.Add(new() { Value = phone });
    consume.Parameters.Add(new() { Value = mac });
    return await consume.ExecuteNonQueryAsync() == 1;
}
const maxAttempts = 5

func verifyOTP(phone, submitted string) (bool, error) {
	// 1. Charge the attempt — only if the code is live, unconsumed, and under the attempt cap.
	var mac string
	err := db.QueryRow(
		`UPDATE otp SET attempts = attempts + 1
		 WHERE phone = $1 AND consumed = false AND expires_at > $2 AND attempts < $3
		 RETURNING mac`,
		phone, time.Now().Unix(), maxAttempts).Scan(&mac)
	if err == sql.ErrNoRows {
		// expired, already used, locked out, or never sent
		return false, nil
	} else if err != nil {
		return false, err
	}

	// 2. Compare in constant time; consume on success — exactly one row must change.
	if !hmac.Equal([]byte(mac), []byte(codeMAC(strings.TrimSpace(submitted)))) {
		return false, nil
	}
	res, err := db.Exec("UPDATE otp SET consumed = true WHERE phone = $1 AND mac = $2 AND consumed = false", phone, mac)
	if err != nil {
		return false, err
	}
	n, _ := res.RowsAffected()
	return n == 1, nil
}

Table for reference: otp(phone PRIMARY KEY, mac TEXT, expires_at BIGINT, attempts INT, consumed BOOLEAN). One live code per phone keeps the logic simple; a resend replaces the row.


Step 3: Throttle

OTP endpoints are a favorite target for SMS pumping: an attacker scripts thousands of "send me a code" requests to premium-rate or fraud-ring numbers, and you pay for every one.

LimitSuggested value
Sends per phone number3 per 10 minutes, 10 per day
Sends per IP / session5 per 10 minutes
Resend cooldown30–60 seconds, enforced server-side
New numbers per account per dayLow single digits for most products

Also watch for a burst of sends to sequential numbers (a classic pumping signature), and alert on daily credit consumption (GET /v1/credits) crossing a threshold.


Gotchas

  • Delivery isn't instant everywhere. Most codes arrive in seconds; some carriers and some number types are slower. Show a "didn't get it? resend in 0:45" countdown rather than letting users hammer the button.
  • Number type matters. Short codes and verified toll-free numbers have the highest OTP throughput and the least filtering. If OTP is a core flow, talk to EZ Texting about the right number for it.
  • Don't put links in OTP messages. They lower deliverability and train users to tap links in "security" texts.
  • Don't reuse codes across channels or users. One code, one number, one use.
  • Log sends without logging codes. Keep the message id and the phone for audit; never write the code, the MAC, or the pepper to logs.
  • Not every 400 is the user's fault. Running out of credits or an account that still needs verification also returns 400. The samples check the error text so a user isn't told their number is wrong when the problem is on your side; alert yourself on those, and turn on auto-refill so codes don't stop when credits run out.
  • Users who opted out. Someone who replied STOP to any of your texts can't receive codes: the send returns 400 "The phone numbers that you're sending to are opted out". Tell them how to opt back in (text JOIN, or one of your keywords, to your number), then let them request a new code.
  • If a send's outcome is unknown (timeout or 5xx from POST /v1/messages), don't replay it. Let the user request a fresh code; the old row is replaced.
  • Landlines and VoIP. Most landlines and some VoIP numbers can't receive texts. The send is accepted and the message shows as bounced later. If a user reports no code, check /responses/delivery for the message ID before assuming a bug.

Related

API reference


Did this page help you?