Weave 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 Client Laravel Package

smsapi/php-client

SMSAPI PHP Client is a Composer package for integrating your PHP app with the SMSAPI.COM and SMSAPI.PL APIs. Since v3 it supports PSR-17 and PSR-18 HTTP clients, with a ready-made Curl adapter. Install via composer require smsapi/php-client.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require smsapi/php-client:^4.0.1
    

    Pin to ^4.0.1 or later. The v4.0.1 patch fixes a PHP 8.5 curl_close() deprecation, a TypeError when curl_init() fails, and several HTTP client cURL issues — if you are on PHP 8.4/8.5 or run in environments where cURL can fail (containers with restricted networking), earlier 4.0.x builds can throw fatal errors instead of returning a clean failure.

  2. Verify the transport

    php -m | grep curl
    php -v
    

    The library talks to the API over cURL. Confirm the extension is enabled and that you have not disabled allow_url_fopen-style outbound HTTP in your runtime.

  3. Basic Configuration Create a config file (e.g., config/smsapi.php) with your API credentials:

    return [
        'api_key' => env('SMSAPI_KEY'),
        'base_url' => env('SMSAPI_BASE_URL', 'https://api.smsapi.com'),
    ];
    
  4. First Use Case: Sending a Text Message

    use Smsapi\Client;
    
    $client = new Client(config('smsapi.api_key'), config('smsapi.base_url'));
    $response = $client->sendSms(
        'from' => 'YourBrand',
        'to' => '1234567890',
        'text' => 'Hello from Laravel!'
    );
    
  5. Laravel Service Provider (Optional) Bind the client to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            return new Client(config('smsapi.api_key'), config('smsapi.base_url'));
        });
    }
    

Implementation Patterns

Common Workflows

  1. Sending Bulk SMS

    $client->sendSms([
        'from' => 'YourBrand',
        'to' => ['1234567890', '0987654321'],
        'text' => 'Bulk message to multiple recipients.'
    ]);
    
  2. Handling Responses Check the response status and data:

    if ($response->isSuccess()) {
        $messageId = $response->getMessageId();
        // Log or store $messageId for tracking.
    } else {
        $error = $response->getError();
        Log::error("SMS failed: " . $error);
    }
    
  3. Laravel Notifications Integration Extend the notification channel with a custom driver:

    // app/Notifications/SmsVerification.php
    public function via($notifiable)
    {
        return ['sms'];
    }
    
    public function toSms($notifiable)
    {
        return [
            'from' => 'YourBrand',
            'to' => $notifiable->phone,
            'text' => 'Your verification code: ' . $this->verificationCode,
        ];
    }
    
  4. Queueing SMS Jobs Dispatch a job for async sending:

    // app/Jobs/SendSmsJob.php
    use Smsapi\Client;
    
    public function handle(Client $client)
    {
        $client->sendSms($this->messageData);
    }
    
  5. Transport Resilience (new in 4.0.1) A failed curl_init() now surfaces as a normal error instead of a TypeError. Treat transport failures and API failures as distinct so you can retry the former safely:

    try {
        $response = $client->sendSms($payload);
    } catch (\Throwable $e) {
        // Transport/connection level — retry with backoff, don't mark as "sent".
        throw $e;
    }
    
    if (! $response->isSuccess()) {
        // API level rejection (bad number, no credits, throttling).
    }
    

Integration Tips

  • Environment Variables: Use .env for sensitive data (e.g., SMSAPI_KEY).
  • Rate Limiting: Implement a queue (e.g., Laravel Queues) to avoid hitting API limits.
  • Logging: Log all SMS attempts (success/failure) for auditing.
  • Fallbacks: Combine with another SMS provider (e.g., Twilio) as a backup.
  • Stay patched: Track 4.0.x releases. The 4.0.1 patch is a drop-in bugfix — no API changes — so upgrading from 4.0.0 is low risk and recommended.
  • Version pinning in CI: If you cannot upgrade immediately, pin 4.0.0 explicitly so a fresh composer update doesn't silently move you between cURL behaviours.

