andrejro2/yeastar-gsm-laravel

Laravel package for sending SMS via Yeastar Gateway using API

Installs: 3

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/andrejro2/yeastar-gsm-laravel

1.0.1 2025-09-01 11:04 UTC

This package is auto-updated.

Last update: 2025-10-01 11:18:21 UTC


README

A Laravel package for sending SMS messages via Yeastar Gateway using the Asterisk Manager Interface (AMI) protocol. This package provides a clean, Laravel-friendly interface to interact with Yeastar GSM gateways.

Features

  • ๐Ÿš€ Simple Integration - Easy-to-use Laravel facade and service container integration
  • ๐Ÿ”’ Secure Connection - Uses AMI protocol for secure communication with Yeastar gateways
  • โš™๏ธ Configurable - Multiple gateway support with environment-based configuration
  • ๐Ÿงช Well Tested - Comprehensive test suite included
  • ๐Ÿ“ Detailed Logging - Built-in logging support for debugging and monitoring
  • ๐ŸŽฏ Type Safe - Full PHP 8.1+ type declarations and PHPDoc annotations
  • ๐Ÿ”„ Multiple Gateways - Support for multiple gateway configurations
  • โฑ๏ธ Timeout Control - Configurable connection and read timeouts

Requirements

  • PHP 8.1 or higher
  • Laravel 9.0, 10.0, or 11.0
  • Yeastar Gateway with AMI enabled
  • Network connectivity to the Yeastar gateway

Installation

You can install the package via Composer:

composer require andrejro2/yeastar-gsm-laravel

The package will automatically register its service provider and facade.

Publishing Configuration

Publish the configuration file to customize the package settings:

php artisan vendor:publish --tag="yeastar-sms-config"

This will create a config/yeastar-sms.php file where you can configure your gateway settings.

Configuration

Environment Variables

Add the following environment variables to your .env file:

# Default Yeastar Gateway Configuration
YEASTAR_HOST=192.168.1.1:5038
YEASTAR_USERNAME=admin
YEASTAR_SECRET=your_ami_secret

# Connection Timeouts (optional)
YEASTAR_CONNECTION_TIMEOUT=30
YEASTAR_READ_TIMEOUT=5

# Logging (optional)
YEASTAR_LOGGING_ENABLED=true
YEASTAR_LOG_CHANNEL=default

Multiple Gateway Support

You can configure multiple gateways for different environments:

# Production Gateway
YEASTAR_PROD_HOST=192.168.1.100:5038
YEASTAR_PROD_USERNAME=prod_user
YEASTAR_PROD_SECRET=prod_secret

# Staging Gateway
YEASTAR_STAGING_HOST=192.168.1.200:5038
YEASTAR_STAGING_USERNAME=staging_user
YEASTAR_STAGING_SECRET=staging_secret

AMI Configuration on Yeastar

Ensure that AMI is enabled on your Yeastar gateway:

  1. Log into your Yeastar web interface
  2. Go to Settings โ†’ System โ†’ AMI
  3. Enable AMI and configure a user with SMS sending permissions
  4. Note the port number (default is 5038)

Usage

Basic Usage with Facade

use AndrejRo2\LaravelYeastarSms\Facades\YeastarSms;
use AndrejRo2\LaravelYeastarSms\Exceptions\YeastarSmsException;

try {
    // Send SMS (connection configured via config/env)
    $success = YeastarSms::sendSms(
        port: 0,                        // GSM port (0-based)
        destination: '+1234567890',     // Phone number with country code
        message: 'Hello from Laravel!', // Message content
        id: 'SMS001'                   // Optional SMS ID for tracking
    );
    
    if ($success) {
        echo 'SMS sent successfully!';
    }
} catch (YeastarSmsException $e) {
    echo 'Error: ' . $e->getMessage();
}

Manual Connection Configuration

use AndrejRo2\LaravelYeastarSms\Facades\YeastarSms;

// Configure connection manually
YeastarSms::setConnection('192.168.1.1:5038', 'admin', 'secret');

// Send SMS
$success = YeastarSms::sendSms(0, '+1234567890', 'Hello World!');

Dependency Injection

use AndrejRo2\LaravelYeastarSms\Contracts\YeastarSmsInterface;

