Download the PHP package moffhub/sms-handler without Composer
On this page you can find all versions of the php package moffhub/sms-handler. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download moffhub/sms-handler
More information about moffhub/sms-handler
Files in moffhub/sms-handler
Package sms-handler
Short Description Unified SMS gateway for Laravel with multi-provider support (Advanta, Africa's Talking, Twilio, Nexmo, Onfon). Queue-ready, delivery tracking, fallback chains, templating, and analytics.
License MIT
Homepage https://github.com/moffhub/sms-handler
Informations about the package sms-handler
SMS Handler
A simple, unified SMS integration library for Laravel. Send SMS messages through multiple providers with a consistent API, automatic fallback, rate limiting, templating, cost estimation, and analytics.
Features
- [x] Send SMS, Bulk SMS, and Scheduled SMS
- [x] Multiple provider support (Advanta, Africa's Talking, Twilio, Nexmo, Onfon Media)
- [x] Custom provider extensibility
- [x] Automatic fallback provider chain
- [x] Per-provider rate limiting
- [x] SMS templating with variable interpolation
- [x] Cost estimation and segment counting
- [x] Analytics and success rate tracking
- [x] Webhook delivery report handling with signature validation
- [x] Events (SmsSent, SmsFailed, DeliveryReportReceived)
- [x] Structured logging with credential scrubbing
- [x] Laravel Notification channel support
- [x] Phone number and message validation
- [x] Database or file logging
Supported Providers
- Advanta - Kenya SMS gateway
- Africa's Talking - Pan-African SMS gateway
- Twilio - Global SMS provider
- Nexmo/Vonage - Global SMS provider
- Onfon Media - Kenya SMS gateway
- Custom - Build your own provider
Installation
Configuration
Publish the config and migrations:
Environment Variables
Add the following to your .env file based on your provider:
Usage
Using the Facade
Using Dependency Injection
Switching Providers at Runtime
Fallback Provider Chain
Configure a fallback provider that is used automatically when the primary provider fails with a ProviderException. Fallback is limited to one level (no chaining beyond the fallback).
Or in config/sms.php:
When the primary provider fails, the package will:
- Log the failure
- Automatically retry with the fallback provider
- Log the fallback activation
- Return the fallback result (or null if the fallback also fails)
Non-ProviderException errors (e.g., validation errors) are not retried and are rethrown.
Rate Limiting
Configure per-provider rate limits (messages per minute). When the limit is exceeded, messages are automatically queued for later delivery instead of being rejected.
Or in config/sms.php:
Programmatic access:
Rate Limiting Recommendations
- Set rate limits based on your provider's API quotas to avoid being blocked.
- Start with conservative limits and increase as needed.
- Monitor your queue to ensure rate-limited messages are being delivered.
- Use
null(unlimited) only for providers with no known API rate limits.
SMS Templating
Define reusable SMS templates with {{ variable }} interpolation:
Send a templated SMS:
Message length is validated after interpolation. If the rendered message exceeds the configured max_message_length, an InvalidMessageException is thrown.
Cost Estimation
Estimate the cost of sending an SMS before dispatching. The estimator calculates SMS segment count based on message encoding (GSM-7 vs UCS-2) and multiplies by the configured per-segment cost.
Segment Counting Rules
| Encoding | Single SMS | Multi-part (per segment) |
|---|---|---|
| GSM-7 | 160 chars | 153 chars |
| UCS-2 | 70 chars | 67 chars |
Unicode characters (emoji, CJK, Arabic, etc.) force UCS-2 encoding, which reduces the per-segment capacity.
Configure per-segment cost in your provider config:
When logging to the database (SMS_LOG_CHANNEL=model), the estimated_cost and segment_count columns are automatically populated on each SmsLog record.
Analytics & Success Rate Tracking
Query SMS analytics aggregated from the sms_logs table:
CLI Stats Command
View SMS statistics from the command line:
Error Handling
Exception Types
The package defines a hierarchy of exceptions:
| Exception | Description |
|---|---|
SmsException |
Base exception class for all SMS errors |
ProviderException |
Provider-level failures (API errors, timeouts). Triggers fallback if configured. |
InvalidPhoneNumberException |
Invalid, empty, or malformed phone numbers |
InvalidMessageException |
Empty or too-long messages |
Handling Exceptions
Events
Listen for SMS lifecycle events:
Webhook Setup
Enable webhooks to receive delivery reports from providers:
This registers POST routes for each provider:
| Provider | Endpoint | Route Name |
|---|---|---|
| Advanta | POST /sms/webhooks/advanta |
sms.webhooks.advanta |
| Africa's Talking | POST /sms/webhooks/africastalking |
sms.webhooks.africastalking |
| Onfon | POST /sms/webhooks/onfon |
sms.webhooks.onfon |
| Nexmo | POST /sms/webhooks/nexmo |
sms.webhooks.nexmo |
| Twilio | POST /sms/webhooks/twilio |
sms.webhooks.twilio |
Webhook Signature Validation
Set webhook secrets to validate incoming requests:
If a secret is configured, the package validates the signature header on incoming webhook requests. Invalid signatures receive a 403 response.
Provider Webhook Setup
Twilio:
- Go to your Twilio Console > Phone Numbers > Active Numbers
- Click your number and set the "A MESSAGE COMES IN" webhook URL to your endpoint
- Set the Status Callback URL to
https://yourdomain.com/sms/webhooks/twilio
Africa's Talking:
- Go to your AT Dashboard > SMS > SMS Callback URLs
- Set the Delivery Reports URL to
https://yourdomain.com/sms/webhooks/africastalking
Advanta:
- Configure the callback URL in your Advanta dashboard or pass it in the API request
- Set it to
https://yourdomain.com/sms/webhooks/advanta
Nexmo/Vonage:
- Go to Vonage Dashboard > Settings
- Set the SMS Delivery Receipt URL to
https://yourdomain.com/sms/webhooks/nexmo
Onfon:
- Contact Onfon support to configure your callback URL
- Set it to
https://yourdomain.com/sms/webhooks/onfon
Delivery Report Payload Examples
Twilio:
Africa's Talking:
Advanta:
Nexmo/Vonage:
Onfon:
Africa's Talking Integration
The library fully supports the Africa's Talking Bulk SMS API:
Sandbox Testing
Production
Features
- Automatic sandbox/production URL detection
- Phone number formatting (supports 0712..., 254712..., +254712...)
- Bulk SMS with enqueue support
- Sender ID/Short code support
- Detailed response handling with message IDs and costs
Custom Providers
Create your own provider by extending CustomProvider:
Register your provider:
Add config:
Update .env:
Laravel Notifications
Use SMS in Laravel notifications:
Ensure your notifiable model has a routeNotificationForSms method:
Logging
SMS messages can be logged to file or database:
When using database logging, each SmsLog record includes:
provider- The provider class usedto- Recipient phone numbermessage- Message contentsuccess- Boolean success statusmessage_id- Provider message IDdelivery_status- Updated via webhooksestimated_cost- Calculated cost based on segments and provider ratesegment_count- Number of SMS segmentsscheduled_at- For scheduled messagesresponse- Raw provider response
Structured Logging
The package logs structured events to a configurable log channel:
Log events include:
sms.sent- Successful send with provider, recipient, message_idsms.failed- Failed send with provider, recipient, error detailssms.bulk_failed- Bulk send failuresms.delivery_report- Incoming delivery report
All log entries are scrubbed of sensitive data (API keys, tokens, secrets).
Testing & Mocking
Faking HTTP Requests
Use Laravel's HTTP faking to test SMS sending without making real API calls:
Faking Events
Test that events are dispatched correctly:
Testing Templates
Testing Cost Estimation
Troubleshooting
Common Issues
SMS not sending:
- Check your provider credentials in
.env - Verify
SMS_PROVIDERis set to a valid provider name - Check
SMS_LOG_CHANNEL=logand review Laravel logs for errors - Ensure your queue worker is running if using queued sending
Validation errors:
- Phone numbers must have at least 9 digits and no more than 15 (E.164)
- Messages cannot be empty or exceed
SMS_MAX_MESSAGE_LENGTH(default: 918 characters) - Phone numbers are auto-formatted; supported formats:
0712345678,254712345678,+254712345678
Rate limiting:
- If messages are being queued unexpectedly, check
rate_limitconfig per provider - Use
Sms::rateLimiter()->remainingAttempts('provider')to check remaining quota - Clear the limiter with
Sms::rateLimiter()->clear('provider')
Webhooks not receiving reports:
- Ensure
SMS_WEBHOOKS_ENABLED=true - Verify your webhook URL is publicly accessible (use ngrok for local dev)
- Check webhook secrets match what the provider expects
- Review logs for 403 responses (signature validation failures)
Fallback not activating:
- Fallback only triggers on
ProviderException, not on validation errors - Verify the fallback provider name matches a configured driver
- Fallback is limited to 1 level -- the fallback provider's own fallback is not used
- Check logs for "SMS fallback activated" messages
Cost estimation showing 0:
- Ensure
per_segment_costis configured for the provider inconfig/sms.php - Cost is 0.0 by default if not configured
Debug Logging
Enable debug-level structured logging:
Testing
License
MIT License. See LICENSE for details.