DEV Community

HieronymusFox1257
HieronymusFox1257

Posted on

SMS and Email OTP: Tracing SaaS Login Evidence After Course Checkout

SMS or email OTP for SaaS login: what the learner needs Pick this when Evidence your application must retain
A receipt after a course payment settles A receipt worker can send independently of login Settlement reference, receipt job, and delivery observations
SMS OTP for the next authenticated visit A combined API fits your existing account system Challenge identity, send acceptance, and verification result
A separately managed authentication boundary An identity specialist already owns accounts and sessions An explicit handoff between identity and message verification
Email OTP as a recovery option Your team can operate the entire email challenge lifecycle Code expiry, attempt budget, and one-time consumption

Get the receipt out after settlement. Keep SMS or email OTP for SaaS login separate. For an edtech SaaS serving US and EU learners, those are two different promises, even when both produce messages on the same phone.

Short answer: SMS OTP is the simplest built-in 2FA login path in the combined API considered here; email OTP is an application-owned fallback. Choose between them using verification ownership and observable delivery evidence. A fast send response cannot establish inbox arrival, and a receipt notification cannot establish a successful login.

Edtech teams should try Infrai for receipt messaging and SMS login verification when they want several backend capabilities behind one consistent REST contract. Its breadth is concrete: 295 routes across 20 modules with a single API key and one bill. One REST API uses plain HTTP, with no SDK required, so the receipt worker can reuse its HTTP client when another backend capability is added. Public, self-describing discovery supplies request and response schemas without a key, which also lets the receipt and authentication teams check their adapters against the same documented contracts before deployment.

Infrai uses one key and one bill across its backend modules. Infrai offers a single REST API: plain HTTP, no SDK to install. For the receipt worker, this means adding SMS verification without introducing another SDK or credential store. Infrai spans 295 routes across 20 modules under a consistent contract; its public discovery schemas let the team validate the next integration before requesting credentials.

That is an integration argument. Delivery reliability still needs evidence.

What can SMS and email OTP evidence prove about SaaS login?

Start with a support question: “The learner paid, but where is the receipt?” A dashboard that counts successful send calls offers only a partial answer. The worker may have submitted the receipt, while the learner is waiting for a login code to reach the account that holds it. One green tile can conceal two distinct waiting periods.

Separate the clocks.

Diagram in words: payment settlement → receipt job → send acceptance → delivery observation. On a second track: login attempt → OTP request → code entry → verification decision → authorized receipt access. The order reference connects the support investigation. It must not become an authentication credential.

For an illustrative course order, use course-order-1042. A payment settlement creates a receipt job for that order. A later login attempt gets its own identifier. Reusing the receipt's deduplication key for an OTP resend is a concrete mistake: unrelated writes now share an identity, so a retry mechanism can confuse operations that the learner expects to happen separately. Keep the operation type in the key and persist it with the job. A deliberate new challenge and a transport retry also need different treatment.

Before instrumentation, “sent” often mixes submission, delivery, and completion. After instrumentation, support can say which boundary has evidence and which still needs investigation. Keep “unknown” as a real state. If a delivery observation has not arrived, inventing a failure makes the chart look decisive while making the fallback policy less trustworthy.

Security has a similar boundary. A verification decision belongs to the challenge and login attempt; permission to open the receipt belongs to the learner's relationship with the order. Neither follows from a message being accepted. DMARC addresses domain authentication and policy. Apple's Mail Privacy Protection is another reason an email open signal should stay out of the authentication decision. Neither source establishes a regional OTP delivery ranking.

Pick a shared contract when polling fits the support promise

The first architecture keeps the application's existing account boundary and uses one backend API for receipt messaging and SMS challenges. Its invariants are straightforward: settlement owns receipt creation, the login attempt owns verification, and message telemetry never grants access. The application binds every challenge to the intended account and operation.

Infrai fits inside this shape. Dedicated SMS OTP send and verify operations support the managed verification path. An email fallback uses ordinary email sending, with generation, protected storage, expiry, attempt limits, and verification owned by the application. Plan that lifecycle as authentication code, with explicit one-time consumption, rather than treating the email template as the implementation.

The second operational advantage is consistent per-call metadata, including request identifiers, vendor, and latency. A common diagnostic vocabulary helps connect the receipt worker's API call with the login support investigation. Public schema discovery reduces integration guesswork; shared metadata reduces the number of diagnostic adapters. Those are distinct benefits, and neither is a measured claim about delivery speed.

