PHP code example of fardadev / kavenegar-for-laravel

1. Go to this page and download the library: Download fardadev/kavenegar-for-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fardadev / kavenegar-for-laravel example snippets


return [
    // Your Kavenegar API key (', ''),
    
    // Default sender line number (optional)
    'sender' => env('KAVENEGAR_SENDER', null),
    
    // HTTP request timeout in seconds
    'timeout' => env('KAVENEGAR_TIMEOUT', 30),
    
    // Skip SMS sending in local/dev environments
    'skip_in_development' => env('KAVENEGAR_SKIP_IN_DEV', true),
    
    // Test phone numbers (SMS skipped in testing environment)
    'test_phone_numbers' => [
        '09112223344',
    ],
    
    // Verification templates (must be created in Kavenegar panel)
    'templates' => [
        'login' => env('KAVENEGAR_TEMPLATE_LOGIN', 'login-verify'),
        'email_password' => env('KAVENEGAR_TEMPLATE_EMAIL_PASS', 'email-pass'),
        'two_factor' => env('KAVENEGAR_TEMPLATE_2FA', 'email-2fa'),
    ],
];

use FardaDev\Kavenegar\Facades\Kavenegar;

// Send to single recipient
$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Hello from Kavenegar!'
);

// Send to multiple recipients
$result = Kavenegar::send(
    receptor: ['09123456789', '09987654321'],
    message: 'Hello everyone!'
);

// Send with all options
$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Scheduled message',
    sender: '10004346',
    date: time() + 3600, // Send in 1 hour
    type: 1, // Save to phone memory
    localid: [123], // For duplicate prevention
    hide: 1, // Hide receptor in logs
    tag: 'marketing',
    policy: 'custom-flow'
);

// Check result
foreach ($result as $response) {
    echo "Message ID: {$response->messageid}\n";
    echo "Status: {$response->statustext}\n";
    echo "Cost: {$response->cost} Rials\n";
    
    if ($response->isDelivered()) {
        echo "Message delivered!\n";
    } elseif ($response->isPending()) {
        echo "Message is pending...\n";
    }
}

use FardaDev\Kavenegar\Client\KavenegarClient;

class NotificationService
{
    public function __construct(private KavenegarClient $kavenegar) {}
    
    public function sendWelcomeSMS(string $phone): void
    {
        $this->kavenegar->send(
            receptor: $phone,
            message: 'Welcome to our service!'
        );
    }
}

$result = Kavenegar::sendArray(
    senders: ['10004346', '10004347', '10004348'],
    receptors: ['09123456789', '09987654321', '09111111111'],
    messages: ['Message 1', 'Message 2', 'Message 3']
);

// Simple verification code
$result = Kavenegar::verifyLookup(
    receptor: '09123456789',
    template: 'login-verify',
    token: '123456'
);

// With multiple tokens
$result = Kavenegar::verifyLookup(
    receptor: '09123456789',
    template: 'email-pass',
    token: '123456',
    token2: '[email protected]'
);

// With all token parameters
$result = Kavenegar::verifyLookup(
    receptor: '09123456789',
    template: 'custom-template',
    token: 'value1',
    token2: 'value2',
    token3: 'value3',
    token10: 'value10',
    token20: 'value20'
);

use FardaDev\Kavenegar\Helpers\KavenegarHelper;

$helper = app(KavenegarHelper::class);

// Send login code
$result = $helper->sendLoginCode('09123456789', '123456');

// Send email + password code
$result = $helper->sendEmailPasswordCode(
    '09123456789',
    '123456',
    '[email protected]'
);

// Send 2FA code
$result = $helper->sendTwoFactorCode(
    '09123456789',
    '654321',
    '[email protected]'
);

// Check by message ID
$status = Kavenegar::status('8792343');

// Check multiple messages
$status = Kavenegar::status(['8792343', '8792344']);

// Check by local ID
$status = Kavenegar::statusLocalMessageId('123');

// Check by receptor and date range
$status = Kavenegar::statusByReceptor(
    receptor: '09123456789',
    startdate: strtotime('-1 day'),
    enddate: time()
);

foreach ($status as $s) {
    echo "Message {$s->messageid}: {$s->statustext}\n";
    
    if ($s->isDelivered()) {
        echo "Delivered successfully!\n";
    }
}

// Get full message details
$messages = Kavenegar::select('8792343');

// Get messages in date range
$messages = Kavenegar::selectOutbox(
    startdate: strtotime('-1 day'),
    enddate: time(),
    sender: '10004346' // Optional filter
);

// Get latest messages
$messages = Kavenegar::latestOutbox(
    pagesize: 100,
    sender: '10004346' // Optional filter
);

