OTP SMS API in PHP and .NET (C#): send, verify and webhooks

Written and reviewed by the DiOTP team Published 30 November 2026Last updated 30 November 2026

7 min read

This guide shows how to call an SMS API from PHP and from C# to send and check one-time passwords. If you are planning an OTP integration in PHP, you will find a dependency-free curl version and a Laravel version. If you work in .NET, there is an ASP.NET Core minimal API that uses HttpClient, records and System.Net.Http.Json. All three talk to the same two DiOTP endpoints, keep the API key on the server, and turn API errors into clear messages for your users.

The flow in both languages

Phone verification needs only two calls. Your server asks DiOTP to send a code to a number and gets back a request_id. Later, when the user types the code, your server sends that request_id and the code to the verify endpoint. A 200 reply means the number belongs to the person in front of the screen.

  1. Your form posts the mobile number to your own backend, never to https://api-diotp.diorbit.com/v1 directly.
  2. Your backend calls POST /v1/otp/send with the API key and returns only the request_id to the browser.
  3. The user enters the code. Your form posts the request_id and the code back to your backend.
  4. Your backend calls POST /v1/otp/verify. On 200 it marks the number verified and starts the session.

DiOTP generates the code, stores it and checks it, so your database never holds a secret that could leak. Codes expire after 5 minutes, allow 5 attempts and can be verified only once. The full field list is in the OTP API docs, with separate pages for sending an OTP and verifying an OTP.

Why the key stays on the server: anyone can read code that runs in a browser or a mobile app. A leaked key lets a stranger send messages that you pay for. Keep it in an environment variable such as DIOTP_API_KEY, and let only your backend use it.

No package needed in PHP or .NET

There is no PHP or .NET package, and you do not need one: the API is two HTTPS POST requests with a JSON body. The sections below show those calls with plain curl, with Laravel's Http facade, and with HttpClient in C#. Official SDKs exist for Node.js and Python.

OTP integration in PHP with curl (SMS API PHP example)

The first version uses only the curl and json extensions, which almost every PHP host already has. A single helper sends a JSON request and returns the status code and the decoded body. One file handles both actions, chosen by a query parameter.

The send action adds an Idempotency-Key header. If the call fails with 503 sending_unavailable or the connection drops, the helper retries once with the same key, so the user can never receive two codes for one tap.

otp.php

<?php
// POST otp.php?action=send    {"phone": "9876543210"}
// POST otp.php?action=verify  {"requestId": "...", "code": "482913"}
declare(strict_types=1);
header("Content-Type: application/json");

const DIOTP_API = "https://api-diotp.diorbit.com/v1";

function diotp_post(string $path, array $body, array $headers = []): array
{
    $ch = curl_init(DIOTP_API . $path);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => array_merge([
            "Authorization: Bearer " . getenv("DIOTP_API_KEY"),
            "Content-Type: application/json",
            "Accept: application/json",
        ], $headers),
        CURLOPT_POSTFIELDS     => json_encode($body),
    ]);
    $raw = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    if ($raw === false) {
        // Network failure: treat it like a temporary outage.
        return [503, ["error" => ["code" => "sending_unavailable"]]];
    }
    return [$status, json_decode($raw, true) ?? []];
}

function reply(int $status, array $data): never
{
    http_response_code($status);
    echo json_encode($data);
    exit;
}

$in = json_decode(file_get_contents("php://input"), true) ?? [];
$action = $_GET["action"] ?? "";

if ($action === "send") {
    $phone = preg_replace("/[^0-9]/", "", (string) ($in["phone"] ?? ""));
    if (!preg_match("/^[6-9][0-9]{9}$/", $phone)) {
        reply(400, ["error" => "invalid_phone"]);
    }
    $body = ["to" => $phone, "country_code" => 91, "purpose" => "login"];
    $key = ["Idempotency-Key: " . bin2hex(random_bytes(16))];

    [$status, $data] = diotp_post("/otp/send", $body, $key);
    if ($status === 503) {
        [$status, $data] = diotp_post("/otp/send", $body, $key); // same key, safe
    }
    if ($status !== 200) {
        reply($status, ["error" => $data["error"]["code"] ?? "unknown"]);
    }
    reply(200, ["requestId" => $data["request_id"], "expiresAt" => $data["expires_at"]]);
}

if ($action === "verify") {
    [$status, $data] = diotp_post("/otp/verify", [
        "request_id" => (string) ($in["requestId"] ?? ""),
        "code"       => (string) ($in["code"] ?? ""),
    ]);
    if ($status !== 200) {
        reply($status, ["error" => $data["error"]["code"] ?? "unknown"]);
    }
    // Verified: start the session for this user before replying.
    reply(200, ["verified" => true]);
}

reply(404, ["error" => "unknown_action"]);

The never return type needs PHP 8.1 or later. On older versions, drop the return type and keep the exit. Set DIOTP_API_KEY in your server or PHP-FPM pool configuration, not in a file inside the web root.

Laravel: the same calls with the Http facade

Laravel ships an HTTP client built on Guzzle, so you do not need curl calls at all. Add the key to your .env file and expose it through config/services.php, which keeps it out of your code and lets config caching work.

config/services.php (excerpt)

'diotp' => [
    'key' => env('DIOTP_API_KEY'),
],

The routes below use the Http facade. withToken sets the Bearer header, withHeaders adds the Idempotency-Key, and post sends the body as JSON by default.

routes/api.php

<?php

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

Route::post('/otp/send', function (Request $request) {
    $data = $request->validate(['phone' => ['required', 'regex:/^[6-9][0-9]{9}$/']]);

    try {
        $response = Http::withToken(config('services.diotp.key'))
            ->withHeaders(['Idempotency-Key' => (string) Str::uuid()])
            ->timeout(15)
            ->post('https://api-diotp.diorbit.com/v1/otp/send', [
                'to' => $data['phone'],
                'country_code' => 91,
                'purpose' => 'login',
            ]);
    } catch (ConnectionException) {
        return response()->json(['error' => 'sending_unavailable'], 503);
    }

    if ($response->failed()) {
        return response()->json(['error' => $response->json('error.code')], $response->status());
    }
    return ['requestId' => $response->json('request_id')];
});

Route::post('/otp/verify', function (Request $request) {
    $data = $request->validate([
        'requestId' => ['required', 'string'],
        'code' => ['required', 'string', 'min:4', 'max:10'],
    ]);

    $response = Http::withToken(config('services.diotp.key'))
        ->timeout(15)
        ->post('https://api-diotp.diorbit.com/v1/otp/verify', [
            'request_id' => $data['requestId'],
            'code' => $data['code'],
        ]);

    if ($response->failed()) {
        return response()->json(['error' => $response->json('error.code')], $response->status());
    }
    // Verified: log the user in here, for example with Auth::login($user).
    return ['verified' => true];
});

Laravel 11 and later create routes/api.php only after you run php artisan install:api. Earlier versions include it by default. Add throttling middleware to the send route as well, so one visitor cannot ask for codes in a loop.

SMS API .NET example: an ASP.NET Core minimal API in C#

This is a complete SMS API C# example. For .NET, the cleanest pattern is a named HttpClient registered with IHttpClientFactory. The factory manages connection pooling for you, and the base address, timeout and Bearer header live in one place. Requests and responses are C# records, and System.Net.Http.Json handles the JSON with PostAsJsonAsync and ReadFromJsonAsync.

The API uses snake_case field names such as request_id and country_code. A JsonSerializerOptions with JsonNamingPolicy.SnakeCaseLower maps them to normal C# property names, which needs .NET 8 or later. The key comes from configuration, and ASP.NET Core reads environment variables into configuration by default, so DIOTP_API_KEY works with no extra code. In development you can keep it in user secrets instead.

Program.cs

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

// Reads the DIOTP_API_KEY environment variable (or user secrets in development).
var apiKey = builder.Configuration["DIOTP_API_KEY"]
    ?? throw new InvalidOperationException("DIOTP_API_KEY is not set.");

