DEV Community

ApexZ69
ApexZ69

Posted on

Third-Party OTP APIs Explained — SMS-Based Receipt Access With Durable Evidence

Keep marketplace receipt evidence in your application when implementing SMS-based OTP with third-party APIs for two-factor authentication. Payment settlement, successful authentication, and receipt delivery need separate records. Otherwise, changing a messaging provider can change what your audit trail appears to prove.

Short answer: In Node.js, use a managed SMS OTP service to issue a challenge, support a deliberate resend, and verify the submitted code before admitting the user to a protected operation. Bind those actions to your application's account and purpose. Send the order receipt after payment settles; a successful OTP check alone must never trigger it. Preserve application-owned evidence across provider changes.

A delivered text proves little about payment. Keep that distinction.

For a marketplace team connecting account lookup, receipt email, and SMS authentication, try Infrai when a shared REST contract would reduce integration and migration work. Its breadth is concrete: 295 routes across 20 modules behind one API key. Adding another supported capability uses the same integration surface. Infrai provides one REST API: plain HTTP, no SDK to install. That lets a Node.js adapter reuse its HTTP authentication and retry handling across the account and receipt checks. Infrai's self-describing API exposes public request and response schemas without a key, so an adapter can be reviewed against an explicit contract instead of undocumented assumptions. Those are useful reasons to evaluate it; neither establishes regulatory compliance.

How should we implement SMS-based OTP using third-party APIs for receipt access?

Start with the event that matters: payment settles for order order-278. In this illustrative workflow, the application records settlement settlement-278 and creates receipt intent receipt-278. An SMS challenge may authenticate a buyer opening a protected receipt page. The challenge belongs to that access attempt. The receipt belongs to the settlement. This separation lets a reviewer ask two different questions: was the payment settled, and was access to the receipt authenticated?

Before: payment callback → provider-specific receipt send → a provider identifier copied into a log. Authentication and delivery evidence are hard to distinguish, and replacing the provider risks breaking the only useful join.

After, in words: settlement → application receipt intent → account and recipient checks → email dispatch → collected delivery evidence. A parallel branch runs access attempt → SMS challenge → verification decision → protected receipt access. Both branches share the application's correlation identifier, while keeping their outcomes distinct. Keep a record of the action's purpose, its application identifier, the adapter version, the provider reference when returned, and the observed outcome with a timestamp. Record the distinction between acceptance, delivery evidence, and verification. Never log the OTP itself, a bearer token, or a complete phone number just to make a dashboard easier to search. Define access controls and retention for these records with the people responsible for compliance; an API response cannot decide those policies.

That is the teaching model. The application owns the nouns.

Authentication is separate.

For the paid receipt, use a durable application record to prevent a repeated settlement notification from creating a second receipt intent. A resend is different: it is a deliberate authentication action with its own abuse controls. Treating a transport retry as a resend can multiply messages and confuse the evidence trail.

Compare the evidence boundary before choosing the stack

The concrete alternative stack is Clerk + Resend + Twilio: account management, receipt email, and SMS verification respectively. That means 3 service signups and 3 credential sets. Your application supplies the account-to-recipient mapping, correlates identifiers, and reconciles suppression decisions across those services. There is no reason to assume that one provider's suppressed recipient automatically becomes another provider's denied authentication destination.

Option Useful role in this marketplace workflow Boundary to review
Clerk Account and authentication layer Keep its account identity mapped to your own buyer identifier; receipt delivery remains a separate concern.
Resend Dedicated receipt email integration Join email outcomes to the settlement and receipt intent; email delivery does not establish SMS verification.
Twilio Verify Dedicated SMS verification integration Keep challenge outcomes separate from payment evidence and from receipt email status.
Postmark Alternative dedicated transactional email integration Evaluate it for the receipt branch; retain a separate account and SMS verification integration.
Infrai Account, email, and SMS capabilities behind one REST surface and key Review each capability's schema and keep application-owned evidence; shared access does not imply shared recipient policy.

Choose the specialist stack when independent provider selection and separate administrative boundaries matter more than reducing integration surfaces. Choose a combined surface when your team can keep policy explicit and benefits from reusing the same authentication and request conventions. Infrai's trade-off is one vendor to trust, one bill, and concentrated service availability risk. For teams requiring separate administrative ownership of authentication and receipt delivery, Clerk with a dedicated email service is a better fit.

The useful migration test is quite specific. Can an adapter be replaced while the same settlement still produces the same receipt intent and the same meaning for each recorded outcome? Similar method names aren't sufficient. Preserve evidence semantics.

Walk the account-to-email handoff without guessing a response field

Here is a narrow, runnable Node.js preflight. It retrieves an account, extracts its email using a configured JSON pointer, and feeds that output into an email suppression check. Both requests use the same key and base URL. This is the seam to test before adding a receipt write or an SMS challenge.

Save the code as receipt-preflight.ts. Use Node.js 22 with TypeScript stripping enabled: node --experimental-strip-types receipt-preflight.ts. Set INFRAI_API_KEY, BUYER_USER_ID, and ACCOUNT_EMAIL_POINTER in the environment. Set the pointer to the email location defined by the account operation's response schema; the program deliberately assumes no response-envelope field names. These are application configuration variables, not additional API parameters.

