Developer Reference · API v1.0

RunOTP API Documentation

Reverse WhatsApp & Telegram OTP and Dedicated VIP 2-Way Messaging. Base URL: https://api.runotp.com/v1

llms.txt
Your API Keys Pre-injected in code
API Key (Public Identifier) YOUR_API_KEY
API Secret (Server-side only — not your login password) ••••••••••••••••••••••••••••••••
Phone format everywhere: international digits only, no + or 00 (e.g. 201012345678).
Test in Postman (1-File Setup) Private File
CONFIDENTIAL — DO NOT PUBLISH OR SHARE: This downloaded file (RunOTP.private.postman_collection.json) contains your live apiSecret. Keep it strictly on your local machine, never commit it to GitHub (add it to .gitignore), and never publish it to public Postman workspaces or chat groups.
Want zero webhooks & zero UI work? Use Flash Start — redirect users to Go.aspx and verify the burnable token in 1 POST call. Works on http://localhost.
Open Flash Start Studio →
STEP 1 RunOTPClient (Unified Helper SDK) Add Once · Used Everywhere

Drop this single helper class into your backend project first. It is the backbone used by Steps 2, 3 & 4 — handling link generation, X-RunOTP-Signature HMAC verification, optional AES-256 decryption, and VIP outbound messaging.

Node.js (Express / JavaScript) — RunOTPClient.js (Unified Helper SDK)
// runotp-client.js (Node.js 18+ built-in fetch + crypto)
const crypto = require('crypto');

class RunOTPClient {
  constructor(apiKey = 'YOUR_API_KEY', apiSecret = 'YOUR_API_SECRET') {
    this.apiKey = apiKey;
    this.apiSecret = apiSecret;
    this.apiBase = 'https://api.runotp.com/v1';
  }

  /**
   * Generate live WhatsApp and/or Telegram verification links & QR codes.
   * @param {string} msg - Custom message containing (apiKey) as 1st bracket and (otp) as 2nd bracket.
   * @param {'both'|'whatsapp'|'telegram'} channel - Default: 'both'
   * @param {'en'|'ar'} lang - Telegram bot prompt language ('en' or 'ar')
   */
  async generateLink(msg, channel = 'both', lang = 'en') {
    const res = await fetch(`${this.apiBase}/links`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        apiKey: this.apiKey,
        apiSecret: this.apiSecret,
        msg,
        channel,
        lang
      })
    });

    const data = await res.json();
    if (!res.ok) {
      throw new Error(data.notes || data.error || `HTTP ${res.status}`);
    }
    // Always returns { url, qr, telegramUrl, telegramQr, channel, notes }
    return data;
  }

  /**
   * Verify X-RunOTP-Signature & X-RunOTP-Timestamp (HMAC-SHA256 + 300s replay window).
   */
  verifySignature(rawBody, timestamp, signature) {
    if (!timestamp || !signature) return false;
    const ts = Number(timestamp);
    if (!Number.isFinite(ts) || Math.abs(Math.floor(Date.now() / 1000) - ts) > 300) {
      return false;
    }

    const expected = 'sha256=' + crypto
      .createHmac('sha256', this.apiSecret)
      .update(`${timestamp}.${rawBody}`, 'utf8')
      .digest('hex');

    const a = Buffer.from(expected, 'utf8');
    const b = Buffer.from(String(signature).trim(), 'utf8');
    return a.length === b.length && crypto.timingSafeEqual(a, b);
  }

  /**
   * Auto-detects plain JSON vs. AES-256-CBC Base64 encrypted webhook body.
   */
  decryptWebhook(rawBody) {
    const text = (rawBody || '').trim();
    if (!text) return null;
    if (text.startsWith('{')) {
      return JSON.parse(text);
    }

    const raw = Buffer.from(text, 'base64');
    if (raw.length <= 16) return null;

    const iv = raw.subarray(0, 16);
    const cipherText = raw.subarray(16);
    const key = crypto.createHash('sha256').update(this.apiSecret, 'utf8').digest();
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    const plainJson = Buffer.concat([decipher.update(cipherText), decipher.final()])
      .toString('utf8')
      .replace(/^\uFEFF/, '');

    return JSON.parse(plainJson);
  }

  /**
   * Send an outbound WhatsApp text or media message (Dedicated VIP only).
   */
  async sendOutbound(destinationNumber, message, mediaUrl = '', clientRef = '', typingDelay = 2000) {
    const res = await fetch(`${this.apiBase}/messages`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        apiKey: this.apiKey,
        apiSecret: this.apiSecret,
        destinationNumber: String(destinationNumber).trim(),
        message,
        mediaUrl,
        clientRef: clientRef || `REF_${Date.now()}`,
        typingDelay
      })
    });
    return res.json();
  }
}

