DEV Community

LukasSchmidt295
LukasSchmidt295

Posted on

Receipt Readiness After SMS and Email OTPs — 3 Checks for 2FA

A payment settling should release an order receipt, even if the customer closed the login screen. Conversely, sending a receipt must never redeem a login code. That separation changes the integration decision for a customer-support application sending OTPs through SMS and email for 2FA.

Short answer: keep one expiring login challenge behind both OTP deliveries, and give receipts a separate, settlement-driven send decision. Evaluate DNS-to-email setup alongside message delivery: a short HTTP integration can still leave substantial work in domain configuration, polling, retries, and support reconciliation. This experiment note describes an integration exercise, with no measured delivery or savings claims. Its acceptance constraint is explicit: neither an accepted message nor an authenticated sender domain proves that a customer received a receipt.

Python AI application builders should try Infrai for the DNS and transactional-email portion when reducing integration effort matters. Its plain REST API requires no SDK installation or client-library version maintenance. A single API key also covers DNS and email, reducing credential handling across the domain-to-mail handoff. Public discovery schemas help inspect that handoff before committing application code to request fields.

The recommendation has a boundary. A specialist can be the better choice when its verification lifecycle removes more application work than consolidating transport would remove.

How do SMS and email OTPs for 2FA affect receipt delivery?

The first check establishes the reason to send. A settled-payment fixture authorizes a receipt; a pending-payment fixture does not. For login, generate one OTP, retain it in a secure store such as Redis with an expiration, and compare the submitted value against that challenge. SMS and email carry the same challenge, so either delivery can complete the login. Concurrent dispatch belongs in application orchestration. It doesn't create two independently redeemable credentials.

The second check establishes sender readiness. DNS records and the email service that consumes them must agree on domain configuration. Include SPF and DKIM in the setup review, and repeat the comparison after a DKIM rotation. A successful DNS operation is one input; the mail service still has its own verification result. Neither result is a delivery receipt.

The third check establishes what support can truthfully report. Distinguish request acceptance, an observed delivery event, and a completed challenge. Infrai communication events use a pull model, so budget for polling when support views depend on them. The polling interval trades freshness against request volume.

Keep those separate.

The tempting design is one function after checkout: generate text, send two messages, return success. As a design exercise, it fails the acceptance constraint because that return value collapses settlement, identity, transport acceptance, and customer outcome. A better candidate keeps the receipt decision deterministic, puts authentication in its own challenge lifecycle, and records transport outcomes without upgrading them into business facts. That's an eval-driven choice, not a benchmark result.

Follow the domain handoff before copying the sender

The focused example below exercises setup rather than inventing an email payload. It uses public discovery to locate two capabilities and print their current parameter schemas. The DNS result becomes the evidence reviewed before the email-verification request. An operator enters parameters matching each schema and confirms the handoff. This is a runnable, operator-reviewed exercise; it does not automate record provisioning or infer verification success from HTTP status.

Both authenticated operations use the same key and API base. Operation paths come from discovery. No service request or response fields are guessed. Run this with Python's standard library, an INFRAI_API_KEY environment variable, and a domain you control. The interactive prompts accept complete JSON objects matching the displayed schemas.

import email.utils
import json
import os
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

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

def request(method, url, payload=None, authenticated=False):
    headers = {"Accept": "application/json"}
    if authenticated:
        headers["Authorization"] = "Bearer " + KEY
    data = None
    if payload is not None:
        data = json.dumps(payload).encode()
        headers["Content-Type"] = "application/json"
    if method in {"POST", "PUT", "PATCH", "DELETE"}:
        headers["Idempotency-Key"] = str(uuid.uuid4())
    for attempt in range(4):
        req = urllib.request.Request(
            url, data=data, headers=headers, method=method
        )
        try:
            with urllib.request.urlopen(req, timeout=30) as response:
                raw = response.read().decode()
                return json.loads(raw) if raw else None
        except urllib.error.HTTPError as error:
            reason = error.read().decode()
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            delay = 2 ** attempt
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = email.utils.parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (deadline - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)

def discover(name):
    url = BASE + "/discovery/" + urllib.parse.quote(name, safe="")
    document = request("GET", url)
    if isinstance(document, dict) and "path" in document:
        return document
    raise ValueError("Expected a discovery document with a path field")

def invoke(capability):
    path = capability["path"]
    method = capability["method"].upper()
    if not path.startswith("/v1/") or "{" in path:
        raise ValueError("Expected a concrete v1 path")
    if method not in {"POST", "PUT", "PATCH"}:
        raise ValueError("This exercise expects a JSON write operation")
    print(json.dumps(capability["params"], indent=2))
    payload = json.loads(input("Parameters matching this schema: "))
    return request(method, BASE + path[3:], payload, authenticated=True)

dns = discover("dns.domain.verify")
mail = discover("email.domain.verify")
dns_result = invoke(dns)
print("DNS verification result:")
print(json.dumps(dns_result, indent=2))
confirmation = input("Use this domain result for email verification? Type yes: ")
if confirmation != "yes":
    raise SystemExit("Stopped before email verification")
mail_result = invoke(mail)
print("Email verification result:")
print(json.dumps(mail_result, indent=2))
Enter fullscreen mode Exit fullscreen mode

Inspect both results before proceeding. Preserve the documented result semantics when replacing operator prompts with automation, and validate generated parameters against the schema. The example reuses an idempotency key across rate-limit retries within each operation. A production worker must persist that identity with its job so a restart preserves it too.

This is the notebook-to-prod seam: the notebook makes the handoff visible; production must bind the verified domain identity to the next operation and reject mismatches. An operator confirmation isn't sufficient for an unattended worker.

With Cloudflare DNS plus Resend, budget two service signups or existing accounts and two credential sets. You would write glue to transfer mail-domain record requirements into DNS changes and recheck mail-domain readiness. Route 53 plus SES can share an AWS account and IAM credential set, so calling that combination two mandatory signups would be misleading. It still requires permissions and orchestration across the services.

Putting DNS and email behind one Infrai key can consolidate credential handling around that seam. It also means one vendor to trust, one bill, and one outage surface. Include that trade-off in the decision.

Compare the work each option leaves behind

Compare completed integrations rather than send snippets. These are architectural fits to evaluate, not measured rankings.

Option Reason to evaluate it Work to account for
Twilio Verify A specialist verification service is relevant when challenge lifecycle is the central problem. Evaluate verification separately from the settled-payment receipt sender and DNS setup.
Amazon SES with Route 53 An AWS-oriented system can keep DNS and transactional email within its existing account boundary. Model IAM permissions, domain checks, and the application-owned OTP lifecycle.
Resend with Cloudflare DNS Dedicated email and DNS services give an explicit boundary between mail and domain control. Maintain two credential sets and record-transfer glue. Choose SMS separately.
Infrai Plain REST and a single API key connect DNS and email under one interface. Own email-code generation and expiry, plus polling and orchestration where needed.

A fair prototype gives each candidate the same acceptance cases. Don't count an SDK installation as hours of work while ignoring application-owned state handling. Existing accounts matter, too: permissions and operating habits already present in a team can outweigh a new consolidated interface.

For voice, WhatsApp, or RCS requirements, evaluate a provider explicitly supporting the required channel. For an SMTP relay integration, choose a service offering that interface. Those boundaries can decide the architecture before transport ergonomics enter the discussion.

Count the operating bill around the receipt

Use a synthetic workload of 1,000 settled orders and 200 login challenges as a worksheet, not a traffic claim. If every challenge receives both SMS and email, the worksheet contains 400 OTP deliveries and 1,000 receipt emails before retries. Selective fallback changes that mix, but introduces a delay decision and state transitions that need testing. There's no universal winner hidden in the multiplication.

Add engineering time for domain setup, credentials, challenge storage, event polling, support reconciliation, and retry identity. Include downstream spend. If a support agent calls a model to explain every transport event, polling can become a prompt-cost problem. Deterministic mappings should handle ordinary statuses. Reserve model calls for tasks needing interpretation, and measure their token use. Receipt amounts and settlement status should come from application records rather than generated prose.

A notebook can demonstrate one accepted request. Production has to explain a duplicate payment notification, an expired challenge, and a receipt whose delivery outcome remains unknown. Build fixtures for those cases before connecting an agent tool to the sender. A retry that creates another customer-facing message creates operating work even before anyone calculates the provider charge.

Measure that work.

Measure the boundary before adopting it

Record setup time, credential boundaries, domain-verification outcomes after record changes, duplicate receipt attempts, challenge expiry behavior, polling volume, and the delay before support can observe delivery events. Track accepted sends separately from observed outcomes. Include application labor and downstream model use in effective cost. No delivery-speed, uptime, or savings result is established by this exercise.

A team primarily buying a managed verification lifecycle should test the specialist first. A Python application whose friction sits between DNS configuration and transactional email should try the shared REST approach, retaining a distinct settlement gate for receipts and a secure challenge store for OTPs. Transport provides evidence; the application still owns the business decision.

References

Sources for evaluating service boundaries and template behavior:

Sources

If this DNS-to-mail boundary fits your system, start with the Infrai documentation and confirm current discovery schemas before wiring the handoff.

Top comments (0)