Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Laravel Package

signalads/php

PHP client for the SignalAds REST API to send SMS messages. Supports single and bulk sends, pattern-based SMS, and structured error handling via ApiException/HttpException. Install with Composer and authenticate using your API key from the SignalAds panel.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require signalads-co/php
    

    Ensure vendor/autoload.php is included in your project (Laravel handles this automatically via composer.json).

  2. Retrieve API Key: Fetch your key from the SignalAds Panel.

  3. First Use Case: Send a single SMS in a Laravel controller:

    use SignalAds\SignalAdsApi;
    
    public function sendSms()
    {
        $api = new SignalAdsApi(config('services.signalads.key'));
        $response = $api->Send(
            config('services.signalads.sender_id'),
            '09123456789',
            'Hello from Laravel!'
        );
        return response()->json($response);
    }
    

Laravel Integration

Add to config/services.php:

'signalads' => [
    'key' => env('SIGNALADS_API_KEY'),
    'sender_id' => env('SIGNALADS_SENDER_ID'),
],

Implementation Patterns

Core Workflows

  1. Single SMS:

    $api->Send($senderId, $recipient, $message);
    
    • Use for one-off notifications (e.g., OTPs, alerts).
  2. Bulk SMS:

    $api->SendGroup($senderId, ['09123456789', '09123456788'], $message);
    
    • Ideal for marketing campaigns or batch updates.
    • Tip: Validate recipients against a database to avoid duplicates.
  3. Templated SMS:

    $api->SendPattern($senderId, '12345', ['param1', 'param2'], $recipients);
    
    • Predefined templates reduce errors and improve consistency.
    • Laravel Tip: Store pattern_id in a config file for reusability.
  4. Status Checks:

    $api->Status($messageId, 10, 0, 4); // Get last 10 delivered messages
    
    • Use in queues/jobs to track delivery (e.g., after bulk sends).

Laravel-Specific Patterns

  1. Service Provider: Bind the API client for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(SignalAdsApi::class, function ($app) {
            return new SignalAdsApi(config('services.signalads.key'));
        });
    }
    
  2. Queued Jobs: Dispatch SMS sends asynchronously:

    use Illuminate\Support\Facades\Bus;
    
    Bus::dispatch(new SendSmsJob($recipient, $message));
    
    // app/Jobs/SendSmsJob.php
    public function handle()
    {
        $api = app(SignalAdsApi::class);
        $api->Send(config('services.signalads.sender_id'), $this->recipient, $this->message);
    }
    
  3. API Responses: Normalize responses for consistency:

    $response = $api->Send(...);
    if ($response['error']['message']) {
        Log::error("SMS failed: " . $response['error']['message']);
        return back()->with('error', 'Failed to send SMS');
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Security:

    • Never hardcode keys. Use Laravel’s .env and config/services.php.
    • Gotcha: The package lacks rate-limiting checks. Implement retries with exponential backoff in your code:
      try {
          $api->Send(...);
      } catch (ApiException $e) {
          if ($e->getCode() === 429) { // Rate limited
              sleep(2);
              retry();
          }
      }
      
  2. Recipient Validation:

    • SignalAds may reject invalid numbers (e.g., non-Iranian). Pre-validate with:
      if (!preg_match('/^09[0-9]{9}$/', $phone)) {
          throw new \InvalidArgumentException('Invalid phone number');
      }
      
  3. Pattern IDs:

    • Gotcha: Pattern IDs are case-sensitive and must match the API exactly. Fetch available patterns via the SignalAds Panel.
  4. Status Codes:

    • PENDING (1) may persist for minutes. Avoid polling too frequently (e.g., use Laravel’s schedule for delayed checks).

Debugging

  1. HTTP Exceptions:

    • Enable Guzzle’s debug middleware to inspect raw API responses:
      $api = new SignalAdsApi($key, [
          'debug' => true,
          'handler' => new \GuzzleHttp\HandlerStack(),
      ]);
      
  2. Logging:

    • Wrap API calls in a logger:
      try {
          $response = $api->Send(...);
          Log::info('SMS sent', ['response' => $response]);
      } catch (Exception $e) {
          Log::error('SMS failed', ['error' => $e->getMessage()]);
      }
      

Extension Points

  1. Custom Responses:

    • Extend the SignalAdsApi class to add methods for unsupported endpoints (e.g., GetBalance):
      class ExtendedSignalAdsApi extends SignalAdsApi {
          public function GetBalance() {
              return $this->request('GET', '/balance');
          }
      }
      
  2. Webhook Integration:

    • Use the Status endpoint to build a Laravel route for real-time updates:
      Route::post('/sms/webhook', function (Request $request) {
          $api = new SignalAdsApi(config('services.signalads.key'));
          $status = $api->Status($request->message_id);
          // Process status updates (e.g., trigger events)
      });
      
  3. Testing:

    • Mock the API in PHPUnit:
      $mockHandler = new \GuzzleHttp\Handler\MockHandler([
          new \GuzzleHttp\Psr7\Response(200, [], json_encode(['data' => ['message_id' => 'test']]))
      ]);
      $api = new SignalAdsApi($key, ['handler' => new \GuzzleHttp\HandlerStack($mockHandler)]);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor