kwidoo / sms-verification
A flexible SMS verification package supporting multiple providers
Requires
- php: ^8.2
- guzzlehttp/guzzle: ^7.0
- plivo/plivo-php: ^4.66.5
- seven.io/api: 6.0.0
- telesign/telesign: ^5.2
- telesign/telesignenterprise: ^5.3
- telnyx/telnyx-php: ^3.0
- twilio/sdk: ^8.3
- vonage/client: ^4.1
Requires (Dev)
- mockery/mockery: ^1.6
- orchestra/testbench: ^10.0
- phpunit/phpunit: ^11.0.1
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Laravel SMS Verification
A Laravel package for sending and validating SMS-based verification codes through multiple providers (e.g., Twilio, Vonage, or any custom provider**).
Overview
- Round Robin Support: Optionally cycle through multiple providers.
- Pluggable Architecture: Implement your own custom verifier(s).
- Abstracted Interface: A single interface for
create()(sending code) andvalidate()(checking code).
Table of Contents
Installation
-
Require via Composer:
composer require kwidoo/sms-verification
-
Publish Config (Optional):
This will publish
sms-verification.phpinto your Laravelconfigdirectory.php artisan vendor:publish --provider="Kwidoo\SmsVerification\SmsVerificationProvider" --tag="sms-verification-config"
-
Configure Environment Variables:
In your
.envfile, make sure to set the appropriate credentials for your desired providers. For example:# Twilio TWILIO_SID=xxxxxxxxxx TWILIO_AUTH_TOKEN=xxxxxxxxxx TWILIO_VERIFY_SID=xxxxxxxxxx # Vonage VONAGE_API_KEY=xxxxxxxxxx VONAGE_API_SECRET=xxxxxxxxxx VONAGE_BRAND="My Awesome App"
Configuration
The default configuration file sms-verification.php looks like this:
return [ 'verifiers' => [ 'twilio' => \Kwidoo\SmsVerification\Verifiers\TwilioVerifier::class, 'vonage' => \Kwidoo\SmsVerification\Verifiers\VonageVerifier::class, ], 'default' => 'twilio', 'round_robin' => [ 'verifiers' => ['twilio', 'vonage'], 'current_verifier_cache_key' => 'round_robin_verifiers_', 'verifier_for_number_cache_key' => 'round_robin_verifier_for_', ], 'vonage' => [ 'api_key' => env('VONAGE_API_KEY'), 'api_secret' => env('VONAGE_API_SECRET'), 'brand' => env('VONAGE_BRAND', 'MyApp'), ], 'twilio' => [ 'sid' => env('TWILIO_SID'), 'auth_token' => env('TWILIO_AUTH_TOKEN'), 'verify_sid' => env('TWILIO_VERIFY_SID'), ], ];
default: Indicates the default SMS provider if one is not explicitly specified.round_robin: An array of provider keys to use in a rotating fashion whenRoundRobinVerifieris requested.round_robin_cache_key: Cache key used to persist the index in the round-robin cycle.twilio,vonage: Provider-specific credentials and settings.
Usage
Basic Usage
If you only want to use one provider (e.g., Twilio) for all verifications:
-
Set
'default' => 'twilio'insms-verification.php. -
In your code, you can do something like:
use Kwidoo\SmsVerification\VerifierFactory; class SomeController extends Controller { public function sendCode(Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); $verifier = $factory->make(); // uses default (twilio) $verifier->create($phoneNumber); return response()->json(['status' => 'Verification code sent.']); } public function checkCode(Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); $code = $request->input('code'); $verifier = $factory->make(); // uses default (twilio) if ($verifier->validate([$phoneNumber, $code])) { return response()->json(['status' => 'Code is valid!']); } // If invalid, handle appropriately return response()->json(['error' => 'Invalid code'], 422); } }
Round Robin Usage
If you want to rotate between providers (e.g., Twilio → Vonage → Twilio → Vonage…), you can request the round-robin verifier:
-
round_robinis an array of strings referencing your verifiers:['twilio', 'vonage']. -
In your code, you might do:
use Kwidoo\SmsVerification\VerifierFactory; class SomeController extends Controller { public function sendCode(Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); $verifier = $factory->make('roundRobin'); $verifier->create($phoneNumber); return response()->json(['status' => 'Verification code sent.']); } public function checkCode(Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); $code = $request->input('code'); $verifier = $factory->make('roundRobin'); if ($verifier->validate([$phoneNumber, $code])) { return response()->json(['status' => 'Code is valid!']); } // If invalid, handle appropriately return response()->json(['error' => 'Invalid code'], 422); } }
The round-robin verifier will:
- On
create(), pick the next provider in a cycle, send the verification code, and remember which provider was used for that phone number. - On
validate(), retrieve that same provider to check the code.
Custom Verifiers
You can create your own SMS verifier by:
- Creating a class that implements
VerifierInterface(or extend the baseVerifierclass). - Register it in the container or simply reference its FQN in
sms-verification.verifiers.
Example:
namespace App\Verifiers; use Kwidoo\SmsVerification\Verifiers\Verifier; class MyCustomVerifier extends Verifier { public function create(string $phoneNumber): void { // Implementation to send code } public function validate(array $credentials): bool { // Implementation to check code return true; } }
Then, in sms-verification.php:
'verifiers' => [ 'twilio' => \Kwidoo\SmsVerification\Verifiers\TwilioVerifier::class, 'vonage' => \Kwidoo\SmsVerification\Verifiers\VonageVerifier::class, 'my_custom' => \App\Verifiers\MyCustomVerifier::class, ],
And in code:
$verifier = $factory->make('my_custom');
Stateless challenges
Verifiers that implement ChallengeVerifierInterface keep nothing between sending and checking a code.
dispatch() returns a Challenge (recipient, provider reference, opaque state, expiry) that the caller persists
wherever it likes and hands back to verify():
use Kwidoo\SmsVerification\Challenge\Challenge; $verifier = $factory->make('telesign'); $challenge = $verifier->dispatch('+37120000000'); $store->put($id, $challenge->toArray()); // your storage, not the package's $valid = $verifier->verify(Challenge::fromArray($store->get($id)), $request->input('code'));
A wrong or expired code returns false; a provider failure throws VerifierException.
For providers that generate the code themselves the state is empty; for Telesign (Messaging API) the package
generates the code and the state holds only an HMAC of it, keyed with SMS_VERIFICATION_CODE_KEY (or APP_KEY),
so whoever stores the challenge cannot read or brute force the code.
Telesign
TELESIGN_CUSTOMER_ID=... TELESIGN_API_KEY=... # Production by default; the SDK itself defaults to the sandbox. TELESIGN_REST_ENDPOINT=https://rest-api.telesign.com TELESIGN_MESSAGE="Your verification code is :code" TELESIGN_CODE_LENGTH=6 TELESIGN_CODE_TTL=300 SMS_VERIFICATION_CODE_KEY=
Full-service (enterprise) Telesign accounts can let Telesign own the code instead. Same credentials:
| Factory name | API | Code generated / checked by |
|---|---|---|
telesign |
Messaging API POST /v1/messaging |
this package (HMAC-sealed challenge) |
telesignVerify |
Verify API verify.telesign.com/verification |
Telesign |
telesignSmsVerify |
SMS Verify API /v1/verify/sms |
Telesign |
TELESIGN_VERIFY_ENDPOINT=https://verify.telesign.com TELESIGN_VERIFY_METHODS=sms # ordered policy, e.g. "whatsapp,sms" TELESIGN_VERIFY_MESSAGE_TEMPLATE= # template name configured with Telesign TELESIGN_SMS_VERIFY_ENDPOINT=https://rest-ww.telesign.com TELESIGN_SMS_VERIFY_TEMPLATE="Your code is :code" # or $$CODE$$ TELESIGN_SMS_VERIFY_LANGUAGE=
Challenge drivers (per-call configuration)
VerifierFactory builds verifiers from the application's config. A host that serves several tenants, each with its
own credentials, uses the driver registry instead: it builds a stateless verifier from a plain array per call.
use Kwidoo\SmsVerification\Challenge\ChallengeDrivers; use Kwidoo\SmsVerification\Challenge\ChallengeRuntime; $drivers = ChallengeDrivers::defaults(); // telesign, telesign_verify, telesign_sms_verify $verifier = $drivers->make('telesign_verify', [ 'customer_id' => '...', 'api_key' => '...', 'methods' => 'whatsapp,sms', ], new ChallengeRuntime( httpHandler: $myGuzzleHandler, // optional: send provider HTTP through the host's transport codeKey: $secret, // required by drivers that generate the code (telesign) timeout: 10, )); $challenge = $verifier->dispatch('+37120000000'); $verifier->verify($challenge, '1234567');
Each driver describes itself, so a host can publish a configuration form and log redaction without provider knowledge:
$drivers->options() (merged across drivers), $drivers->sensitiveKeys(), $drivers->redaction(). Add your own with
$drivers->with(new MyDriver()) (implement Kwidoo\SmsVerification\Contracts\ChallengeDriver). Unknown drivers and missing
options throw ConfigurationException.
| Driver | Provider API | Code owned by | Options (* required) |
|---|---|---|---|
telesign |
Telesign Messaging | package (sealed) | customer_id, api_key, url, message (:code), code_length, ttl |
telesign_verify |
Telesign Verify API | Telesign | customer_id, api_key, url, methods, message_template, ttl |
telesign_sms_verify |
Telesign SMS Verify | Telesign | customer_id, api_key, url, message (:code/$$CODE$$), language, ttl |
twilio |
Twilio Verify v2 | Twilio | account_sid, auth_token, verify_sid*, channel (sms), locale, ttl |
vonage |
Vonage Verify v2 | Vonage | api_key, api_secret, brand*, locale, ttl |
telnyx |
Telnyx Verify v2 | Telnyx | api_key, verify_profile_id, url, ttl |
plivo |
Plivo Verify sessions | Plivo | auth_id, auth_token, app_uuid, channel (sms), locale, brand_name, code_length, ttl |
sinch |
Sinch Verification | Sinch | application_key, application_secret, url, ttl |
seven |
seven.io SMS | package (sealed) | api_key*, from, url, message (:code), code_length, ttl |
"Code owned by provider": the challenge carries only the provider's reference and verify() asks the provider.
"Package (sealed)": the provider only delivers text, so the verifier generates the code and the challenge carries an HMAC
of it (needs ChallengeRuntime::$codeKey). Every driver sends its HTTP through ChallengeRuntime::$httpHandler
(Twilio via Twilio\Http\GuzzleClient, Vonage via PSR-18, Plivo via PlivoGuzzleHttpClient, Sinch via
PendingRequest::setHandler(), seven.io and Telnyx via package clients). A wrong, expired or used-up code is
false; outages, rate limits and auth failures throw VerifierException.
---|---|
| telesign | customer_id, api_key (sensitive), url (https://rest-api.telesign.com), message (:code), code_length (6), ttl (300) |
| telesign_verify | customer_id, api_key, url (https://verify.telesign.com), methods (sms), message_template, ttl |
| telesign_sms_verify | customer_id, api_key, url (https://rest-ww.telesign.com), message (:code / $$CODE$$), language, ttl |
Console Command
This package includes a console command to generate new custom verifiers from a stub:
php artisan verifier:create-sms-verifier {name?}
If you omit {name}, the command will prompt you to enter the verifier’s class name. It also asks for the client class (namespace) that the verifier should inject.
The newly generated file will be placed in app/Verifiers/{Name}.php. You can customize paths or logic within the command class CreateSmsVerifier.
Example Code
Here’s a quick example to tie it all together:
// routes/api.php use Illuminate\Support\Facades\Route; use Kwidoo\SmsVerification\VerifierFactory; Route::post('/send-code', function(\Illuminate\Http\Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); // If you want round robin, pass 'roundRobin' or whichever config key you want: // $verifier = $factory->make('roundRobin'); $verifier = $factory->make(); // default is 'twilio' $verifier->create($phoneNumber); return response()->json(['message' => 'Code sent']); }); Route::post('/verify-code', function(\Illuminate\Http\Request $request, VerifierFactory $factory) { $phoneNumber = $request->input('phone_number'); $code = $request->input('code'); $verifier = $factory->make(); // or 'roundRobin' $isValid = $verifier->validate([$phoneNumber, $code]); return response()->json(['valid' => $isValid]); });
Credits
- Twilio for their robust Verify service.
- Vonage (formerly Nexmo) for their Verify APIs.
- Sinch for their SMS verification service.
- Telnyx for their Verify API.
- Plivo for their SMS verification service.
- seven.io for their SMS verification service.
- Telesign for their SMS verification service.
- Laravel community for a great framework to extend.
License
This package is open-sourced software licensed under the MIT license.
TODO
- Make more round-robin strategies (e.g., Weighted Round Robin, Random, etc.).
- Implement a “fallback” approach (try one provider; if it fails, try another).
- Add tests.
- Add webhook support to better handle fails
- Add support for other SMS providers:
- Plivo
- Sinch
- seven.io
- Telesign
- ClickSend
- Textmagic
- SlickText
- Infobip
- Routee
- Telnyx