class SmsController extends Controller
{
    public function sendSms(YeastarSmsInterface $yeastarSms)
    {
        try {
            $success = $yeastarSms->sendSms(0, '+1234567890', 'Hello via DI!');
            
            return response()->json(['success' => $success]);
        } catch (YeastarSmsException $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}

Using Different Gateway Configurations

// Use a specific gateway configuration
$gatewayConfig = config('yeastar-sms.gateways.production');

YeastarSms::setConnection(
    $gatewayConfig['host'],
    $gatewayConfig['username'],
    $gatewayConfig['secret']
);

$success = YeastarSms::sendSms(0, '+1234567890', 'Production SMS');

Bulk SMS Sending

$phones = ['+1234567890', '+0987654321', '+1122334455'];
$message = 'Bulk SMS message';

foreach ($phones as $index => $phone) {
    try {
        $smsId = 'BULK_' . time() . '_' . $index;
        $success = YeastarSms::sendSms(0, $phone, $message, $smsId);
        
        if ($success) {
            echo "SMS sent to {$phone}\n";
        }
        
        // Add delay to prevent overwhelming the gateway
        usleep(500000); // 0.5 second delay
        
    } catch (YeastarSmsException $e) {
        echo "Failed to send SMS to {$phone}: " . $e->getMessage() . "\n";
    }
}

Artisan Command

The package includes an example Artisan command for sending SMS from the command line:

# Basic usage
php artisan sms:send "+1234567890" "Hello from command line!"

# With options
php artisan sms:send "+1234567890" "Hello!" --port=0 --gateway=production --id=CMD001

To use this command, copy the example from examples/ArtisanCommand.php to your app/Console/Commands/ directory.

API Reference

YeastarSms Methods

setConnection(string $host, string $username, string $secret): void

Configure the gateway connection parameters.

  • $host - Gateway hostname and port (e.g., "192.168.1.1:5038")
  • $username - AMI username
  • $secret - AMI secret/password

sendSms(int $port, string $destination, string $message, ?string $id = null): bool

Send an SMS message via the gateway.

  • $port - GSM port number (0-based, will be converted to 1-based for gateway)
  • $destination - Phone number in E.164 format (e.g., "+1234567890")
  • $message - SMS message content (max 160 characters recommended)
  • $id - Optional SMS ID for tracking (auto-generated if not provided)

Returns true on success, throws YeastarSmsException on failure.

getConnection(): ?array

Get the current connection configuration (with secret hidden).

setTimeout(int $timeout): self

Set connection timeout in seconds (default: 30).

setReadTimeout(int $readTimeout): self

Set read timeout in seconds (default: 5).

Exception Handling

The package throws YeastarSmsException for various error conditions:

try {
    YeastarSms::sendSms(0, '+1234567890', 'Test message');
} catch (YeastarSmsException $e) {
    // Handle specific error types
    $message = $e->getMessage();
    
    if (str_contains($message, 'connection')) {
        // Connection failed - check network/hostname
    } elseif (str_contains($message, 'authentication')) {
        // Authentication failed - check credentials
    } elseif (str_contains($message, 'SMS command failed')) {
        // SMS sending failed - check gateway/SIM status
    }
}

Configuration Reference

The package configuration file (config/yeastar-sms.php) includes:

return [
    // Default gateway configuration
    'default' => [
        'host' => env('YEASTAR_HOST', '192.168.1.1:5038'),
        'username' => env('YEASTAR_USERNAME', 'admin'),
        'secret' => env('YEASTAR_SECRET', 'admin'),
    ],
    
    // Connection timeouts
    'timeouts' => [
        'connection' => env('YEASTAR_CONNECTION_TIMEOUT', 30),
        'read' => env('YEASTAR_READ_TIMEOUT', 5),
    ],
    
    // Logging configuration
    'logging' => [
        'enabled' => env('YEASTAR_LOGGING_ENABLED', true),
        'channel' => env('YEASTAR_LOG_CHANNEL', 'default'),
    ],
    
    // Multiple gateway configurations
    'gateways' => [
        'production' => [...],
        'staging' => [...],
        'development' => [...],
    ],
];

Testing

Run the package tests:

composer test

Run tests with coverage:

composer test-coverage

Troubleshooting

Common Issues

  1. Connection Failed

    • Verify gateway hostname and port
    • Check network connectivity
    • Ensure firewall allows connection to AMI port (default 5038)
  2. Authentication Failed

    • Verify username and secret
    • Check if AMI is enabled on the gateway
    • Ensure user has proper permissions
  3. SMS Command Failed

    • Check if GSM module is properly configured
    • Verify SIM card balance and network registration
    • Ensure correct port number
  4. Timeout Errors

    • Increase timeout values in configuration
    • Check network latency
    • Verify gateway is responsive

Debugging

Enable logging to see detailed information about SMS sending:

YEASTAR_LOGGING_ENABLED=true
LOG_LEVEL=debug

This will log connection attempts, authentication, and SMS sending details.

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for details.

Security Vulnerabilities

If you discover a security vulnerability, please send an e-mail to the package maintainer. All security vulnerabilities will be promptly addressed.

Credits

This package is based on the Go implementation at yeastartgsms.

License

The MIT License (MIT). Please see License File for more information.

Changelog

Please see CHANGELOG.md for more information on what has changed recently.

Related Projects

Support

Made with โค๏ธ for the Laravel community