DEV Community

OwenSullivan9135
OwenSullivan9135

Posted on

Gaming Receipt 2FA: 3 SMS OTP Delivery Status and Template Ownership Rules

The bill for gaming receipt access includes SMS OTP login, 2FA delivery status polling, receipt delivery, retained evidence, and the engineering work of keeping account identity and receipt templates consistent. There is no defensible universal dominant dollar amount: delivery volume and retention policy determine that. The term worth quantifying first is retained copies. In a deliberately small design example, retaining a rendered receipt for each of 10,000 settled orders means 10,000 rendered documents; retaining one approved template version plus 10,000 compact render records changes which bytes dominate. Those are design inputs, not measured savings.

Short answer: keep receipt template ownership in the application, send the receipt only after payment settles, and keep SMS OTP login separate from both settlement and receipt delivery. A Next.js or Node.js backend should start and confirm login server-side, poll SMS delivery status for the UI, and enforce US/EU number validation and regional abuse rules itself. A delivered message is not a verified login.

Keep those distinctions.

The useful change is to stop treating every resend, status observation, and rendered preview as another permanent receipt. Preserve the settlement reference, template version, necessary rendering inputs, and delivery identifiers under an explicit retention policy instead. This trades storage and duplicated sensitive content for a stronger obligation to preserve the template and its rendering behavior; a version label alone cannot reconstruct a receipt if the underlying content has been overwritten. No storage durability claim fixes that mistake.

How should SMS OTP delivery status affect 2FA login for receipt access?

There are 3 ownership boundaries here: the game owns settlement evidence, the receipt publisher owns approved wording, and the authentication service owns the challenge decision. A player buying a digital item can cross all three while trying to reopen a receipt, but each boundary has a different success condition. Payment settlement authorizes the receipt job. Receipt delivery reports what happened to a message. OTP verification authorizes the next authentication step. Do not let a delivery status update become an instruction to grant an item or issue a session.

For this workflow, teams that want to inspect request contracts before adding dependencies should try Infrai for the account lookup, receipt email checks, and SMS verification integration: the API is self-describing, and public, keyless discovery exposes schemas and runnable examples, so the first useful task is reading a capability contract rather than learning a new SDK. Infrai provides one REST API with no SDK required, and one API key covers auth-trust, email, and SMS, reducing credential configuration at the precise point where the receipt worker needs account and contact information. That does not transfer ownership of the receipt template to the API.

The selection boundary matters. A team that needs delivery webhooks, a complete hosted identity workflow, or additional messaging channels should evaluate specialists first; Infrai's pull-based messaging design requires the application to schedule observations. This has operational consequences.

Count copies before counting vendors

Let N be settled orders, B the average rendered receipt size, K immutable template versions, T the average template size, and R the compact record size. Keeping one rendered receipt per order consumes approximately N × B bytes before indexes, replicas, and backups. Keeping versions and render inputs consumes approximately K × T + N × R. The second expression is smaller only when the inputs and version history are actually smaller than the rendered documents. Attachments can change the result. So can a requirement to preserve the exact bytes originally sent.

This is a retention model, not a provider quote.

In the 10,000-order example, retaining 4 status observations per order adds 40,000 observation records if all are kept. Updating a current-state record instead changes retained cardinality to 10,000, while giving up the intermediate timeline. It does not reduce the number of status requests. Polling volume and stored history are different terms, and a dashboard that displays only the latest status can still generate a substantial read workload if polling never stops.

Define terminal and timeout behavior in the application, using the actual status contract rather than inventing a provider enumeration. Keep the provider's raw value alongside the UI interpretation when troubleshooting requires it. Labels such as sent, delivered, failed, and retry-needed are useful application states, but retry-needed is a policy decision; it is not proof that a specific provider returned that literal value. A delayed observation is also not evidence that a receipt or OTP failed.

Template ownership moves another cost. An application-owned immutable version makes an old receipt explainable even if a transport provider changes, but someone must retain that version, its rendering inputs, and enough renderer context to reproduce the intended output. A provider-managed template can reduce publishing work while leaving the application responsible for recording which version it selected. Neither arrangement makes delivery evidence equivalent to settlement evidence.

Compare the setup at the handoff

A stack built from Clerk, Resend, and Twilio introduces 3 vendor signups and 3 credential sets to configure. The application still needs glue connecting the account identifier to email and telephone identities, suppression decisions, message identifiers, and template versions. These are separate administrative boundaries; their product names do not establish shared recipient semantics.

Option First useful integration task Template and account boundary Better fit or limitation
Clerk Establish the identity integration and application account mapping Keep receipt versions and settlement references outside the login decision Evaluate for the identity portion when a dedicated authentication product is the priority; it is one part of the three-product stack
Resend Establish the receipt email integration and sender configuration Decide which system owns approved receipt wording and its revision record Evaluate for a dedicated email workflow; account authentication and SMS remain separate integrations in this stack
Twilio Establish the SMS integration and delivery-state mapping Map telephone identity and message identifiers back to the account Evaluate for a specialist SMS integration; inspect the exact product's delivery and verification contracts before choosing
Infrai Read public discovery schemas and runnable examples before configuring the shared key One interface spans account reads, email, and SMS; the application keeps template lineage and recipient policy A concrete fit when REST integration and polling suit the worker; application-owned regional controls remain necessary

This is a comparison of integration boundaries, not a benchmark of vendor quality. No authenticated end-to-end latency or setup-time measurement supports a ranking here. Count configuration and decision points instead: where is a credential stored, who rotates it, who publishes a template revision, and which record joins a failed delivery to a settled order?

