Examples

Node.js

A plain Node.js client and an Express server with send and check endpoints.

Both files are tested against the API's sandbox on every change.

Client (no dependencies, Node 18+)

examples/nodejs/otp-client.mjs
// OTP.ps client for Node.js 18+ (no dependencies). Server-side only:
// the API key comes from the environment and must never reach a browser.
//
//   OTP_PS_API_KEY=otp_test_…   (sandbox) or otp_live_… (real messages)
//   OTP_PS_BASE_URL=https://otp.ps   (optional)

export class OtpError extends Error {
  constructor(status, body) {
    super(body?.message ?? `OTP.ps answered HTTP ${status}`);
    this.name = "OtpError";
    this.status = status;
    this.code = body?.error ?? "unknown"; // e.g. invalid_phone, rate_limited (see the errors reference)
    this.retryAfter = body?.retry_after; // seconds, for rate_limited
  }
}

function settings() {
  const key = process.env.OTP_PS_API_KEY;
  if (!key) throw new Error("OTP_PS_API_KEY is not set");
  return { key, base: (process.env.OTP_PS_BASE_URL ?? "https://otp.ps").replace(/\/$/, "") };
}

async function request(method, path, body, headers = {}) {
  const { key, base } = settings();
  const res = await fetch(`${base}/api/v1${path}`, {
    method,
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...headers },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(15_000),
  });
  const data = await res.json().catch(() => null);
  if (!res.ok) throw new OtpError(res.status, data);
  return data;
}

/**
 * Sends a code. Returns { id, status, to, expires_at, … } (and test_code with a test key).
 * Pass an idempotencyKey (e.g. "order-1042-otp-1") to make retries safe: the same key
 * never sends or charges twice.
 */
export function sendCode(phone, { purpose = "verify", locale, idempotencyKey } = {}) {
  return request(
    "POST",
    "/verify/send",
    { phone, purpose, ...(locale ? { locale } : {}) },
    idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
  );
}

/** Checks the code the customer typed. Trust only `valid === true`. */
export function checkCode(id, code) {
  return request("POST", "/verify/check", { id, code: String(code) });
}

export function getBalance() {
  return request("GET", "/balance");
}

Express endpoints

Your page calls POST /api/otp/send with { phone } and POST /api/otp/check with { code }. The verification id and number stay on the server; the browser only learns that a code was sent. Pair it with the React form.

examples/nodejs/server.mjs
// Express example: phone verification endpoints for your own website or app.
// The browser talks to these two routes; only this server talks to OTP.ps.
//
//   npm install express
//   OTP_PS_API_KEY=otp_test_… node server.mjs
import { randomUUID } from "node:crypto";
import express from "express";
import { checkCode, OtpError, sendCode } from "./otp-client.mjs";

export const app = express();
app.use(express.json());

// Pending verifications, by browser session. Use your real session store
// (Redis, your database, express-session) in production.
const pending = new Map(); // sessionId -> { id, phone, sentAt }
const verifiedPhones = new Map(); // sessionId -> phone (server-side truth)

function session(req, res) {
  let sid = /(?:^|;\s*)sid=([\w-]+)/.exec(req.headers.cookie ?? "")?.[1];
  if (!sid) {
    sid = randomUUID();
    res.cookie("sid", sid, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production" });
  }
  return sid;
}

// Your own limit per visitor, on top of OTP.ps's limits, so nobody can drain your balance.
const hits = new Map();
function tooMany(key, max = 5, windowMs = 15 * 60_000) {
  const now = Date.now();
  const list = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
  hits.set(key, [...list, now]);
  return list.length >= max;
}

function fail(res, e) {
  if (e instanceof OtpError) {
    // Show the customer something useful, never the raw error.
    const message = {
      invalid_phone: "Please check the mobile number.",
      unsupported_network: "Only Jawwal and Ooredoo numbers can receive codes.",
      rate_limited: "Please wait before asking for a new code.",
      sms_failed: "We couldn't send the message. Please try again.",
    }[e.code] ?? "Verification is unavailable right now. Please try again later.";
    return res.status(e.status === 429 ? 429 : 400).json({ error: e.code, message, retryAfter: e.retryAfter });
  }
  console.error("OTP.ps request failed:", e.message); // never log codes or keys
  return res.status(503).json({ error: "unavailable", message: "Verification is unavailable right now." });
}

app.post("/api/otp/send", async (req, res) => {
  const sid = session(req, res);
  if (tooMany(`send:${sid}`) || tooMany(`ip:${req.ip}`, 20)) {
    return res.status(429).json({ error: "rate_limited", message: "Too many requests. Try again later." });
  }
  try {
    const v = await sendCode(String(req.body?.phone ?? ""), {
      purpose: req.body?.purpose === "order" ? "order" : "verify",
      locale: req.body?.locale === "en" ? "en" : "ar",
    });
    pending.set(sid, { id: v.id, phone: String(req.body.phone), sentAt: Date.now() });
    // Don't send the verification id or test_code to the browser.
    res.json({ sent: true, to: v.to, expiresAt: v.expires_at });
  } catch (e) {
    fail(res, e);
  }
});

app.post("/api/otp/check", async (req, res) => {
  const sid = session(req, res);
  const p = pending.get(sid);
  if (!p) return res.status(400).json({ error: "no_code", message: "Ask for a code first." });
  try {
    const r = await checkCode(p.id, String(req.body?.code ?? ""));
    if (r.valid) {
      pending.delete(sid);
      verifiedPhones.set(sid, p.phone); // mark the phone verified on the server, not in the browser
      return res.json({ verified: true });
    }
    if (r.status !== "pending") pending.delete(sid); // expired, failed or replaced: a new code is needed
    res.status(400).json({ verified: false, status: r.status, attemptsLeft: r.attempts_left });
  } catch (e) {
    fail(res, e);
  }
});

export function verifiedPhoneFor(sid) {
  return verifiedPhones.get(sid) ?? null;
}

if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
  app.listen(process.env.PORT ?? 3000, () => console.log("Listening"));
}

View as Markdown