Installation:
composer require mahdimajidzadeh/kavenegar
For Laravel <5.5, add the service provider to config/app.php:
MahdiMajidzadeh\Kavenegar\KavenegarServiceProvider::class
Publish Config:
php artisan vendor:publish --provider="MahdiMajidzadeh\Kavenegar\KavenegarServiceProvider"
This generates .env keys and a config file at config/kavenegar.php.
Configure .env:
KAVENEGAR_API_KEY=your_api_key_here
First Use Case: Send a basic SMS in a controller or service:
use MahdiMajidzadeh\Kavenegar\KavenegarSMS;
$sms = new KavenegarSMS();
$result = $sms->send('09123456789', 'Hello from Laravel!');
Sending SMS:
$sms->send('09123456789', 'Your verification code is 1234.');
$sms->sendArray(['09123456789', '09198765432'], 'Hello all!');
Verification & Tracking:
$sms->status('local_message_id');
$sms->select(); // All outbox messages
$sms->latestOutbox(10); // Last 10 messages
Inbox Management:
$sms->receive(); // All inbox messages
$sms->receive(10); // Last 10 messages
Integration with Laravel:
Service Container: Bind the SMS client in a service provider for dependency injection:
$this->app->singleton(KavenegarSMS::class, function ($app) {
return new KavenegarSMS(config('kavenegar.api_key'));
});
Then inject KavenegarSMS into controllers/services.
Queued Jobs: Dispatch SMS sending as a job for async processing:
use MahdiMajidzadeh\Kavenegar\Jobs\SendSMS;
SendSMS::dispatch('09123456789', 'Your code is 1234.')->onQueue('sms');
Event-Driven Notifications:
Extend Laravel’s Notifiable trait to send SMS notifications:
use MahdiMajidzadeh\Kavenegar\HasSmsNotifications;
class User extends Authenticatable implements Notifiable
{
use HasSmsNotifications;
}
Then define a sendSmsVerification method in the model.
Template-Based SMS: Use Kavenegar’s templates for dynamic content:
$sms->send('09123456789', 'template_name', ['code' => '1234']);
Rate Limiting: Implement middleware to throttle SMS requests:
use Illuminate\Cache\RateLimiting\Limit;
RateLimiter::for('sms', function (Request $request) {
return Limit::perMinute(5)->by($request->user()->id);
});
Logging & Retries: Log failed SMS attempts and retry using Laravel’s queue:
try {
$sms->send($phone, $message);
} catch (\Exception $e) {
Log::error("SMS failed: " . $e->getMessage());
// Retry logic or notify admin
}
API Key Misconfiguration:
KAVENEGAR_API_KEY is set in .env and matches the config file.status property after sending:
if ($sms->status !== 200) {
throw new \Exception($sms->message);
}
Phone Number Formatting:
+ or 0098).$phone = preg_replace('/[^0-9]/', '', $phone);
Rate Limits:
429 responses gracefully:
if ($sms->status === 429) {
sleep(1); // Retry after delay
$sms->send($phone, $message);
}
Timeouts:
max_execution_time or use async jobs.Local Testing:
$this->app->instance(KavenegarSMS::class, Mockery::mock(KavenegarSMS::class));
Enable Debug Mode:
Set debug to true in config/kavenegar.php to log raw API responses.
Check HTTP Status:
200: Success.400: Invalid parameters (e.g., malformed phone).401: Invalid API key.403: Insufficient balance or blocked number.Inspect Raw Response:
$response = $sms->send($phone, $message);
dd($response->getRawResponse()); // Debug full API response
Custom Responses:
Extend the KavenegarSMS class to handle business logic:
class CustomKavenegarSMS extends KavenegarSMS {
public function sendVerification($phone, $code) {
$result = $this->send($phone, "Your code is {$code}.");
if ($result->status !== 200) {
event(new SmsFailed($phone, $result->message));
}
return $result;
}
}
Webhook Integration: Use Kavenegar’s webhooks to handle delivery reports:
Route::post('/kavenegar-webhook', function (Request $request) {
$payload = $request->json()->all();
// Process delivery status (e.g., update DB)
});
Fallback Mechanisms: Implement a fallback to another SMS provider if Kavenegar fails:
try {
$sms->send($phone, $message);
} catch (\Exception $e) {
$fallbackSms->send($phone, $message); // e.g., Twilio
}
Environment Overrides:
Override config values in .env:
KAVENEGAR_DEBUG=true
KAVENEGAR_TIMEOUT=30
Proxy Support: If behind a proxy, configure Guzzle’s client in the service provider:
$client = new \GuzzleHttp\Client([
'timeout' => 30,
'proxy' => 'http://your-proxy:port',
]);
SSL Verification: Disable SSL verification only for testing (not production):
$sms = new KavenegarSMS(config('kavenegar.api_key'), false); // Disables SSL
How can I help you explore Laravel packages today?