Search by

diorbit / diotp

Diorbit Technologies LLP

Official PHP SDK for the DiOTP OTP API: send and verify one-time passwords by SMS or WhatsApp.

dev-main 2026-11-30 12:54 UTC

This package is not auto-updated.

Last update: 2026-12-01 11:30:33 UTC


README

Latest version CI PHP version Licence

The official PHP SDK for DiOTP: send and verify one-time passwords by SMS or WhatsApp.

  • PHP 8.1 or newer.
  • PSR-18 HTTP with PSR-17 factories. Uses Guzzle 7 by default; bring any PSR-18 client you like.
  • Typed results, one exception class per error family, automatic retries with safe idempotency, and a webhook signature helper.

Install

composer require diorbit/diotp

Quickstart

Set DIOTP_API_KEY in your server's environment, then:

<?php
require 'vendor/autoload.php';

$diotp = new Diorbit\DiOTP\Client(); // reads DIOTP_API_KEY

$sent = $diotp->sendOtp(to: '9876543210'); // country code 91 by default
$check = $diotp->verifyOtp(requestId: $sent->requestId, code: '482913');

echo $check->verified ? 'Verified' : 'Not verified';

In a real app you send in one request, keep $sent->requestId (for example in the session), and verify when the user types the code. verifyOtp() returns only when the code matched; a wrong, expired or used code throws an exception (see Error handling).

Configuration

use Diorbit\DiOTP\Client;

$diotp = new Client(
    apiKey: 'dio_...',          // default: the DIOTP_API_KEY environment variable
    baseUrl: 'https://api-diotp.diorbit.com/v1',
    timeout: 10.0,               // seconds, for the default Guzzle client
    maxRetries: 2,               // automatic retries; 0 turns them off
);

$diotp = Client::fromEnvironment(maxRetries: 3); // same options, key from DIOTP_API_KEY

If no key is passed and DIOTP_API_KEY is not set, the constructor throws Diorbit\DiOTP\Exception\ConfigurationException. Keep the key on your server. The SDK never prints it: var_dump(), print_r() and (string) $diotp show it as dio_... and its last four characters.

Your own HTTP client

Pass any PSR-18 client and PSR-17 factories. The timeout option applies only to the default Guzzle client, so set the timeout on your own client.

$diotp = new Client(
    httpClient: $psr18Client,          // Psr\Http\Client\ClientInterface
    requestFactory: $psr17Factory,     // Psr\Http\Message\RequestFactoryInterface
    streamFactory: $psr17Factory,      // Psr\Http\Message\StreamFactoryInterface
);

Methods

Method API call Returns
sendOtp(string $to, int $countryCode = 91, string $channel = 'sms', string $purpose = 'login', ?string $template = null, ?string $idempotencyKey = null) POST /otp/send SendResult (requestId, channel, expiresAt, idempotencyKey)
verifyOtp(string $requestId, string $code) POST /otp/verify VerifyResult (requestId, verified, verifiedAt)
resendOtp(string $to, int $countryCode = 91, string $channel = 'sms', string $purpose = 'login', ?string $template = null) POST /otp/send SendResult
me() GET /me Account (clientId, clientName, clientStatus, keyId, keyName, keyLastFour)
usage(?string $period = null) GET /usage Usage (period, attempts, accepted, billableUnits, amount)
isTestMode() GET /me bool

$channel is sms or whatsapp. $template is a template id from the Templates page; leave it out to use your account's default. Usage::$amount is a decimal string such as "29.50", kept as a string so no precision is lost. Times are ISO 8601 strings as the API returns them.

Resending a code

resendOtp() is a helper, not a separate endpoint: the API has no resend call. It sends a new code through POST /otp/send with a new Idempotency-Key. The API allows one code to the same number every 30 seconds, so wait 30 seconds after the last send (show a timer in your app). Sooner, it throws RateLimitException with the code resend_cooldown. Verify with the requestId of the newest send.

Error handling

Every exception extends Diorbit\DiOTP\Exception\DiOTPException, which has:

  • getErrorCode(): the API's error.code, for example invalid_code. Branch on this.
  • getStatus(): the HTTP status, or null when no response arrived.
  • getRequestId(): the request_id to quote to support (from the error body or the X-Request-Id header).
  • getMessage(): a sentence for people.
use Diorbit\DiOTP\Exception;