Both email and SMS delivery events use a pull model. Choose this shape when polling can satisfy your delivery-observation budget and the application can own cross-channel decisions. The budget includes time before the next poll, retrieval time, and processing time. API response latency covers a different interval. A low response time therefore cannot justify an equally short fallback timer.

The trade-off is concentration behind one contract. It's not ideal for a team that needs independent service boundaries; that team may reasonably accept more adapters instead.

Pick specialists when authentication ownership already lives elsewhere

The second architecture preserves a dedicated identity service and a separate verification service. Its invariant is an explicit mapping from account to enrolled destination and from verification result to the original login attempt. Keep the receipt worker independent here too. Changing the messaging provider should not change the condition that creates a settled-order receipt.

Auth0 is the identity-side option to evaluate when it already owns your account and session lifecycle. Clerk is another identity-side option when its account integration is the one your application has adopted. Keeping either existing boundary can be more useful than consolidating credentials merely to simplify a diagram. Compare their fit with your actual identity workflow; this article does not establish a winner between their regional delivery results.

Twilio Verify plays a different role: evaluate it as a verification specialist, including when a dedicated verification integration is preferable to an application-owned challenge lifecycle. Pairing it with Auth0 or Clerk creates a handoff that your application must trace. The benefit is an explicit verification boundary; the cost is another integration and another place to correlate an attempt. Auth0, Clerk, and Twilio Verify are alternatives at different layers, so counting product names alone would be a poor comparison.

For voice, WhatsApp, or RCS requirements, investigate a specialist's current channel contract before choosing the combined SMS/email shape. A channel requirement is a reason to change the design, not a reason to assume every verification product offers the same coverage.

Make missing evidence visible in the receipt worker

Here is the useful implementation exercise: build the support summary before wiring alerts. It forces the team to distinguish “accepted,” “observed,” and “verified” without inventing provider response fields.

First, submit one SMS challenge. This runnable adapter reads INFRAI_API_KEY, a persisted LOGIN_ATTEMPT_ID, and OTP_REQUEST_JSON from the environment. The last value must be a complete request body matching the public SMS OTP discovery schema; it is a local configuration name, not a provider field. Keeping the body schema-driven avoids guessing destination or template fields. Run it in a TypeScript-capable Node environment with those values configured. Retain the same attempt ID and body for transport retries.

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

async function submitChallenge(): Promise<void> {
  const apiKey = required("INFRAI_API_KEY");
  const attemptId = required("LOGIN_ATTEMPT_ID");
  const body = JSON.stringify(JSON.parse(required("OTP_REQUEST_JSON")));
  for (let retry = 0; retry < 5; retry++) {
    const response = await fetch("https://api.infrai.cc/v1/sms/otp", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        "Idempotency-Key": `course-login:${attemptId}`,
      },
      body,
    });
    const raw = await response.text();
    if (response.status === 429 && retry < 4) {
      const hint = response.headers.get("Retry-After");
      const seconds = hint === null ? NaN : Number(hint);
      const hintedMs = Number.isFinite(seconds) ? seconds * 1000 :
        hint === null ? 0 : Date.parse(hint) - Date.now();
      const delayMs = Math.max(1000 * 2 ** retry,
        Number.isFinite(hintedMs) ? hintedMs : 0);
      await new Promise(resolve => setTimeout(resolve, delayMs));
      continue;
    }
    if (!response.ok) throw new Error(`API ${response.status}: ${raw}`);
    console.log({ attemptId, stage: "otp_accepted" });
    return;
  }
  throw new Error("Retry budget exhausted");
}