builder.Services.AddHttpClient("diotp", client =>
{
    client.BaseAddress = new Uri("https://api-diotp.diorbit.com/v1/");
    client.Timeout = TimeSpan.FromSeconds(15);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
});

var app = builder.Build();

var snake = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
};

app.MapPost("/api/otp/send", async (SendInput input, IHttpClientFactory factory) =>
{
    var phone = new string((input.Phone ?? "").Where(char.IsAsciiDigit).ToArray());
    if (phone.Length != 10 || phone[0] < '6')
        return Results.BadRequest(new { error = "invalid_phone" });

    var client = factory.CreateClient("diotp");
    var idempotencyKey = Guid.NewGuid().ToString();

    async Task<HttpResponseMessage> SendOnce()
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, "otp/send")
        {
            Content = JsonContent.Create(new SendRequest(phone, 91, "login"), options: snake),
        };
        request.Headers.Add("Idempotency-Key", idempotencyKey);
        return await client.SendAsync(request);
    }

    try
    {
        var response = await SendOnce();
        if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
            response = await SendOnce(); // same key, so no second code

        if (!response.IsSuccessStatusCode)
            return await ToError(response);

        var sent = await response.Content.ReadFromJsonAsync<SendResponse>(snake);
        return Results.Ok(new { requestId = sent!.RequestId, expiresAt = sent.ExpiresAt });
    }
    catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
    {
        return Results.Json(new { error = "sending_unavailable" }, statusCode: 503);
    }
});

app.MapPost("/api/otp/verify", async (VerifyInput input, IHttpClientFactory factory) =>
{
    var client = factory.CreateClient("diotp");
    var response = await client.PostAsJsonAsync(
        "otp/verify", new VerifyRequest(input.RequestId, input.Code), snake);

    if (!response.IsSuccessStatusCode)
        return await ToError(response);

    var result = await response.Content.ReadFromJsonAsync<VerifyResponse>(snake);
    // result!.Verified is true here: sign the user in.
    return Results.Ok(new { verified = result!.Verified });
});

async Task<IResult> ToError(HttpResponseMessage response)
{
    ApiError? body = null;
    try { body = await response.Content.ReadFromJsonAsync<ApiError>(snake); }
    catch (JsonException) { }
    return Results.Json(new { error = body?.Error.Code ?? "unknown" },
        statusCode: (int)response.StatusCode);
}

app.Run();

// What the browser sends to you.
record SendInput(string? Phone);
record VerifyInput(string RequestId, string Code);

// What you send to DiOTP, and what comes back.
record SendRequest(string To, int CountryCode, string Purpose);
record SendResponse(string RequestId, string Channel, DateTimeOffset ExpiresAt);
record VerifyRequest(string RequestId, string Code);
record VerifyResponse(string RequestId, bool Verified, DateTimeOffset VerifiedAt);
record ApiError(ApiErrorBody Error);
record ApiErrorBody(string Code, string Message, string? RequestId);

Two details matter here. The send route builds a fresh HttpRequestMessage for each attempt, because a request message cannot be sent twice, but it reuses the same Idempotency-Key. The verify route uses PostAsJsonAsync directly, since a verify call has no idempotency header and is free.

The browser-facing records bind with the default web settings, so a JSON body of {"phone": "9876543210"} reaches SendInput without any attributes.

Verifying webhook signatures

Webhooks tell your server what happened after the send: otp.sent, otp.delivered, otp.failed and otp.verified. Add an HTTPS URL under Webhooks in your dashboard, and copy the signing secret, which starts with whsec_ and is shown only once. Store it as DIOTP_WEBHOOK_SECRET next to your API key.

Every delivery carries X-Diorbit-Event, X-Diorbit-Timestamp and X-Diorbit-Signature. The signature is the hex HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with your secret. Compute the same value and compare it in constant time. Use the body exactly as received, because parsing and re-encoding the JSON changes the bytes. The webhooks reference lists every field.

webhook.php

