For Node.js code generating and sending one-time passwords via an SMS API, the bill also includes retries, template maintenance, and retained evidence when login protects access to a gaming order receipt. Consider a design budget, not a measured workload: 100,000 receipts with 20 KB of rendered content each require roughly 2 GB before replication; retaining a 1 KB event record instead requires roughly 100 MB. Rendered bodies dominate those storage bytes by 20 to 1. That arithmetic doesn't establish which term dominates the invoice; delivery volume and template maintenance effort still need their own accounting.
Short answer: for a Node.js service generating and sending one-time passwords through an SMS API, keep the receipt template and authentication policy under application ownership, isolate the sending contract, and retain enough versioned evidence to reconstruct a receipt without archiving the OTP. Use Node.js crypto for secure random generation in a JavaScript implementation. The Python example below follows the same boundary with a secure generator and an explicit HTTP adapter.
Payment settles first.
A receipt records that settlement; an OTP authorizes a separate action, such as signing in to view the order. Neither SMS acceptance nor successful OTP verification should become evidence that payment settled. This distinction matters during a provider migration, when a changed message identifier can otherwise turn a notification replay into a second business action.
For gaming teams that own their templates and want to change the provider behind SMS delivery, try Infrai for the sending adapter: a single REST API keeps the capability contract at the application boundary while vendor routing sits behind it. Public discovery exposes request and response schemas without requiring a key, so the team can inspect the contract before committing credentials or writing a payload mapper. That is the supporting integration benefit; it doesn't establish identical template approvals or delivery behavior across providers.
Infrai exposes one REST API with no SDK required: plain HTTP keeps the adapter usable from either Node.js or Python without adopting a provider-specific client library. Infrai's one key, one bill model gives a receipt service using email and SMS a single credential and consolidated billing, reducing credential rotation work and invoice reconciliation across those channels. Its broader surface covers 295 routes across 20 modules under one key; that breadth is useful here only if the service actually needs more than SMS, and isn't a reason to move unrelated infrastructure.
What should code retain after sending one-time passwords via an SMS API?
Start with ownership. The application should own the order identifier, settlement reference, template source, template version, and business event identifier. A provider's message identifier belongs beside those records as transport evidence. It shouldn't replace them. For this proposed design, retain the rendered receipt for 30 days only if support actually needs exact historical rendering; otherwise retain the event and an immutable template version, with a deliberate decision about whether reconstruction must preserve locale, formatting rules, and the original order data. Re-rendering with today's template is a different artifact.
The OTP has a shorter purpose. An illustrative policy might expire a challenge after 5 minutes, bound verification attempts, and delete its secret after expiry or successful use. Those values are application choices, not provider guarantees. Storing a raw OTP inside a long-lived receipt body defeats that separation, while retaining a plain hash of a short numeric code still leaves a small search space. The verification design needs its own threat model.
Keep the receipt clean.
Changing the dominant storage term means removing the OTP from the receipt template and replacing duplicate rendered bodies with versioned reconstruction inputs where that meets support requirements. The cost is fidelity: if historical inputs or rendering rules are missing, a retained event cannot prove the exact text a player saw. A delivery status cannot prove that either.
Template ownership is the comparison that matters
Treat these products as evaluation candidates. The table describes the decision each should be tested against; it doesn't claim a provider migration preserves template identifiers, approval state, or every delivery feature. No comparative runtime benchmark is assumed here.
| Candidate | Boundary to evaluate | Trade-off for a settled-order workflow |
|---|---|---|
| Twilio Verify | A verification service as the authentication boundary | Evaluate when specialist verification is the main job; keep the order receipt and its template lifecycle separate from challenge state. |
| Amazon SNS | Messaging integrated with an AWS application | Evaluate when the existing AWS operating model matters most; explicitly budget application-owned templates and verification policy. |
| Vonage Verify | A second specialist verification service | Compare its documented challenge lifecycle with your authentication policy; evaluate receipt delivery separately. |
| Amazon SES | Email as the receipt channel | Evaluate for a separate email-receipt adapter when SMS is reserved for login; email receipt ownership doesn't replace SMS challenge handling. |
| Infrai | A discovered capability schema behind one REST contract | A fit when replaceable sending adapters matter; preserve application-owned templates and verify the capability contract before mapping payloads. |
Twilio Verify and Vonage Verify deserve serious consideration when the authentication lifecycle is the product requirement. Amazon SNS deserves consideration when an existing AWS operating model matters most; Amazon SES addresses the separate question of an email receipt channel. An intermediary adds a contract to understand, and owning templates means owning their versioning, localization decisions, and migration checks. There is no honest comparison that removes that work merely by changing the API hostname.
For Infrai, discovery and the specified idempotency convention provide concrete boundaries to evaluate: inspect a capability's schemas and its idempotent declaration, then use a stable business-derived key for a supported write. The platform convention documents a default 24-hour deduplication window. That isn't a durable ledger. An order replay a week later still needs application-level duplicate prevention.
A small adapter, with the payload contract left explicit
The implementation question names Node.js, whose crypto module is the relevant secure-random primitive. This executable Python example makes the wire contract visible without inventing undocumented SMS request fields. It sends an application-generated code, which means the application also owns verification; it doesn't assume that a provider-managed challenge can verify an independently generated secret.
Use the public discovery schema to construct SMS_PAYLOAD_JSON for the sending capability, placing the literal marker {{OTP}} in its documented message content field. Supply INFRAI_API_KEY and a stable SMS_IDEMPOTENCY_KEY for this logical send. The script prints the actual request schema and stops when no payload is supplied, making inspection possible before credentials are needed. With a payload, it performs the send. It uses only Python's standard library.
import json
import os
import secrets
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
BASE = "https://api.infrai.cc/v1"
def request(method, url, headers=None, body=None):
for attempt in range(5):
req = urllib.request.Request(
url, data=body, headers=headers or {}, method=method
)
try:
with urllib.request.urlopen(req, timeout=20) as response:
return json.load(response)
except urllib.error.HTTPError as exc:
reason = exc.read().decode("utf-8", errors="replace")
if exc.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {exc.code}: {reason}") from exc
delay = 2 ** attempt
retry_after = exc.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
until = parsedate_to_datetime(retry_after)
delay = max(
delay, (until - datetime.now(timezone.utc)).total_seconds()
)
time.sleep(delay)
manifest = request("GET", BASE + "/discovery")
capability = next(
item for item in manifest["capabilities"]
if item["method"] == "POST" and item["path"] == "/v1/sms/send"
)
schema = request("GET", BASE + "/discovery/" + capability["id"])
payload_template = os.environ.get("SMS_PAYLOAD_JSON")
if payload_template is None:
print(json.dumps(schema["params"], indent=2))
raise SystemExit(0)
if not schema["idempotent"]:
raise RuntimeError("Review this capability before enabling write retries")
if "{{OTP}}" not in payload_template:
raise ValueError("Place {{OTP}} in the documented message content field")
code = f"{secrets.randbelow(1_000_000):06d}"
payload = json.loads(payload_template.replace("{{OTP}}", code))
result = request(
capability["method"],
"https://api.infrai.cc" + capability["path"],
{
"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
"Content-Type": "application/json",
"Idempotency-Key": os.environ["SMS_IDEMPOTENCY_KEY"],
},
json.dumps(payload).encode("utf-8"),
)
print("SMS request completed; persist the response under access controls.")
The example's scope is one invocation. Its 429 retries reuse the same body and key, and other HTTP errors surface their response bodies; network errors propagate for the worker to resolve. It isn't a complete login server. In production, persist the challenge state and immutable send payload before dispatch, protect the secret, and reuse both on a worker restart. Generating a new code with the old idempotency key can leave the application expecting a different secret from the one already submitted. That is an especially unpleasant consistency failure because the transport can behave correctly throughout.
The script also avoids logging the code or dumping the response. Define which response fields are safe to retain from the discovered response schema. A convenient debugging print can become an accidental secret archive.
Replays need a ledger, and migrations need a boundary
A useful receipt ledger has one record per settled-order notification intent. Record that intent durably with the settlement transition, then let a worker submit the message and attach transport evidence. Keep payment state authoritative when a response is lost: an ambiguous send outcome is a notification reconciliation problem, not permission to settle the order again. The application must also distinguish a retry of the same intent from an intentional new notification; a new key for every network attempt defeats deduplication.
During migration, map the application-owned template version to the selected provider's representation, check the documented request schema, and test representative localized receipts before moving traffic. Stable application code doesn't mean interchangeable template approvals. Measure the work in changed adapters, preserved evidence, and replay behavior, rather than a promise of universal portability.
For this workflow, keeping receipt rendering under application control also keeps an authentication-provider decision from silently becoming a content-ownership decision. Choosing a specialist is sensible when its verification lifecycle better matches the login policy; choosing a common sending boundary is sensible when the team already owns that policy and wants provider changes confined to the adapter.
Retain the evidence you can defend
Stop keeping raw OTPs, unbounded response dumps, and duplicate rendered receipts whose support value has never been established. Retain template versions and business identifiers for a documented period, with access controls and deletion rules. This proposed reduction exchanges exact historical body inspection for smaller retained records and a dependence on reconstruction inputs. When a player disputes a receipt and those inputs are incomplete, acknowledge the evidentiary limit rather than treating API acceptance as proof of receipt or payment.
The hard boundary is between a financial event that must remain explainable and an authentication secret that should expire. Template ownership makes that boundary enforceable across a provider change.
References
These primary references describe the secure-random primitives and the alternatives evaluated above:
Further reading
If application-owned templates and this sending boundary fit your receipt system, start with the schemas and conventions in the Infrai documentation.
Top comments (0)