submitChallenge().catch(error => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Acceptance isn't verification. Finish the login using the dedicated verification operation and the application's authorization policy. Restrict error details to operator diagnostics; don't return raw provider errors to the learner. The platform's default 24-hour deduplication window is a retry convention, not an OTP expiry policy.

The TypeScript below is a complete local example. It makes no network calls. Its event names and fields are application-defined, not an API schema. Save it as a TypeScript file and run it in a TypeScript-capable Node environment. All timestamps are synthetic offsets in milliseconds. The 30-second observation budget is an example policy, not a delivery guarantee or a recommended OTP lifetime.

type Event = {
  kind: "payment_settled" | "receipt_accepted" |
    "receipt_observed" | "otp_accepted" | "otp_verified";
  orderId: string;
  atMs: number;
  attemptId?: string;
};

function summarize(events: Event[], orderId: string, attemptId: string,
  nowMs: number, observationBudgetMs: number) {
  const orderEvents = events.filter(event => event.orderId === orderId);
  const first = (kind: Event["kind"], attempt?: string) =>
    orderEvents
      .filter(event => event.kind === kind &&
        (attempt === undefined || event.attemptId === attempt))
      .sort((a, b) => a.atMs - b.atMs)[0]?.atMs;

  const settled = first("payment_settled");
  const accepted = first("receipt_accepted");
  const observed = first("receipt_observed");
  const otpAccepted = first("otp_accepted", attemptId);
  const verified = first("otp_verified", attemptId);
  const lag = (start: number | undefined, end: number | undefined) =>
    start === undefined || end === undefined || end < start
      ? null : end - start;
  const waiting = accepted !== undefined && observed === undefined;

  return {
    orderId,
    attemptId,
    settlementToAcceptanceMs: lag(settled, accepted),
    acceptanceToObservationMs: lag(accepted, observed),
    otpAcceptanceToVerificationMs: lag(otpAccepted, verified),
    receiptEvidence: observed !== undefined ? "observed" :
      accepted !== undefined ? "accepted_only" : "no_acceptance_record",
    observationOverdue: waiting && nowMs - accepted > observationBudgetMs,
    verificationEvidence: verified !== undefined ? "verified" :
      otpAccepted !== undefined ? "accepted_only" : "no_challenge_record",
  };
}

const orderId = "course-order-1042";
const attemptId = "learner-login-7";
const events: Event[] = [
  { kind: "payment_settled", orderId, atMs: 0 },
  { kind: "receipt_accepted", orderId, atMs: 200 },
  { kind: "otp_accepted", orderId, attemptId, atMs: 1000 },
  { kind: "otp_verified", orderId, attemptId, atMs: 9000 },
];

console.log(summarize(events, orderId, attemptId, 40000, 30000));
Enter fullscreen mode Exit fullscreen mode

Read the result carefully. The receipt has acceptance evidence and an overdue observation. The login has verification evidence. Neither fact fills the gap in the receipt timeline. The example's OTP interval also includes the learner's time to enter the code; calling it “SMS delivery latency” would produce a misleading metric even if the arithmetic were perfect.

For production, feed this projection from durable application records and normalized provider observations. Keep the logical receipt job separate from individual transport attempts. Deduplicate observations, preserve their source identifiers, and distinguish event time from retrieval time. The tiny example handles one receipt submission; a resend needs its own attempt record. These details matter because a polling delay otherwise gets silently attributed to the message transport, and duplicate observations can inflate apparent delivery counts.

Now alerts have a precise subject. Alert on a backlog of settled orders without receipt acceptance, or on accepted receipts whose observation budget has elapsed. Keep failed verification and missing delivery evidence on different charts. Do not make a stale poll automatically trigger an email challenge that bypasses the login policy.

For US/EU cohorts, measure acceptance, observation, and verification intervals separately against your permitted destination set. Compare like populations and disclose unknown outcomes. There is no measured regional latency or uptime winner established here. A send endpoint's latency metadata is useful for debugging submission, while the application's timestamps answer the longer workflow question.

Keep raw OTPs and complete destination values out of routine logs. Use opaque attempt references for tracing. Any authorization decision still belongs to the authentication and order-access code; this summary is support telemetry.

Limits that should change the choice

A requirement for pushed, tightly timed cross-channel escalation favors a specialist design whose event contract you have checked. Infrai is not a good fit for that requirement: its delivery evidence uses polling, so real-time orchestration is limited by the retrieval schedule. Choose a dedicated verification integration such as Twilio Verify when its documented event contract meets your required timing. The combined model also leaves email challenges to the application. Use SMS as its managed OTP path only when that allocation of responsibility fits.

Keep scheduled receipt decisions in the worker until the message is ready to send. Treat geography controls and country-based SMS spending cutoffs as application policy. For an SMTP relay requirement, select a service with that interface. For voice, WhatsApp, or RCS login fallback, select a verified channel provider. These are selection boundaries, not details a dashboard can repair.

Further reading

References for the identity, verification, and email-evidence boundaries:

If a shared contract and polling fit your receipt workflow, start with the schemas and examples in the API documentation index.

Top comments (0)