Free Numbers Pricing Reviews Feedback Terms & Policy API Docs Blog About
Log in Get Started
6 views 5 min read
Back to Blog
API

OTP API Integration: Step-by-Step Python and PHP Examples

OTP API Integration: Step-by-Step Python and PHP Examples

If you are building a signup, login, or payment flow, you need a reliable OTP API integration. The goal is simple: send a code, receive it, verify it, and log everything. But the details matter, especially around error handling, retries, and code expiry. This guide walks through a clean OTP integration pattern in Python and PHP, with runnable examples you can adapt for your own stack.

Quick answer: To integrate an OTP API, generate a random code on your server, store it with an expiry and a hashed value, call the provider API to deliver it, then verify the submitted code against the hash within the expiry window. Never trust the client; always verify server-side.

What You Need

  • A provider account and API key. Create one at SMS Feel.
  • A rented virtual number or a sender ID, depending on the provider.
  • A database table for OTP requests.
  • Python 3 or PHP 8 installed.

Designing the OTP Flow

  1. User submits a phone number.
  2. Server generates a 6-digit code using a cryptographically secure RNG.
  3. Server stores a hash of the code, the phone, an expiry time (for example, five minutes), and a rate-limit counter.
  4. Server calls the SMS provider API to send the code.
  5. User submits the code.
  6. Server hashes the submitted code and compares it with the stored hash.
  7. Server checks the expiry and the attempt count.
  8. Server marks the OTP as used and returns success.

Database Schema

A minimal table works for most apps:

  • id — primary key
  • phone — the number the code was sent to
  • code_hash — SHA-256 of the OTP
  • expires_at — timestamp
  • attempts — integer
  • used — boolean
  • created_at — timestamp

Python Example

This snippet shows the send and verify steps in Python using the requests library and the SMS Feel API pattern. Replace the endpoint and payload to match the current docs at SMS Feel docs.

import hashlib, secrets, time, requests
from datetime import datetime, timedelta

API_KEY = "YOUR_API_KEY"
BASE = "https://api.smsfeel.example"  # replace with current endpoint

def generate_code():
    return str(secrets.randbelow(900000) + 100000)

def send_otp(phone, code):
    payload = {"to": phone, "message": f"Your code is {code}"}
    headers = {"Authorization": f"Bearer {API_KEY}"}
    r = requests.post(f"{BASE}/send", json=payload, headers=headers, timeout=10)
    r.raise_for_status()
    return r.json()

def store_otp(db, phone, code):
    code_hash = hashlib.sha256(code.encode()).hexdigest()
    expires = datetime.utcnow() + timedelta(minutes=5)
    db.execute("INSERT INTO otps (phone, code_hash, expires_at, attempts, used) VALUES (?,?,?,?,?)",
               (phone, code_hash, expires, 0, False))

def verify_otp(db, phone, submitted):
    row = db.execute("SELECT code_hash, expires_at, attempts, used FROM otps WHERE phone=? ORDER BY id DESC LIMIT 1", (phone,)).fetchone()
    if not row or row["used"] or row["expires_at"] < datetime.utcnow() or row["attempts"] >= 5:
        return False
    ok = row["code_hash"] == hashlib.sha256(submitted.encode()).hexdigest()
    db.execute("UPDATE otps SET attempts=attempts+1, used=? WHERE phone=?", (ok, phone))
    return ok

PHP Example

The same flow in PHP using cURL and PDO:

<?php
function generate_code() {
    return str_pad((string)random_int(0, 999999), 6, "0", STR_PAD_LEFT);
}

function send_otp($phone, $code) {
    $payload = json_encode(["to" => $phone, "message" => "Your code is " . $code]);
    $ch = curl_init("https://api.smsfeel.example/send");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("API_KEY"), "Content-Type: application/json"],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function store_otp($pdo, $phone, $code) {
    $hash = hash("sha256", $code);
    $expires = date("Y-m-d H:i:s", time() + 300);
    $stmt = $pdo->prepare("INSERT INTO otps (phone, code_hash, expires_at, attempts, used) VALUES (?,?,?,0,0)");
    $stmt->execute([$phone, $hash, $expires]);
}

function verify_otp($pdo, $phone, $submitted) {
    $stmt = $pdo->prepare("SELECT code_hash, expires_at, attempts, used FROM otps WHERE phone=? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$phone]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row || $row["used"] || strtotime($row["expires_at"]) < time() || $row["attempts"] >= 5) return false;
    $ok = hash_equals($row["code_hash"], hash("sha256", $submitted));
    $pdo->prepare("UPDATE otps SET attempts=attempts+1, used=? WHERE phone=?")->execute([(int)$ok, $phone]);
    return $ok;
}
?>

Error Handling and Rate Limiting

  • Retry the send call on network errors with exponential backoff.
  • Cap attempts per phone and per IP.
  • Return generic errors to the client to avoid enumeration.
  • Log provider response codes for debugging.
  • Alert when send failure rates spike.

Frequently Asked Questions

Should I store the OTP in plain text?

No. Store a hash. If your database leaks, plain-text OTPs become a direct account takeover vector.

How long should an OTP be valid?

Five minutes is a good default. Shorter for banking, longer only if you have strong rate limits.

Can I use the same API for testing and production?

Use separate API keys and, ideally, separate numbers for staging. See SMS Feel docs for environment setup.

What happens if the SMS fails to send?

Return a clear error, do not consume the OTP, and let the user retry. Never confirm the send until the provider acknowledges it.

Is the SMS API compatible with my framework?

The API is HTTP-based, so it works with any language. The two examples above cover Python and PHP, the two most common stacks.

Conclusion

A clean OTP API integration is mostly about server-side discipline: hashed codes, short expiry, strict rate limits, and clear error handling. Copy the examples above, adapt them to your stack, and start with a test number from SMS Feel.

Related reading: more API and developer guides on the SMS Feel blog.

Tags

#otp api integration #sms verification api python #sms api php example #developer otp api #otp api #rest api
Contact us