NewBulkSMSIraq is now an official Meta Tech Partner for WhatsApp in Iraq.Read the news
Guides

How to Send SMS and OTP from PHP and Laravel in Iraq (with Code)

Working PHP 8 and Laravel code for sending SMS, sending OTP codes on WhatsApp with SMS fallback and verifying them through the Bulk SMS Iraq API, plus error handling, number formatting and security.

Bulk SMS Iraq logoBulk SMS Iraq teamErbil, Kurdistan Region 8 min readUpdated
PHP and Laravel code sending an SMS and a WhatsApp OTP to an Iraqi phone number through the Bulk SMS Iraq API
On this page
  1. What you need before you start
  2. Iraqi phone number format (964…)
  3. Send SMS and OTP with plain PHP (cURL)
  4. Laravel SMS API and OTP verification
  5. Handling API errors
  6. Security checklist for PHP OTP API integrations
  7. Testing your integration

To send SMS and OTP codes from PHP or Laravel in Iraq, you call three JSON endpoints on the Bulk SMS Iraq API with a Bearer API key: one sends an SMS, one sends a verification code on WhatsApp with automatic SMS fallback, and one checks the code your user typed. No SDK is needed; PHP’s cURL extension or Laravel’s Http client is enough.

Below is copy-ready code for plain PHP and for Laravel, plus Iraqi number formatting, the error codes you will actually meet and the security rules that protect your balance.

What you need before you start

  • An account and API key. Create an account on our sign-up page. Your API key is in your account in the customer portal.
  • A sender ID. This is your registered app or brand name, sent as sender_id in every request. See our guide to SMS sender ID registration in Iraq.
  • PHP 8.1 or later with the cURL extension, or Laravel 10 or later.
  • The API reference. All parameters and error codes are in the API documentation. The base URL is https://gateway.standingtech.com/api, and the API integration page shows the overall flow.

Iraqi phone number format (964…)

The API expects numbers in international format without + or 00, such as 9647701234567. Users in Iraq usually type the local form, 0770 123 4567, so normalise the input on your server before you call the API. This works for Zain (078x/079x), Asiacell (077x) and Korek (075x) numbers:

function normalize_iraqi_mobile(string $input): ?string
{
    $n = preg_replace('/\D+/', '', $input);   // remove +, spaces, dashes

    if (str_starts_with($n, '00')) {
        $n = substr($n, 2);                    // 00964... becomes 964...
    }
    if (str_starts_with($n, '9640')) {
        $n = '964' . substr($n, 4);            // +964 0770... becomes 964770...
    } elseif (str_starts_with($n, '0')) {
        $n = '964' . substr($n, 1);            // 0770... becomes 964770...
    } elseif (str_starts_with($n, '7')) {
        $n = '964' . $n;                       // 770... becomes 964770...
    }

    return preg_match('/^9647\d{9}$/', $n) === 1 ? $n : null;
}

The API also rejects invalid Iraqi numbers with error 1216 before sending, so you never pay for them.

Send SMS and OTP with plain PHP (cURL)

All three endpoints take and return JSON, so one helper covers every request. Keep your key in an environment variable, BSI_API_KEY, never in the code.

<?php
declare(strict_types=1);

const BSI_API = 'https://gateway.standingtech.com/api';

function bsi_post(string $path, array $payload): array
{
    $ch = curl_init(BSI_API . $path);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . getenv('BSI_API_KEY'),
            'Content-Type: application/json',
            'Accept: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload, JSON_THROW_ON_ERROR),
    ]);

    $body = curl_exec($ch);
    if ($body === false) {
        throw new RuntimeException('Network error: ' . curl_error($ch));
    }

    $data = json_decode($body, true);

    return is_array($data) ? $data : ['status' => 'failed', 'error' => ['code' => null, 'message' => 'Unexpected response']];
}

Send an SMS

For order updates and alerts, call POST /v5/sms/send with recipient, sender_id and message. The API detects English (160 characters per part) or Arabic and Kurdish (70 per part) and returns the parts charged.

$res = bsi_post('/v5/sms/send', [
    'recipient' => '9647701234567',
    'sender_id' => 'YourBrand',
    'message'   => 'Your order 1042 from YourShop arrives today at 2:30 PM.',
]);

if (($res['status'] ?? '') === 'success') {
    echo 'Accepted, parts charged: ' . $res['data']['sms_count'];
} else {
    echo 'Error ' . ($res['error']['code'] ?? '') . ': ' . ($res['error']['message'] ?? '');
}

Send an OTP on WhatsApp with SMS fallback

Call POST /v5/otp/send with channel set to whatsapp and fallback set to sms. If the number has no WhatsApp account, the same code goes out by SMS. With "message": "auto" the API generates a 6-digit code and writes the message in the language you set in lang (en, ar, ku or fa).

session_start();

$phone = normalize_iraqi_mobile($_POST['phone'] ?? '');
if ($phone === null) {
    http_response_code(422);
    exit('Please enter a valid Iraqi mobile number.');
}