try {
    $diotp->verifyOtp(requestId: $requestId, code: $code);
} catch (Exception\InvalidCodeException $e) {
    // 400 invalid_code: let the user try again (five attempts per code)
} catch (Exception\ExpiredException | Exception\ConflictException $e) {
    // 410 expired, 409 already_verified or not_pending: send a new code
} catch (Exception\RateLimitException $e) {
    // 429, for example too_many_attempts or resend_cooldown
    $wait = $e->getRetryAfter(); // seconds from Retry-After, or null
} catch (Exception\DiOTPException $e) {
    error_log("DiOTP {$e->getErrorCode()} ({$e->getRequestId()}): {$e->getMessage()}");
}
Exception When
AuthenticationException 401 unauthorized
InsufficientBalanceException 402 insufficient_balance
PermissionException 403, for example account_suspended
NotFoundException 404 not_found
ConflictException 409 already_verified, not_pending, idempotency_key_reused, channel_not_enabled
ExpiredException 410 expired
ValidationException 422 invalid_request, template_not_available
InvalidCodeException (extends ValidationException) 400 invalid_code
RateLimitException 429 resend_cooldown, phone_hourly_limit, phone_daily_limit, api_key_minute_limit, rate_limited, too_many_attempts
ServerException 5xx, for example 503 sending_unavailable
NetworkException no response: timeout, DNS, refused or reset connection (any PSR-18 ClientExceptionInterface)
TrialRestrictedException (extends PermissionException) 403 trial_restricted
TrialUsedUpException 402 trial_used_up
TestLimitException (extends RateLimitException) 429 test_limit
ConfigurationException no API key, or an option out of range
WebhookSignatureException a webhook failed verification

The three test-mode exceptions also implement the TrialException interface, so catch (Exception\TrialException $e) catches all of them. A code the SDK does not know yet maps by status to the closest class and keeps its raw code. getRetryAfter() reads the Retry-After header; the API does not send one today, so it is null.

Every code with its cause and fix: https://diotp.diorbit.com/docs/errors

Retries

The SDK retries automatically, up to maxRetries times (default 2), with exponential backoff and full jitter: a random wait between 0 and min(8, 0.5 * 2^attempt) seconds.

  • Retried: network errors and 5xx responses.
  • Never retried: 4xx responses, including 429. A RateLimitException is thrown at once with getRetryAfter() for you to decide.
  • Sends are safe to retry. Each sendOtp() call generates one Idempotency-Key (a UUID v4) and reuses it on every retry of that call, so a retry never delivers or bills twice. Pass your own idempotencyKey to make your own retries safe too. Reusing a key with a different body returns 409 idempotency_key_reused.
  • Verify retries less. The server counts every verify attempt against the five allowed per code, so verifyOtp() is retried only on network errors and 502, 503 and 504.

Webhooks

DiOTP signs each webhook delivery. X-Diorbit-Timestamp holds the Unix time and X-Diorbit-Signature the lowercase hex HMAC-SHA256 of {timestamp}.{raw body}, keyed with your endpoint's signing secret. Verify the raw body before you decode it:

use Diorbit\DiOTP\Exception\WebhookSignatureException;
use Diorbit\DiOTP\Webhook;

$rawBody = file_get_contents('php://input');

try {
    $event = Webhook::verify($rawBody, getallheaders(), (string) getenv('DIOTP_WEBHOOK_SECRET'));
} catch (WebhookSignatureException $e) {
    http_response_code(400);
    exit;
}

match ($event->event) {
    'otp.sent', 'otp.delivered', 'otp.failed', 'otp.verified' => handle($event),
    default => null,
};
http_response_code(200);

Webhook::verify() accepts PSR-7 style headers ($request->getHeaders()), plain arrays or $_SERVER, matching names case-insensitively. It rejects timestamps more than 300 seconds from now; pass toleranceSeconds to change that. When you already have the two values, use Webhook::verifySignature($rawBody, $signature, $timestamp, $secret). The comparison is constant-time (hash_equals).

WebhookEvent has event, createdAt, requestId, channel (sms or whatsapp), status (delivered or failed on delivery receipts) and data, the whole decoded payload.

Sandbox / test mode

Every new account starts in test mode. It is the real API with one restriction, not a simulator:

  • Codes go only to the mobile number verified at sign-up, with its country code. Any other number throws TrialRestrictedException (403 trial_restricted).
  • Test messages are free. When they run out, sends throw TrialUsedUpException (402 trial_used_up). Ask to go live from Account in the dashboard.
  • A live account switched back to test mode in the dashboard gets a daily allowance; past it, sends throw TestLimitException (429 test_limit).
  • The usual rate limits apply in test mode too.

$diotp->isTestMode() returns true when GET /me reports trial or pending_review. A live account switched to test mode still reports live, so check the dashboard for that case. Going live needs no code change: the same key and base URL keep working.

More: https://diotp.diorbit.com/docs/sandbox

Documentation

Full API documentation: https://diotp.diorbit.com/docs

Releases

Versions are published on Packagist. Packagist reads new tags from this repository through its GitHub webhook, so pushing a v* tag publishes the version; the release workflow runs the checks and creates the GitHub Release.

Licence

MIT. See LICENSE. Copyright (c) 2026 Diorbit Technologies LLP.