Gotchas and Tips

Pitfalls

  1. Package Maintenance Status

    • The package is actively receiving patch releases (4.0.1 adds a first-time contributor fix and a cURL reliability fix), so the earlier "archived/unmaintained" assumption no longer holds.
    • Still, releases are infrequent and patch-level. Do not assume modern Laravel-first ergonomics (no first-party service provider, facade, or config publishing) — wire it up yourself as shown above.
  2. PHP 8.5 cURL Deprecation

    • In 4.0.1, curl_close() handling no longer emits the PHP 8.5 deprecation. If you are on 8.5 and still see the deprecation, you are resolving an older version — check with composer show smsapi/php-client.
    • Deprecations are noisy in strict error handlers; if you convert deprecations to exceptions (set_error_handler / ErrorException), older versions will hard-fail on sends.
  3. cURL Init Failures

    • Pre-4.0.1, a failed curl_init() threw a TypeError that bypassed typical \Exception catches. Catch \Throwable, not just \Exception, if you must support older versions.
  4. Error Handling

    • The package may lack detailed error messages. Wrap calls in try-catch:
      try {
          $response = $client->sendSms(...);
      } catch (\Throwable $e) {
          Log::error("SMS API error: " . $e->getMessage());
      }
      
  5. API Key Exposure

    • Avoid hardcoding keys. Use Laravel's .env and config/services.php.
  6. Character Limits

    • SMS messages are typically limited to 160 characters. Split long messages:
      $client->sendSms([
          'from' => 'YourBrand',
          'to' => '1234567890',
          'text' => chunk_split($longText, 153, "\n"), // Split into parts
      ]);
      

Debugging Tips

  • Enable API Debugging: Check the package's docs for a debug mode or enable HTTP logging:
    \Smsapi\Client::setDebug(true); // If supported.
    
  • Inspect Raw Responses: Dump the raw API response for troubleshooting:
    dd($response->getRawResponse());
    
  • Confirm the installed version when diagnosing transport bugs — most cURL complaints are resolved by moving to ^4.0.1:
    composer show smsapi/php-client
    
  • Test with Sandbox: Use a sandbox/test API key if available.

Extension Points

  1. Custom Response Handling Extend the Response class to add domain-specific logic:

    class CustomResponse extends \Smsapi\Response
    {
        public function isDelivered()
        {
            return $this->getStatus() === 'DELIVERED';
        }
    }
    
  2. Middleware for SMS Add middleware to validate phone numbers or log metadata:

    // app/Http/Middleware/SmsValidation.php
    public function handle($request, Closure $next)
    {
        if ($request->input('to') && !preg_match('/^\d{10,15}$/', $request->input('to'))) {
            abort(422, 'Invalid phone number.');
        }
        return $next($request);
    }
    
  3. Mocking for Tests Use Laravel's mocking to test SMS logic without hitting the API:

    $mock = Mockery::mock(Client::class);
    $mock->shouldReceive('sendSms')->once()->andReturn(new \Smsapi\Response(true));
    $this->app->instance(Client::class, $mock);
    
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.
encore2/laravel-admin2
cboxdk/laravel-console-kit
shapecode/doctrine-dbal-datetimeutc
gilads-otiannoh254/inertia-protocol
dakiquang/laravel-oauth-refresh-lock
woda/laravel-worktrees
dalefranks/ramasite
faghy/laracashbook
roundly-consulting/google-places-for-laravel
roundly-consulting/kubernetes-api-for-laravel
roundly-consulting/plausible-for-laravel
gvp/gvp-laravel-template
metasyncsite/laravel-metasync-client
roundly-consulting/onboarding-for-laravel
adachsoft/cli-process-tester
adachsoft/changelog-linter
adachsoft/collection
adachsoft/php-code-style
adachsoft/api-version-bundle
cgv/localized-resource