$res = bsi_post('/v5/otp/send', [
    'recipient' => $phone,
    'sender_id' => 'YourApp',
    'channel'   => 'whatsapp',
    'fallback'  => 'sms',
    'message'   => 'auto',
    'lang'      => 'ar',
]);

if (($res['status'] ?? '') === 'success') {
    $_SESSION['otp_id']    = $res['id'];   // needed to verify the code
    $_SESSION['otp_phone'] = $phone;
}

Verify the code

When the user types the code, send it with the stored id to POST /v5/otp/verify. A correct code returns {"status":"success"}; a wrong one returns 1512, and an expired or locked code returns 1507.

$res = bsi_post('/v5/otp/verify', [
    'id'   => $_SESSION['otp_id'] ?? '',
    'code' => trim($_POST['code'] ?? ''),
]);

if (($res['status'] ?? '') === 'success') {
    $_SESSION['verified_phone'] = $_SESSION['otp_phone'];
    unset($_SESSION['otp_id'], $_SESSION['otp_phone']);
    $message = 'Your number is verified.';
} else {
    $message = match ((string) ($res['error']['code'] ?? '')) {
        '1512'  => 'That code is not correct. Please try again.',
        '1507'  => 'This code has expired. Please request a new one.',
        default => 'We could not check the code. Please try again.',
    };
}

echo $message;

Laravel SMS API and OTP verification

In Laravel the same calls fit into a config entry, a service class on the Http client, and a controller with two routes.

Configuration: .env and config/services.php

BSI_API_KEY=your-api-key
BSI_SENDER_ID=YourApp
// config/services.php
'bulksmsiraq' => [
    'base_url'  => env('BSI_BASE_URL', 'https://gateway.standingtech.com/api'),
    'key'       => env('BSI_API_KEY'),
    'sender_id' => env('BSI_SENDER_ID'),
],

A small service class

Laravel’s Http client does not throw on 4xx responses by default, so the controller can read the JSON error code directly.

<?php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;

class BulkSmsIraq
{
    private function client(): PendingRequest
    {
        return Http::baseUrl(config('services.bulksmsiraq.base_url'))
            ->withToken(config('services.bulksmsiraq.key'))
            ->acceptJson()
            ->asJson()
            ->timeout(15);
    }

    public function sendSms(string $recipient, string $message): Response
    {
        return $this->client()->post('v5/sms/send', [
            'recipient' => $recipient,
            'sender_id' => config('services.bulksmsiraq.sender_id'),
            'message'   => $message,
        ]);
    }

    public function sendOtp(string $recipient, string $lang = 'en'): Response
    {
        return $this->client()->post('v5/otp/send', [
            'recipient' => $recipient,
            'sender_id' => config('services.bulksmsiraq.sender_id'),
            'channel'   => 'whatsapp',
            'fallback'  => 'sms',
            'message'   => 'auto',
            'lang'      => $lang,
        ]);
    }

    public function verifyOtp(string $id, string $code): Response
    {
        return $this->client()->post('v5/otp/verify', ['id' => $id, 'code' => $code]);
    }
}

Controller and routes

The controller normalises the number, sends the code, keeps the returned id in the session and checks the code on the second request. Put normalize_iraqi_mobile() from above in a helper file loaded through the autoload.files section of composer.json, or make it a method on the service.

<?php

namespace App\Http\Controllers;

use App\Services\BulkSmsIraq;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PhoneVerificationController extends Controller
{
    public function __construct(private BulkSmsIraq $bsi) {}

    public function send(Request $request): JsonResponse
    {
        $data = $request->validate([
            'phone' => ['required', 'string', 'max:20'],
            'lang'  => ['nullable', 'in:en,ar,ku,fa'],
        ]);

        $phone = normalize_iraqi_mobile($data['phone']);
        if ($phone === null) {
            return response()->json(['message' => 'Please enter a valid Iraqi mobile number.'], 422);
        }

        $res = $this->bsi->sendOtp($phone, $data['lang'] ?? 'en');
        if ($res->json('status') !== 'success') {
            return $this->fail($res->json('error.code'));
        }

        $request->session()->put('otp', ['id' => $res->json('id'), 'phone' => $phone]);

        return response()->json(['message' => 'We sent a code to your WhatsApp or by SMS.']);
    }

    public function verify(Request $request): JsonResponse
    {
        $data = $request->validate(['code' => ['required', 'digits:6']]);
        $otp  = $request->session()->get('otp');

        if (! $otp) {
            return response()->json(['message' => 'Please request a new code.'], 422);
        }

        $res = $this->bsi->verifyOtp($otp['id'], $data['code']);
        if ($res->json('status') !== 'success') {
            return $this->fail($res->json('error.code'));
        }

        $request->session()->forget('otp');
        $request->session()->put('verified_phone', $otp['phone']);

        return response()->json(['verified' => true]);
    }

    private function fail(mixed $code): JsonResponse
    {
        [$status, $message] = match ((string) $code) {
            '1907'         => [429, 'Please wait 30 seconds before requesting another code.'],
            '1905', '1906' => [429, 'Too many codes for this number. Please try again later.'],
            '1216'         => [422, 'This does not look like a valid Iraqi mobile number.'],
            '1512'         => [422, 'That code is not correct. Please try again.'],
            '1507'         => [410, 'This code has expired. Please request a new one.'],
            default        => [503, 'We could not complete the request. Please try again.'],
        };

        if ($status === 503) {
            Log::warning('Bulk SMS Iraq API error', ['code' => $code]);
        }

        return response()->json(['message' => $message], $status);
    }
}
// routes/web.php
use App\Http\Controllers\PhoneVerificationController;
use Illuminate\Support\Facades\Route;

