Send SMS and OTP codes from Laravel

Send SMS from a Laravel app with the HTTP client, and send and check one-time codes securely.

This guide sends SMS from a Laravel application with Fortwave, and uses it to send one-time passwords (OTP) for phone verification and login. It uses Laravel's HTTP client, so there is no package to install.

What you need

Add your key to the configuration

Put the key and your sender ID in .env. Never commit the key to your repository.

.env
FORTWAVE_API_KEY=your-api-key
FORTWAVE_SENDER=MyApp
config/services.php
// config/services.php
'fortwave' => [
    'key' => env('FORTWAVE_API_KEY'),
    'sender' => env('FORTWAVE_SENDER'),
    'webhook_secret' => env('FORTWAVE_WEBHOOK_SECRET'),
],

Create a small SMS service

POST /v1/sms sends one message. phone_number takes the number with + and the country code, sender is your approved sender ID (up to 11 letters and digits), and message is up to 600 characters.

app/Services/FortwaveSms.php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class FortwaveSms
{
    /**
     * Send one SMS and return Fortwave's response: the message id, status and credits.
     *
     * @return array{id: string, status: string, to: string, sender: string, item_count: int, remaining_items: int}
     */
    public function send(string $phoneNumber, string $message): array
    {
        return Http::withToken(config('services.fortwave.key'))
            ->acceptJson()
            ->timeout(10)
            ->post('https://rest.api.fortwave.io/v1/sms', [
                'phone_number' => $phoneNumber,
                'sender' => config('services.fortwave.sender'),
                'message' => $message,
            ])
            ->throw()
            ->json();
    }
}

throw() turns an error response into an exception, so a missing credit or an unapproved sender is never silent. A successful call returns the message's id, which delivery webhooks use too, with the credits it used (item_count) and the credits left (remaining_items):

Response
{
  "id": "01JCX4Q8V6M2R7T9K3N5P1W0YZ",
  "item_count": 1,
  "remaining_items": 4999,
  "status": "queued",
  "to": "+25761000000",
  "sender": "MyApp",
  "message": "Message queued for sending"
}

Send an OTP code

Your application generates the code; Fortwave delivers it, in under a second on average in Burundi. Generate it with random_int, which is cryptographically secure, and store only a hash with an expiry.

Send the code
use App\Services\FortwaveSms;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

$code = (string) random_int(100000, 999999);

// Keep only a hash of the code, for 10 minutes.
Cache::put("otp:{$user->id}", Hash::make($code), now()->addMinutes(10));

app(FortwaveSms::class)->send(
    $user->phone_number,
    "Your verification code is {$code}. It expires in 10 minutes.",
);

Check the code

Verify the code
$hash = Cache::get("otp:{$user->id}");

if ($hash === null || ! Hash::check($request->input('code'), $hash)) {
    return back()->withErrors(['code' => 'This code is invalid or has expired.']);
}

Cache::forget("otp:{$user->id}");
// The phone number is verified.

Handle errors

  • 401: the API key is missing, mistyped or revoked.
  • 400: the request was understood but cannot be sent, for example insufficient credits or a sender ID that is not approved. The JSON message explains why.
  • 422: a field is invalid, such as a phone number for the wrong country. errors lists each field.
  • 429: more than 500 sends in a minute from one key. Retry after a short wait, or use the bulk endpoint in the SMS API reference.

Next steps

  • Know when each message is sent or fails with delivery webhooks.
  • Send personalised messages to up to 500 recipients per request with the template endpoint in the SMS API reference.

Still need help?

Our team answers Monday to Friday, during business hours (CAT).