Install the Package
composer require kavenegar/php
Ensure your composer.json includes "kavenegar/php": "^1.2.1" (or latest stable version).
Retrieve API Key Sign up at Kavenegar Panel and grab your API key from Settings.
First Use Case: Send SMS
use Kavenegar\KavenegarApi;
$api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
$sender = "10004346"; // Your sender ID (e.g., "1000XXXX")
$receptors = ["09123456789", "09367891011"];
$message = "Your SMS content here";
try {
$result = $api->Send($sender, $receptors, $message);
// Handle response (see below)
} catch (\Kavenegar\Exceptions\ApiException $e) {
log::error($e->errorMessage());
}
Environment Configuration
Add to .env:
KAVENEGAR_API_KEY=your_api_key_here
Sending SMS
$result = $api->Send($sender, ["09123456789"], $message);
$result = $api->Send($sender, ["09123456789", "09367891011"], $message);
queue to defer SMS sending:
dispatch(new SendSmsJob($sender, $receptors, $message));
Verifying API Responses
Check status and statustext in the response:
if ($result && $result[0]->status === 1) {
// Success (e.g., "در صف ارسال")
}
Error Handling
catch (\Kavenegar\Exceptions\ApiException $e) {
$this->handleApiError($e->errorMessage());
}
catch (\Kavenegar\Exceptions\HttpException $e) {
$this->handleHttpError($e->errorMessage());
}
Logging Responses Log raw responses for debugging:
\Log::debug('Kavenegar Response:', ['data' => $result]);
Laravel Service Provider Bind the API client to the container for dependency injection:
// app/Providers/AppServiceProvider.php
public function register() {
$this->app->singleton(KavenegarApi::class, function ($app) {
return new KavenegarApi(env('KAVENEGAR_API_KEY'));
});
}
Usage in controllers:
use KavenegarApi;
public function sendSms(KavenegarApi $api) {
$api->Send($sender, $receptors, $message);
}
Queue Jobs Create a job for async SMS sending:
// app/Jobs/SendSmsJob.php
public function handle() {
$api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
$api->Send($this->sender, $this->receptors, $this->message);
}
Validation Validate phone numbers before sending:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(['phone' => $receptor], [
'phone' => 'required|string|regex:/^09[0-9]{9}$/'
]);
Rate Limiting
Implement a throttle middleware to avoid hitting API limits:
// app/Http/Middleware/ThrottleKavenegar.php
public function handle($request, Closure $next) {
return parent::handle($request, $next)
->throttle(['kavenegar' => 1, 'minute']);
}
API Key Exposure
.env..env in version control (add to .gitignore).Phone Number Format
+ or 0098 prefixes).$cleanedPhone = preg_replace('/[^0-9]/', '', $phone);
Response Parsing
Send() method returns an array of objects. Always check entries for per-recipient statuses:
if (empty($result[0]->entries)) {
throw new \RuntimeException("No entries in response");
}
Deprecated Methods
Cost Tracking
cost in responses to track SMS expenses:
$totalCost = array_sum(array_map(fn($r) => $r->cost, $result));
Enable Guzzle Logging Configure Guzzle to log HTTP requests:
$api = new KavenegarApi(env('KAVENEGAR_API_KEY'));
$api->getClient()->getEmitter()->addSubscriber(new \GuzzleHttp\HandlerStack());
Mock API Calls
Use Laravel’s Mockery to test without hitting the real API:
$mock = Mockery::mock(KavenegarApi::class);
$mock->shouldReceive('Send')->andReturn([(object)['status' => 1]]);
Check API Status Verify Kavenegar’s service status at status.kavenegar.com.
Custom Response Handling
Extend the KavenegarApi class to add methods for specific use cases:
class ExtendedKavenegarApi extends KavenegarApi {
public function sendVerificationCode($phone, $code) {
$message = "Your verification code: {$code}";
return $this->Send("10004346", [$phone], $message);
}
}
Webhook Integration Use Kavenegar’s webhook feature to receive delivery reports:
// routes/web.php
Route::post('/kavenegar-webhook', [SmsWebhookController::class]);
Fallback Mechanisms Implement retries for failed sends:
use Illuminate\Support\Facades\Retry;
Retry::retry(3, function () use ($api, $sender, $receptors, $message) {
$result = $api->Send($sender, $receptors, $message);
if ($result[0]->status !== 1) {
throw new \RuntimeException("SMS failed");
}
});
Local Testing Use a local SMS gateway (e.g., Twilio Sandbox) during development.
How can I help you explore Laravel packages today?