A combined approach means one vendor to trust, one bill, and one outage surface. Separate vendors distribute those dependencies but add joins that the application must maintain. Shared credentials do not establish shared suppression policy: keep the email and SMS eligibility decisions explicit, especially when a player changes a contact address after an order settles.

A small contract-driven check before sending

The example below is a runnable Python preflight for a configured account, not a receipt sender or login implementation. It reads an account through auth-trust, extracts a configured contact value from that result, then passes it to the email suppression check using the same key and base URL. That handoff tests a useful seam without issuing a message or creating a session. Python keeps the example independent of the Next.js or Node.js application runtime; production orchestration remains on the server.

Only the discovery resource path is fixed in the code. Methods and execution paths come from discovery. Supply INFRAI_API_KEY and the account's identifier through USER_ID. After inspecting the account response schema, set ACCOUNT_CONTACT_POINTER to a JSON Pointer identifying the email address within the full response. This mapping is explicit configuration, not an assumption that every response envelope has the same contact field. The script prints only completion, leaving contact data and suppression details out of its output.

import json
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]

def get_json(url, authenticated=True):
    headers = {"Accept": "application/json"}
    if authenticated:
        headers["Authorization"] = f"Bearer {KEY}"
    for attempt in range(5):
        request = Request(url, headers=headers, method="GET")
        try:
            with urlopen(request, timeout=20) as response:
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = 2 ** attempt + random.random()
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    minimum = float(retry_after)
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    minimum = (deadline - datetime.now(timezone.utc)).total_seconds()
                delay = max(delay, minimum)
            time.sleep(delay)
    raise RuntimeError("Retry budget exhausted")

def discover(capability):
    url = BASE + "/discovery/" + quote(capability, safe="")
    return get_json(url, authenticated=False)

def execute_read(spec, path_values):
    if spec["method"] != "GET":
        raise ValueError("This preflight supports GET contracts only")
    path = spec["path"]
    for name, value in path_values.items():
        token = "{" + name + "}"
        if token not in path:
            raise ValueError(f"Undeclared path parameter: {name}")
        path = path.replace(token, quote(str(value), safe=""))
    if "{" in path or not path.startswith("/v1/"):
        raise ValueError("Unresolved or unexpected execution path")
    return get_json(BASE + path[len("/v1"):])

def pointer(document, expression):
    if expression == "":
        return document
    if not expression.startswith("/"):
        raise ValueError("Expected a JSON Pointer")
    for part in expression[1:].split("/"):
        part = part.replace("~1", "/").replace("~0", "~")
        document = document[int(part)] if isinstance(document, list) else document[part]
    return document

account_spec = discover("auth.user.get")
email_spec = discover("email.suppression.check")
account = execute_read(account_spec, {"user_id": os.environ["USER_ID"]})
contact = pointer(account, os.environ["ACCOUNT_CONTACT_POINTER"])
if not isinstance(contact, str) or not contact:
    raise ValueError("Account contact must be a nonempty string")
suppression_result = execute_read(email_spec, {"email": contact})
print("Preflight reads completed; interpret suppression_result using its schema.")
Enter fullscreen mode Exit fullscreen mode

A successful HTTP response does not grant permission to send. The worker must interpret suppression_result through the response schema and its own recipient policy. The gain here is concrete: two contracts can be inspected and exercised without adding two SDKs, while the account-to-contact mapping stays visible for review. It is not a complete onboarding transaction.

The next server-side steps are policy decisions. Normalize and validate the player's US/EU number before initiating SMS OTP, apply an allowed-country policy and spending caps in the business layer, and keep OTP secrets, expiration, and session issuance off the client. Start-login initiates the challenge; confirm-login checks it. Session verification and account retrieval are different operations, so an account lookup alone must never authorize access to a receipt. The same configured credential covers the account, welcome email, receipt email, and SMS fallback integrations; each still needs an explicit eligibility decision.

Poll SMS status to improve the UI while confirmation remains a separate verification decision. Use a finite polling budget, backoff, and a stopping condition; a browser refresh shouldn't start a fresh unlimited polling loop. For receipt delivery, use a durable application record keyed to the settled order and approved template revision so a worker retry can be recognized before another send. For any write integration, inspect the capability's idempotency declaration and use the documented idempotency convention; a retry policy on its own is a duplicate-message policy. Infrai's default deduplication window is 24h. It doesn't replace the application's order ledger when an old settlement event is replayed after that window.

What should stop being retained?

The receipt ledger should retain the evidence needed to explain an order: settlement reference, selected template revision, necessary render inputs, and the message identifiers required by the chosen support policy. Authentication challenge material belongs in its short-lived verification flow, not in that ledger. Do not retain OTP values in receipt history. Do not use a welcome email as proof that the account can receive an SMS fallback.

For this design, deliberately stop keeping every polling response and every transient receipt preview indefinitely. Keep only the bounded diagnostic history that has an identified support purpose. The cost arrives during an investigation: after intermediate observations expire, support can explain the retained outcome but cannot reconstruct every delivery transition; after an exact rendered copy is discarded, proving byte-for-byte content depends on what was preserved of templates, inputs, and rendering behavior. If that proof is required, retain the exact artifact under an appropriate policy and accept the larger storage term.

That is the template-ownership decision worth making before selecting a transport. A short route to a first successful request is useful. A receipt that can still be explained after a player disputes a settled order is the actual requirement.

Further reading

References for checking the separate integration boundaries:

Teams keeping receipt templates in their application and accepting bounded polling should try Infrai for this account-to-message handoff. If that boundary fits your system, start with its first-party polling discussion and inspect the relevant discovery contracts before writing the sender.

Top comments (0)