// Count messages
$count = Kavenegar::countOutbox(
    startdate: strtotime('-1 day'),
    enddate: time(),
    status: 10 // Optional: only delivered messages
);

// Cancel scheduled message
$result = Kavenegar::cancel('8792343');

// Cancel multiple messages
$result = Kavenegar::cancel(['8792343', '8792344']);

// Send text-to-speech call
$result = Kavenegar::makeTTS(
    receptor: '09123456789',
    message: 'Your verification code is 1 2 3 4 5 6'
);

// Scheduled TTS call
$result = Kavenegar::makeTTS(
    receptor: '09123456789',
    message: 'Reminder message',
    date: time() + 3600 // Call in 1 hour
);

// Get account info
$info = Kavenegar::info();

echo "Credit: {$info->remaincredit} Rials\n";
echo "Expiry: " . $info->getExpiryDate()->format('Y-m-d') . "\n";

if ($info->hasCredit()) {
    echo "Account has credit\n";
}

if ($info->isExpired()) {
    echo "Account is expired!\n";
}

// Get account configuration
$config = Kavenegar::config();

if ($config->hasApiLogsEnabled()) {
    echo "API logs are enabled\n";
}



namespace App\Services;

use FardaDev\Kavenegar\Client\KavenegarClient;
use FardaDev\Kavenegar\Dto\MessageResponse;

class MyCustomSmsService
{
    public function __construct(private readonly KavenegarClient $client) {}

    public function sendOrderConfirmation(string $phone, string $orderNumber): MessageResponse
    {
        return $this->client->verifyLookup(
            receptor: $phone,
            template: 'order-confirmation',
            token: $orderNumber
        );
    }

    public function sendPasswordReset(string $phone, string $code, int $expiryMinutes): MessageResponse
    {
        return $this->client->verifyLookup(
            receptor: $phone,
            template: 'password-reset',
            token: $code,
            token2: (string) $expiryMinutes
        );
    }

    // Add your own custom methods here
}

use App\Services\MyCustomSmsService;

class OrderController
{
    public function __construct(private MyCustomSmsService $sms) {}

    public function confirmOrder($orderId)
    {
        $order = Order::find($orderId);
        $this->sms->sendOrderConfirmation($order->phone, $order->number);
    }
}

use FardaDev\Kavenegar\Exceptions\KavenegarApiException;
use FardaDev\Kavenegar\Exceptions\KavenegarHttpException;
use FardaDev\Kavenegar\Exceptions\KavenegarValidationException;

try {
    $result = Kavenegar::send('09123456789', 'Test message');
} catch (KavenegarValidationException $e) {
    // Input validation error (invalid phone, array mismatch, etc.)
    echo "Validation error: " . $e->getMessage();
    echo "Error code: " . $e->errorCode;
    dump($e->getContext());
} catch (KavenegarApiException $e) {
    // API returned error (401, 411, 418, etc.)
    echo "API error: " . $e->getMessage();
    echo "Error code: " . $e->errorCode;
    
    if ($e->errorCode === 418) {
        echo "Insufficient credit!";
    }
} catch (KavenegarHttpException $e) {
    // Network/connection error
    echo "Connection error: " . $e->getMessage();
}

// In config/kavenegar.php
'skip_in_development' => true,

// SMS will be skipped in local/dev environments
$helper = app(KavenegarHelper::class);
$result = $helper->sendLoginCode('09123456789', '123456');
// Returns true instead of sending actual SMS

// Check if would skip
if ($helper->shouldSkipInDevelopment('09123456789')) {
    echo "SMS would be skipped in this environment";
}

$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Sensitive message',
    hide: 1 // Receptor won't appear in sent message lists
);

// First send
$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Order #123 confirmed',
    localid: [123]
);

// Duplicate attempt - won't send again
$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Order #123 confirmed',
    localid: [123] // Same local ID
);
// Returns existing message details without resending

$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'Special offer!',
    tag: 'marketing-campaign-2024'
);

$result = Kavenegar::send(
    receptor: '09123456789',
    message: 'High priority message',
    policy: 'high-priority-flow'
);

$result = Kavenegar::send('09123456789', 'Test');

// MessageResponse DTO
$response = $result[0];
$response->messageid;   // int
$response->message;     // string
$response->status;      // int
$response->statustext;  // string
$response->sender;      // string
$response->receptor;    // string
$response->date;        // int (UnixTime)
$response->cost;        // int (Rials)

// Helper methods
$response->isDelivered(); // bool
$response->isFailed();    // bool
$response->isPending();   // bool

// AccountInfo DTO
$info = Kavenegar::info();
$info->hasCredit();       // bool
$info->isExpired();       // bool
$info->getCreditAmount(); // int
$info->getExpiryDate();   // DateTime
bash
php artisan vendor:publish --tag=kavenegar-config
bash
composer analyse