Route::post('/verify-phone/send', [PhoneVerificationController::class, 'send'])
    ->middleware('throttle:3,1');
Route::post('/verify-phone/check', [PhoneVerificationController::class, 'verify'])
    ->middleware('throttle:10,1');

The routes live in web.php because they use the session (send the CSRF token from your form or SPA). For a stateless mobile API, store the id in the cache instead, keyed by the number, for example Cache::put("otp:{$phone}", $id, now()->addMinutes(30)), which matches the 30-minute code lifetime.

Handling API errors

Every failed request returns the same shape: {"status":"failed","error":{"code":"1216","message":"Invalid Phone Number for Iraq"}}. Check status first, then branch on error.code. These are the codes you are most likely to see:

CodeMeaningWhat to do
1907Only two OTP requests allowed in 30 secondsShow a resend countdown of 30 seconds
1906 / 1905Hourly or daily limit for the numberAsk the user to try later; ask us to whitelist test numbers
1216Invalid phone number for IraqAsk the user to check the number
1512Wrong codeLet the user try again (5 attempts in total)
1507Code expired or lockedOffer to send a new code
1002 / 1101Missing or invalid API keyCheck BSI_API_KEY on the server
1106Sender ID not allowed for this API keyUse a sender ID registered on your account
1503Insufficient balanceTop up your balance

Log the error code (never the OTP itself) so you can spot problems. The full list is in the documentation.

Security checklist for PHP OTP API integrations

  • Keep the key server-side. Load it from .env, keep .env out of version control, and never put the key in a mobile app or browser JavaScript.
  • Rate-limit your own endpoint. The API allows 2 OTPs per number per 30 seconds plus hourly and daily caps, but bots can rotate numbers. Throttle by IP and session too, as the throttle middleware does above.
  • Block SMS pumping. Fake sign-ups that request codes to many numbers drain your balance. Our OTP Firewall stops this traffic before it is sent.
  • Decide on the server. Only your backend calls verify and marks a number as verified. Never trust a “verified” flag from the client.
  • Never log codes. Keep OTPs and API keys out of logs and error trackers.
Show your own messages, not raw API errors.Map error codes to your own messages, as the fail() method does. That keeps internal details such as sender IDs and balance problems away from users.

Testing your integration

  1. Start in PostmanOpen our Postman collection, add your API key and send a code to your own phone before writing any code.
  2. Fake the API in automated testsLaravel’s Http::fake() returns a stored response, so your test suite never sends real messages. See the example below.
  3. Test the failure pathsRequest codes quickly to trigger 1907 and type a wrong code to see 1512.
  4. Ask for test credit and whitelistingOur team can add test credit to a new account and whitelist test numbers so hourly and daily limits do not block you.
public function test_send_stores_the_otp_id(): void
{
    Http::fake([
        '*/v5/otp/send' => Http::response([
            'status'  => 'success',
            'message' => 'Your message was accepted',
            'id'      => '6745f1c2a9e3b',
        ]),
    ]);

    $this->postJson('/verify-phone/send', ['phone' => '0770 123 4567'])->assertOk();

    $this->assertSame('6745f1c2a9e3b', session('otp.id'));
    Http::assertSent(fn ($request) => $request['recipient'] === '9647701234567'
        && $request['fallback'] === 'sms');
}

Integrating OTP into your PHP or Laravel app? Our developers in Erbil can review your setup on WhatsApp.

Contact us

Frequently asked questions

Is there an official PHP or Laravel package for the Bulk SMS Iraq API?

You don’t need one. The API is plain REST with JSON, so PHP’s built-in cURL extension or Laravel’s Http client is enough, as shown in this guide.

Do I have to generate and store the OTP code myself?

No. Send "message": "auto" and the API generates a 6-digit code, stores it and checks it when you call /v5/otp/verify. You only store the id from the send response.

Which phone number format does the API accept?

International format without + or 00, for example 9647701234567. Invalid Iraqi numbers are rejected with error 1216 before anything is sent, so you are not charged for them.

How can I test without sending many real messages?

Use Laravel’s Http::fake() in automated tests, and send real codes only to your own number. Ask our team for test credit, and to whitelist test numbers if you hit the hourly or daily limits.

What happens if the user does not have WhatsApp?

With channel whatsapp and fallback sms, the same code goes out by SMS automatically. A failed WhatsApp attempt is never charged, so you pay only the SMS price.

Share:

Ready to send your first code?

Get an API key today. Our team in Erbil helps you go live, in English, Arabic or Kurdish.