PHP code example of am-naguib / am-sender

1. Go to this page and download the library: Download am-naguib/am-sender 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/ */

    

am-naguib / am-sender example snippets


use AMSender\Facades\AMSender;

// List all devices
try {
    $devices = AMSender::listDevices();
    echo "Devices: " . json_encode($devices);
} catch (\AMSender\Exceptions\AMSenderException $e) {
    echo "Error: " . $e->getMessage();
}

// Create a new device
try {
    $device = AMSender::createDevice('My Device');
    echo "Device created: " . json_encode($device);
} catch (\AMSender\Exceptions\AMSenderException $e) {
    echo "Error: " . $e->getMessage();
}

// Send a message
try {
    $result = AMSender::send([
        'message' => 'Hello from Laravel!',
        'receivers' => ['+1234567890', '+0987654321'],
        'device_ids' => ['device-id-1', 'device-id-2'],
        'delay_time' => 5,
        'image' => 'https://example.com/image.jpg' // optional
    ]);
    echo "Message sent: " . json_encode($result);
} catch (\AMSender\Exceptions\AMSenderException $e) {
    echo "Error: " . $e->getMessage();
}

use AMSender\AMSender;

class MessageController extends Controller
{
    public function sendMessage(AMSender $amSender)
    {
        try {
            $result = $amSender->send([
                'message' => 'Hello World!',
                'receivers' => ['+1234567890'],
                'device_ids' => ['your-device-id']
            ]);
            
            return response()->json($result);
        } catch (\AMSender\Exceptions\AMSenderException $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }
}

$devices = AMSender::listDevices();

$device = AMSender::createDevice('My New Device');

$result = AMSender::send([
    'message' => 'Your message here',
    'receivers' => ['+1234567890', '+0987654321'],
    'device_ids' => ['device-id-1'],
    'delay_time' => 5, // optional delay in seconds
    'image' => 'https://example.com/image.jpg' // optional image URL
]);

use AMSender\Facades\AMSender;
use AMSender\Exceptions\ValidationException;

try {
    // This will throw ValidationException - device name too short
    AMSender::createDevice('Hi');
} catch (ValidationException $e) {
    echo $e->getMessage(); // "Device name must be at least 3 characters long."
}

try {
    // This will throw ValidationException - phone number too short
    AMSender::send([
        'message' => 'Hello!',
        'receivers' => ['123'], // Too short
        'device_ids' => ['device-1']
    ]);
} catch (ValidationException $e) {
    echo $e->getMessage(); // "Phone number at index 0 is too short. Minimum 5 characters ly!";
} catch (ValidationException $e) {
    echo "Validation error: " . $e->getMessage();
}

use AMSender\Facades\AMSender;
use AMSender\Exceptions\InvalidImageException;
use AMSender\Helpers\ImageHelper;

try {
    $result = AMSender::send([
        'message' => 'Check this image!',
        'receivers' => ['+1234567890'],
        'device_ids' => ['device-1'],
        'image' => 'https://example.com/image.jpg'
    ]);
} catch (InvalidImageException $e) {
    echo "Image error: " . $e->getMessage();
    
    // Get suggestions for fixing the URL
    $suggestions = ImageHelper::getImageUrlSuggestions('https://example.com/image.jpg');
    foreach ($suggestions as $suggestion) {
        echo "- " . $suggestion . "\n";
    }
}

// Test an image URL before sending
$imageUrl = 'https://example.com/image.jpg';
$testResult = ImageHelper::testImageUrl($imageUrl);

if (!$testResult['is_accessible']) {
    echo "Image URL is not accessible\n";
    foreach ($testResult['errors'] as $error) {
        echo "Error: " . $error . "\n";
    }
}

if ($testResult['warnings']) {
    foreach ($testResult['warnings'] as $warning) {
        echo "Warning: " . $warning . "\n";
    }
}

// Common error scenarios:

// 1. URL not accessible
"Image URL is not accessible. Please check: 1) URL is publicly accessible, 2) URL points to a valid image file, 3) Image server allows external access."

// 2. Invalid file type
"The provided URL does not point to a valid image file. Please ensure the URL ends with a valid image extension (jpg, jpeg, png, gif, webp, bmp)."

// 3. URL format issues
"Image must be a valid URL format."
"Image URL must use HTTP or HTTPS protocol."

use AMSender\Exceptions\SubscriptionExpiredException;
use AMSender\Exceptions\DeviceNotFoundException;

try {
    $result = AMSender::send($payload);
} catch (SubscriptionExpiredException $e) {
    // Handle subscription expiry
    echo "Your subscription has expired: " . $e->getMessage();
} catch (DeviceNotFoundException $e) {
    // Handle device issues
    echo "Device error: " . $e->getMessage();
} catch (\AMSender\Exceptions\AMSenderException $e) {
    // Handle other AM-Sender errors
    echo "AM-Sender error: " . $e->getMessage();
}

return [
    // API base URL
    'base_url' => env('AM_SENDER_BASE_URL', 'https://am-sender.com/api'),
    
    // Your authentication key
    'auth_key' => env('AM_SENDER_AUTH_KEY'),
    
    // Request timeout in seconds
    'timeout' => env('AM_SENDER_TIMEOUT', 30),
    
    // Retry configuration
    'retry' => [
        'times' => env('AM_SENDER_RETRY_TIMES', 3),
        'sleep' => env('AM_SENDER_RETRY_SLEEP', 1000),
    ],
];

use AMSender\Facades\AMSender;
use AMSender\Exceptions\ValidationException;
use AMSender\Exceptions\AMSenderException;

try {
    $result = AMSender::send($payload);
    // Handle success
} catch (ValidationException $e) {
    // Handle validation errors (400-level errors)
    Log::warning('Validation error: ' . $e->getMessage());
} catch (AMSenderException $e) {
    // Handle API errors (500-level errors)
    Log::error('API error: ' . $e->getMessage());
}

// ✅ All these formats are accepted
$receivers = [
    '+1234567890',      // International format
    '01234567890',      // Local format
    '123-456-7890',     // With hyphens
    '(123) 456-7890',   // With parentheses
    '123 456 7890',     // With spaces
    '',                 // Empty - will be filtered out automatically
    '   ',              // Whitespace only - will be filtered out
];

// Result: Empty numbers are automatically removed
// Final receivers: ['+1234567890', '01234567890', '123-456-7890', '(123) 456-7890', '123 456 7890']

$allReceivers = ['+1111111111', '+2222222222', /* ... many more */];
$chunks = array_chunk($allReceivers, 100); // Process 100 at a time

foreach ($chunks as $chunk) {
    try {
        AMSender::send([
            'message' => 'Bulk message',
            'receivers' => $chunk,
            'device_ids' => ['device-1'],
            'delay_time' => 2 // Add delay between batches
        ]);
        sleep(5); // Wait between batches to avoid rate limits
    } catch (Exception $e) {
        Log::error("Batch failed: " . $e->getMessage());
    }
}
bash
php artisan vendor:publish --provider="AMSender\AMSenderServiceProvider"