<?php
$raw       = file_get_contents("php://input");
$timestamp = $_SERVER["HTTP_X_DIORBIT_TIMESTAMP"] ?? "";
$signature = $_SERVER["HTTP_X_DIORBIT_SIGNATURE"] ?? "";
$secret    = getenv("DIOTP_WEBHOOK_SECRET");

$expected = hash_hmac("sha256", $timestamp . "." . $raw, $secret);
$fresh    = ctype_digit($timestamp) && abs(time() - (int) $timestamp) < 300;

if (!$fresh || !hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
// Save $event["event"] and $event["request_id"], then do slow work later.
http_response_code(204);

Webhook endpoint in Program.cs

// Add these two using directives at the top of Program.cs.
using System.Security.Cryptography;
using System.Text;

app.MapPost("/webhooks/diotp", async (HttpRequest request, IConfiguration config) =>
{
    using var buffer = new MemoryStream();
    await request.Body.CopyToAsync(buffer);
    var body = buffer.ToArray();

    var timestamp = request.Headers["X-Diorbit-Timestamp"].ToString();
    var signature = request.Headers["X-Diorbit-Signature"].ToString();
    if (!long.TryParse(timestamp, out var sent)
        || Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - sent) > 300)
        return Results.Unauthorized();

    var key = Encoding.UTF8.GetBytes(config["DIOTP_WEBHOOK_SECRET"]!);
    var signed = Encoding.UTF8.GetBytes(timestamp + ".").Concat(body).ToArray();
    var expected = HMACSHA256.HashData(key, signed);

    byte[] given;
    try { given = Convert.FromHexString(signature); }
    catch (FormatException) { return Results.Unauthorized(); }

    if (!CryptographicOperations.FixedTimeEquals(expected, given))
        return Results.Unauthorized();

    // Valid: store the event and return quickly.
    return Results.NoContent();
});

The C# version compares raw bytes instead of hex strings, which avoids any doubt about upper or lower case. Both versions reject timestamps more than five minutes old, so a captured request cannot be replayed later.

Reply with a 2xx within 10 seconds. If you do not, DiOTP retries after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours, six attempts in all. Because a retry can arrive after your first reply was lost, make your handler safe to run twice for the same request_id and event.

Error handling

Every error has the same shape: an error object with a code, a message and a request_id. Branch on the code, not on the message text, and show your own wording to users. The table covers the codes a phone verification screen meets most often.

StatusCodeWhat to do
400invalid_codeWrong code. Let the user try again.
404not_foundUnknown request_id. Start again with a new send.
409already_verifiedThe code was already used. Treat the number as verified if your own record agrees.
409not_pendingThe request has ended. Offer a new code.
410expiredMore than 5 minutes passed. Offer a new code.
429too_many_attemptsFive attempts used. Offer a new code.
429resend_cooldownKeep the resend button disabled for 30 seconds.
429phone_hourly_limit, phone_daily_limitAsk the user to try again later.
401unauthorizedCheck the key on your server. Do not show this to users.
403trial_restrictedTest mode sends only to your own verified number.
503sending_unavailableRetry with the same Idempotency-Key.

A request refused by a limit is not sent and not charged. Log the API request_id with every failure, since it is the fastest way for support to trace a problem. Never log the code the user typed.

Your own send route also needs protection. Put a bot check and a per-IP limit in front of it before launch; the SMS pumping protection guide explains why public OTP forms attract abuse.

Testing and going live

New accounts start in test mode, where messages go only to the mobile number you verified at sign-up. That is enough to try the whole flow: send, a wrong code, a correct code, a second verify and a resend inside 30 seconds. When it all behaves, request to go live from the dashboard. After a business check, the same keys send to any Indian number, with no code change.

OTP API documentation Webhook events and signatures OTP SMS pricing

SDKs Postman collection

Questions people ask

Use the curl extension, as in the first example. It sends a JSON POST with a Bearer header and reads the JSON reply, with no packages to install.

Start building your customer messaging with DiOTP

Free test credits on sign-up, API keys in a minute, and a team that picks up the phone.