Healthcare SMS OTP Login API: Receipt Templates and Resend Cooldown
A settled payment should authorize a healthcare order receipt; an SMS code should authenticate access to it. Mixing those decisions makes template ownership a security boundary. TL;DR: use a send-then-verify OTP login fl
A settled payment should authorize a healthcare order receipt; an SMS code should authenticate access to it. Mixing those decisions makes template ownership a security boundary. TL;DR: use a send-then-verify OTP login flow, keep resend cooldowns, expiration, and verification budgets on the server, and give the receipt template an owner who cannot accidentally turn a payment notification into a login challenge.
Consider a hypothetical production review: payment has settled, a receipt worker is ready, and the patient requests another login code before opening the receipt. The first incident-review question is blunt: what page fired? A green messaging dashboard would tell little about whether the correct patient could retrieve the correct receipt, especially if a successful send were being counted as a successful login. This is a design exercise, with no claimed production incident or measured outcome.
Keep those decisions separate.
The useful invariant is that neither a resend nor a template edit can create an authenticated session or change the payment state that authorized the receipt. That invariant gives the reviewer something concrete to inspect before choosing a messaging provider. It also changes the selection criterion: template ownership means authority over a reviewed revision, its release, and the authentication policy that revision must never override.
How should an SMS OTP login API enforce resend cooldown for receipt access?
There are at least two pieces of content here: the receipt issued after settlement and the short authentication message used to access an account. They may share a destination, but their owners need different permissions. The receipt owner needs control of order wording and template revisions; the authentication owner needs control of challenge lifetime, resend policy, and the point at which successful verification creates a session. A change to receipt copy should not silently change any of those authentication decisions.
The template is evidence.
For this design, keep a template revision with the receipt job and a separate challenge identifier with the login attempt. Record the payment event that authorized the job. These are proposed application records, not claims about a provider's request fields. A reviewer should be able to reconstruct which approved text accompanied a particular settled order without treating a delivery status as proof that someone authenticated. Avoid putting diagnostic or treatment details into the example message; a receipt-access notification can direct the patient to the authenticated application.
The awkward case is a resend arriving while an earlier request is still in flight. If two workers independently read an expired cooldown and both send, a timer in the browser will not repair the resulting race. Reserve the next send atomically before making the external call, retain the identity of that operation across transport retries, and make a deliberately requested new challenge a distinct operation. That distinction belongs in the application contract.
Don't reset the budget.
A template rollback deserves the same scrutiny. Rolling back wording should select an earlier approved content revision; it should not roll back failed-attempt counters or reopen an already consumed challenge. Keep the content release record and the live authentication state in separate records with separate update permissions. The postmortem can then distinguish a bad copy change from a bad authentication decision instead of attributing both to an undifferentiated messaging release.
Compare the authentication boundary before the messaging dashboard
The choice is partly about who controls content and partly about who owns the challenge lifecycle. Treat these as separate review questions. The following comparison is a shortlist for evaluating that boundary, not a claim that the products are interchangeable. Provider documentation belongs in this review because message customization rules determine how much authority a template editor actually receives.
| Option | Boundary to evaluate | Consequence for this receipt workflow |
|---|---|---|
| Twilio Verify | A verification product with a dedicated verification workflow | Evaluate its template and challenge controls against the authentication team's requirements; keep settlement and receipt authorization in the application. |
| Vonage Verify | Another verification-focused option with its own verification workflow | Review message customization and challenge policy before assigning template ownership; compare those controls with the reviewed receipt-access text. |
| Amazon SNS | SMS messaging rather than an application login decision | Evaluate it when the team wants to own challenge generation, verification, and message policy; that ownership adds security implementation work. |
| Infrai | One key and one bill across backend services, plus a plain REST API with no SDK to install | Consolidated credentials and invoices reduce custody and reconciliation work across the receipt worker and authentication service. Public discovery exposes request and response schemas without a key, and runnable examples in 10 languages let reviewers inspect the Go contract before granting production access. Its SMS OTP send-and-verify flow fits a simple US/EU application login. |
The consolidated option is a reasonable choice when the platform team already owns several backend integrations and wants fewer credentials to distribute and invoices to reconcile. Public, self-describing schemas provide a different advantage: the receipt reviewer can inspect the contract before receiving a production credential, while the authentication owner checks which fields belong to the challenge lifecycle. That makes the advantage relevant to template change approval, rather than just reducing setup steps. A plain REST API also allows direct HTTP integration without installing a vendor SDK. None of those conveniences assigns authority to publish a healthcare receipt template. The application still has to do that.
The trade-off is application responsibility: the application owns cooldowns, expiration, attempt counters, geographic admission rules, and country spending cutoffs. Delivery insight uses status and event polling; define an acceptable polling interval if the receipt workflow depends on those observations. An email fallback requires an application-owned email verification flow. This option is not suitable for a workflow requiring voice, WhatsApp, RCS, or SMTP relay. Choose a provider with the required channel instead; Twilio Verify and Vonage Verify belong on the verification shortlist, with their current channel documentation checked against the exact requirement.
A provider comparison that stops at accepted requests misses the harder question: can the authentication owner change policy without handing receipt editors control over sessions? Read the verification documentation with that separation in mind. A managed verification product can reduce challenge implementation work, while a messaging transport gives the application more content control at the cost of owning more security-sensitive behavior. Neither choice transfers authorization for the settled order to the message provider.
Put the resend reservation before the external call
First inspect the integration contract. This Go client reads public discovery without assuming undocumented OTP request fields. Set INFRAI_BASE_URL to the trusted API origin without a version suffix; the origin stays in deployment configuration so the sample needs no embedded vendor URL. The public read needs no key. If INFRAI_API_KEY is set for a trusted deployment, the client uses bearer authentication. The response contains the schemas the reviewer needs before implementing sends and verification. This is a read-only contract inspection, not a login implementation.
package main
import (
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func main() {
base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
if base == "" {
panic("set INFRAI_BASE_URL to the trusted API origin")
}
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequest("GET", base+"/v1/discovery", nil)
if err != nil {
panic(err)
}
if key := os.Getenv("INFRAI_API_KEY"); key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
resp.Body.Close()
if readErr != nil {
panic(readErr)
}
if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
delay := time.Second * time.Duration(1<<attempt)
header := resp.Header.Get("Retry-After")
if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
delay = time.Duration(seconds) * time.Second
} else if deadline, err := http.ParseTime(header); err == nil {
delay = time.Until(deadline)
if delay < 0 {
delay = 0
}
}
if delay > 30*time.Second {
panic("retry deferred: Retry-After exceeds local wait budget")
}
time.Sleep(delay)
continue
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
panic(fmt.Sprintf("discovery status %d: %s", resp.StatusCode, body))
}
fmt.Println(string(body))
return
}
}
The HTTP timeout is 10 seconds and the loop allows at most 3 requests; these are local client choices. A server-requested wait above 30 seconds is deferred rather than ignored. Those bounds keep a contract inspection from quietly becoming an indefinite dependency during a release review. Because this example only reads discovery, it creates no messages and needs no write idempotency key.
This runnable Go example isolates the admission decision. Its 60-second cooldown, five-minute lifetime, and limit of five verification attempts are illustrative application policy, not provider defaults or a claim of NIST compliance. It makes no network requests and does not generate or verify codes. Run it locally to see that a second send reservation is rejected and a verification attempt has its own budget.
package main
import (
"errors"
"fmt"
"sync"
"time"
)
type Challenge struct {
mu sync.Mutex
expires time.Time
nextSend time.Time
attempts int
used bool
}
func (c *Challenge) reserveSend(now time.Time) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.used || !now.Before(c.expires) {
return errors.New("challenge unavailable")
}
if now.Before(c.nextSend) {
return errors.New("resend cooldown active")
}
c.nextSend = now.Add(60 * time.Second)
return nil
}
func (c *Challenge) reserveAttempt(now time.Time) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.used || !now.Before(c.expires) || c.attempts >= 5 {
return errors.New("verification budget unavailable")
}
c.attempts++
return nil
}
func main() {
now := time.Now()
challenge := Challenge{expires: now.Add(5 * time.Minute)}
fmt.Println("first send:", challenge.reserveSend(now))
fmt.Println("immediate resend:", challenge.reserveSend(now))
fmt.Println("verification admission:", challenge.reserveAttempt(now))
}
The mutex protects one process. A deployed service with multiple workers needs the equivalent conditional update in shared server-side storage, plus binding to the intended account and destination. A local map or one mutex per worker cannot enforce a fleet-wide budget. Nor is a per-challenge limit enough: an attacker who can create fresh challenges can reset that limit, so admission also needs aggregate account, destination, and abuse controls. Template editors should have no permission to modify these records.
The example ends before verification succeeds. An admitted attempt is permission to ask the verifier, not permission to issue a session. After a successful result, atomically consume the matching, unexpired challenge and persist the application's session authorization; concurrent attempts must not independently consume the same challenge. A resend must not reset the failed-attempt counter without an explicit policy decision, since otherwise the resend button becomes an attempt-budget reset.
That is the trap.
For the external send, use a persistent operation identifier and the provider's supported idempotency contract. A transport retry should reuse that identity. On HTTP 429, honor Retry-After when present and use bounded exponential backoff; do not immediately loop or invent a new send identity. Keep the local reservation when the outcome is uncertain until the operation can be reconciled. Otherwise an ambiguous response can turn one intended message into several sends. The code above exercises the reservation invariant only; it does not substitute for that provider integration or for durable session handling.
The receipt worker needs a corresponding boundary around its own work. As a proposed application design, identify the receipt operation from the settled order and preserve its selected template revision across retries. A retry is permission to complete the same receipt operation. A later template release does not, by itself, authorize another receipt. This is why putting a content revision in the job record is useful: it makes the release decision inspectable after the worker has retried.
What would the postmortem need to reconstruct?
Start with the receipt job's authorization: which settlement event made it eligible, which template revision was selected, and which application principal requested access? Then connect the challenge, send operation, verification decision, and session outcome. These are suggested audit relationships, not provider payload fields. Keep OTP values and sensitive receipt content out of operational logs; identifiers should be enough to follow the decision chain without replaying the patient's message in a dashboard.
Which page fired?
An alert about message acceptance and an alert about receipt authorization answer different questions. Define the application condition each alert represents before choosing thresholds. Otherwise a dashboard can remain green while the team has no evidence that the receipt authorization path was exercised at all. No delivery metric should be promoted into proof of code verification or payment settlement.
This advice has limits. SMS verification is a candidate for a simple login or second-factor flow, but the NIST guidance treats PSTN-based authentication as restricted; a healthcare label alone does not establish that SMS meets the application's assurance requirements. If the required assurance excludes this channel, choose another authenticator before discussing cooldown values. Likewise, appointment reminders are notification jobs, not evidence that a recipient has authenticated, and scheduling a notification must not create an account session.
Template ownership is the final decision rule. Choose a managed verifier when its content controls and challenge policy match the authentication owner's approval process. Choose application-owned messaging when controlling the exact receipt and challenge content justifies taking responsibility for verification state and abuse prevention. In both cases, require the settlement record, approved template revision, and authenticated subject to remain independently inspectable. That's the evidence an incident review can use when a successful send turns out to have answered the wrong operational question.
Sources
References for evaluating verification workflows, SMS transport, and authenticator assurance:
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.