module.exports = { RunOTPClient };
POST https://your-site.com/runotp-webhook HMAC-SHA256 Signed · 3× Auto-Retry

As soon as the user sends the WhatsApp message or confirms in Telegram, RunOTP delivers the verified phone & OTP to the Webhook URL registered in Settings.

1. Exact Final URL (No Redirects) Register the exact URL that receives POST (match www and trailing slash). If your server replies with a 301/302 redirect, RunOTP will not follow it and delivery fails.
2. Reply HTTP 200 in < 5 Seconds Save the OTP/phone quickly and return 200 OK right away (run slow tasks like emails after). On timeout or 5xx/429, RunOTP auto-retries 3 times (immediate, +1.5s, +4.5s).
3. Pass Raw Text to DecryptWebhook() Read the HTTP request body as plain text first (don't auto-parse as JSON), then pass it to VerifySignature() and DecryptWebhook(rawBody) — it automatically handles both plain JSON and AES-256 encryption!
Incoming Payload (WtsReq after DecryptWebhook)
{
  "event": "otp_received",
  "channel": "whatsapp",
  "key": "YOUR_API_KEY",
  "sender": "201012345678",
  "otp": "482910",
  "message": "Please (YOUR_API_KEY) ... (482910)",
  "message_id": "1796050000000",
  "media_url": "",
  "balance": 14.85,
  "timezone": "+02:00",
  "timestamp": "2026-12-04 15:30:00"
}
Your Required Response (HTTP 200 OK)
{
  "code": "200",
  "status": "success"
}
View incoming security headers (verified automatically by RunOTPClient)
HTTP HeaderWhat it does
X-RunOTP-SignatureCryptographic proof (sha256=HMAC_SHA256("{timestamp}.{rawBody}", apiSecret)) that the request came from RunOTP. Checked automatically by VerifySignature().
X-RunOTP-TimestampUnix time (seconds) the webhook was signed — requests older than 5 minutes (300s) are rejected to prevent replay attacks.
X-Idempotency-KeyUnique ID per message so your server can safely ignore duplicate retries.
X-Retry-AttemptDelivery attempt number (1, 2, or 3).
Optional AES-256If Payload Encryption is ON in Settings, the body arrives as Base64 (IV[16B] + AES-256-CBC). DecryptWebhook(rawBody) detects and decrypts it automatically.
Complete Webhook Receiver Page Code
Node.js (Express / JavaScript) — Complete Webhook Page (webhook-server.js — Express)
// webhook-server.js — Complete RunOTP Webhook Receiver (npm install express)
const express = require('express');
const { RunOTPClient } = require('./runotp-client');

const app = express();
const runOtp = new RunOTPClient();

// Simple in-memory idempotency set (use Redis or a UNIQUE DB column in production)
const processedKeys = new Set();

// IMPORTANT: Use express.text({ type: '*/*' }) so rawBody works for BOTH plain JSON & AES-256
app.post('/runotp/webhook', express.text({ type: '*/*', limit: '256kb' }), async (req, res) => {
  try {
    const rawBody = typeof req.body === 'string' ? req.body : '';
    const timestamp = req.header('X-RunOTP-Timestamp') || '';
    const signature = req.header('X-RunOTP-Signature') || '';
    const idempotencyKey = req.header('X-Idempotency-Key') || '';
    const retryAttempt = req.header('X-Retry-Attempt') || '1';

    // 1. Verify HMAC-SHA256 signature & 5-minute replay window
    if (!runOtp.verifySignature(rawBody, timestamp, signature)) {
      return res.status(401).json({ code: '401', status: 'invalid_signature' });
    }

    // 2. Decrypt (if AES-256 enabled in Settings) or parse plain JSON automatically
    const data = runOtp.decryptWebhook(rawBody);
    if (!data || data.key !== runOtp.apiKey) {
      return res.status(401).json({ code: '401', status: 'unauthorized_key' });
    }

    // 3. Idempotency check (safely acknowledge retries without duplicate activation)
    if (idempotencyKey && processedKeys.has(idempotencyKey)) {
      return res.status(200).json({ code: '200', status: 'already_processed' });
    }

    // 4. Inspect verified fields
    const eventType = data.event || 'otp_received'; // 'otp_received' or 'message_received'
    const channel = data.channel || 'whatsapp';     // 'whatsapp' or 'telegram'
    const phone = data.sender || '';                // Verified international digits e.g. 201012345678
    const otp = data.otp || '';                     // Extracted OTP code from 2nd brackets
    const fullMessage = data.message || '';
    const mediaUrl = data.media_url || '';
    const balance = data.balance;

    // ---------- YOUR BUSINESS LOGIC HERE (Must finish in < 5 seconds) ----------
    if (eventType === 'otp_received' && otp) {
      console.log(`[RunOTP] Verified via ${channel} | Phone: ${phone} | OTP: ${otp} | Attempt: ${retryAttempt}`);
      // TODO: Match (otp) in your DB/cache and mark user/order as verified with (phone)
    } else {
      console.log(`[RunOTP] Inbound message via ${channel} from ${phone}: ${fullMessage}`, mediaUrl);
      // TODO: Handle general customer reply (Dedicated VIP Catch-All mode)
    }
    // ---------------------------------------------------------------------------

    if (idempotencyKey) processedKeys.add(idempotencyKey);

    return res.status(200).json({
      code: '200',
      status: 'success',
      remaining_balance: balance
    });
  } catch (err) {
    console.error('[RunOTP Webhook Error]:', err);
    return res.status(500).json({ code: '500', status: 'server_error' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`RunOTP webhook listening on port ${PORT}`));
Frontend Polling Pattern (Notify the user's browser once your Webhook arrives)

When using Custom REST API (Path B), poll your own backend endpoint every 2.5 seconds (and immediately when the user switches back from WhatsApp/Telegram via visibilitychange):

JavaScript — Frontend Status Polling
async function checkOtpStatus(otpRef) {
  const res = await fetch('/api/check-otp?ref=' + encodeURIComponent(otpRef), { cache: 'no-store' });
  const data = await res.json();
  if (data.verified) {
    window.location.href = '/dashboard'; // User verified!
  }
}
const timer = setInterval(() => checkOtpStatus(currentRef), 2500);
document.addEventListener('visibilitychange', () => {
  if (!document.hidden) checkOtpStatus(currentRef);
});
POST https://api.runotp.com/v1/messages Dedicated VIP ($9.00 / 30 days)

Send outbound WhatsApp text ($0.01) or images, video, audio & PDFs ($0.02) strictly through your paired Dedicated VIP WhatsApp number.

WhatsApp 24-Hour Policy Warning: Only message users who initiated contact first, within 24 hours of their last message. Cold spam risks Meta banning your WhatsApp number. VIP outbound never falls back to shared numbers (returns 503 if disconnected).
Request JSON
{
  "apiKey": "YOUR_API_KEY",
  "apiSecret": "••••••••••••••••",
  "destinationNumber": "201012345678",
  "message": "Your order #9021 is confirmed!",
  "mediaUrl": "",
  "clientRef": "ORD_9021",
  "typingDelay": 2000
}
Response JSON (200 OK)
{
  "success": true,
  "messageId": "3EB0C767D82A1B904F",
  "clientRef": "ORD_9021",
  "remainingBalance": 14.84,
  "_error": ""
}
View outbound parameters
ParameterStatusDescription
destinationNumberRequiredRecipient digits only, international format without + (e.g. 201012345678).
messageRequiredText body or media caption.
mediaUrlOptionalPublic HTTPS image, video, audio, or PDF URL (≤ 10 MB). Empty "" for text-only.
clientRefOptionalYour order/system reference ID.
typingDelayOptionalTyping indicator duration in milliseconds (e.g. 2000 = 2 seconds; default 2000, max 10000).
Outbound VIP Code Example
Node.js (Express / JavaScript) — Send Outbound VIP Message (Text & Media)
const { RunOTPClient } = require('./runotp-client');
const runOtp = new RunOTPClient();

async function sendOrderConfirmation() {
  try {
    const result = await runOtp.sendOutbound(
      '201012345678',                                   // International digits only (no + or 00)
      'Welcome! Your order #9021 has been confirmed.',  // Text body or media caption
      '',                                               // Optional public HTTPS image/video/audio/PDF URL (<= 10MB)
      'ORD_9021',                                       // Your internal reference ID
      2000                                              // Typing indicator duration in ms (max 10000)
    );

    if (result.success) {
      console.log('Delivered! Message ID:', result.messageId);
      console.log('Remaining Balance   :', result.remainingBalance);
    } else {
      console.error('Delivery failed:', result._error || result);
    }
  } catch (err) {
    console.error('Outbound API request failed:', err.message);
  }
}

sendOrderConfirmation();
Channel Modes & Live Pricing
Shared Pool — $0 / month + $0.01 / verified OTP Zero setup on RunOTP's load-balanced WhatsApp & Telegram gateways. Inbound OTP verification only — pay strictly per unique completed verification.
Dedicated VIP — $9.00 / 30 days + $0.01 / text · $0.02 / media or PDF Pair your own branded WhatsApp line via QR in Settings. Unlocks Catch-All inbound messages + Outbound VIP text, images, video & PDFs. Smart renewal charges $0 during inactive months.
Flash Start Auto-Setup & Wallet Status API
POST https://api.runotp.com/v1/flash/config  ·  Header: x-api-secret
// 1) 1-Click Auto-Configure Flash Start (used by Store Plugins & Starter Kits):
{
  "apiKey": "YOUR_API_KEY",
  "apiSecret": "YOUR_API_SECRET",
  "redirectUrl": "https://yourstore.com/verify/callback",
  "brandName": "My Store",
  "theme": "auto",         // "auto" + brandColor/isDark, or lock any of the 10 themes
  "brandColor": "#10B981",
  "isDark": true,
  "channels": "both"       // "both" | "whatsapp" | "telegram"
}

// 2) Check Current Wallet Balance & Config (Read-Only):
{ "apiKey": "YOUR_API_KEY", "apiSecret": "YOUR_API_SECRET", "action": "status" }
HTTP Status & Troubleshooting
StatusMeaningAction
200 OKSucceeded (or idempotent duplicate safely acknowledged).Process response normally.
400Missing field, malformed (ApiKey)(OTP) brackets, or blocked SSRF URL.Validate JSON fields & public HTTPS URLs.
401 / 403Invalid API keys, suspended account, or already-burned Flash token.Verify keys in Settings; never call FlashVerify twice.
402Insufficient prepaid wallet balance.Top up USD or EGP on TopUp.aspx.
429> 60 /v1/links calls/min per API Key (or > 1 call/20s per IP on hosted Go.aspx).Back off briefly and avoid rapid retry loops.
503Dedicated VIP WhatsApp session offline.Re-pair device in Settings or check Status.