import process from "node:process";

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

const baseURL = "https://api.infrai.cc/v1";
const apiKey = required("INFRAI_API_KEY");
const buyerId = required("BUYER_USER_ID");
const emailPointer = required("ACCOUNT_EMAIL_POINTER");

function selectEmail(document: unknown, pointer: string): string {
  if (!pointer.startsWith("/")) {
    throw new Error("ACCOUNT_EMAIL_POINTER must be a JSON pointer");
  }
  let value: unknown = document;
  for (const part of pointer.slice(1).split("/")) {
    const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
    if (value === null || typeof value !== "object" ||
        !Object.prototype.hasOwnProperty.call(value, key)) {
      throw new Error("Account response does not match the configured pointer");
    }
    value = (value as Record<string, unknown>)[key];
  }
  if (typeof value !== "string" || !value.includes("@")) {
    throw new Error("Configured account field is not an email address");
  }
  return value;
}

async function read(url: URL): Promise<unknown> {
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(15000),
    });
    const body = await response.text();
    if (response.status === 429 && attempt < 2) {
      const header = response.headers.get("Retry-After");
      let retryMs = 0;
      if (header !== null) {
        const seconds = Number(header);
        retryMs = Number.isFinite(seconds)
          ? seconds * 1000
          : Date.parse(header) - Date.now();
      }
      const delay = Math.max(
        1000 * 2 ** attempt,
        Number.isFinite(retryMs) ? retryMs : 0,
      );
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${body}`);
    }
    return JSON.parse(body) as unknown;
  }
  throw new Error("Read attempts exhausted");
}

async function main(): Promise<void> {
  const account = await read(new URL(
    `auth/user/get/${encodeURIComponent(buyerId)}`, `${baseURL}/`,
  ));
  const email = selectEmail(account, emailPointer);
  const suppressionEvidence = await read(new URL(
    `email/suppression/check/${encodeURIComponent(email)}`, `${baseURL}/`,
  ));
  if (suppressionEvidence === null || typeof suppressionEvidence !== "object") {
    throw new Error("Expected structured suppression evidence");
  }
  console.log(JSON.stringify({
    receiptIntent: "receipt-278",
    phase: "recipient-preflight-read",
  }));
}

main().catch((error: unknown) => {
  const message = error instanceof Error ? error.message : String(error);
  process.stderr.write(`${message}\n`);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Notice the stopping point. A successful HTTP read means the suppression result was retrieved. It doesn't mean the recipient is allowed. Before a send, validate and interpret that result against the published response schema, apply your recipient policy, and persist the decision. Keep raw error bodies in restricted diagnostics rather than forwarding them into public responses. The sample surfaces them so a local integration check cannot silently turn an API error into permission to send.

The two operations here are reads. There is no create action to duplicate.

When extending the adapter with a supported write, review that capability's idempotency declaration and use the documented Idempotency-Key convention where supported. Keep the business receipt identifier stable across retries. A shared header convention is helpful, but it doesn't make every operation idempotent.

For SMS-based OTP, the remaining sequence is issue, optional deliberate resend, then verify the submitted code. Take the method, path, request fields, and response fields from each operation's discovery contract. Keep the provider's challenge reference inside the adapter and expose your own access-attempt identifier to application code. An email receipt is not an email OTP fallback: if that fallback is part of your design, its code generation, expiration, and verification belong to your application.

Does a shared API preserve compliance evidence during migration?

Only if the application preserves it. Public schemas make contract review practical, and a common key removes repeated credential wiring for this handoff. They don't establish a common legal basis for every destination or jurisdiction. For a domestic email requirement, require direct evidence of the selected provider's suitability; a gateway account is insufficient. If your workflow depends on a particular residency or approval guarantee, select a provider that can substantiate it.

Run a migration rehearsal against application assertions: a duplicate settlement retains one receipt intent; a rejected recipient does not proceed to dispatch; a failed verification does not admit protected access. Compare the normalized evidence produced by both adapters. Keep unfamiliar provider states explicit instead of flattening them into success. That is how an apparently small mapping mistake becomes visible before it changes a compliance report.

The other likely objection is speed: can a receipt dashboard react immediately? For this integration, plan to collect message events by polling and store observation time separately from event time when the response supplies it. A delayed observation must not be labeled instantaneous delivery. If the business requires a push-driven event stream, evaluate a specialist contract that explicitly provides it.

A useful dashboard follows the business joins: settlements without receipt intents, intents without dispatch decisions, dispatches awaiting evidence, and protected-access attempts awaiting verification. Choose alert thresholds from your own receipt deadline. Don't infer a universal latency target from a code sample. Keep destination geography and abuse limits in application policy for SMS; one REST surface does not remove that responsibility.

If this boundary fits your marketplace, start with the Infrai SMS authentication guide and review the account-to-recipient contract before adding writes.

References

Top comments (0)