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

Sdk Laravel Package

textmagic/sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Add the package via Composer:

    composer require textmagic/sdk
    

    Or manually clone the repository and include the autoload.php file.

  2. First Use Case: Initialize the client with your credentials:

    $client = new \TextmagicRestClient('<YOUR_USERNAME>', '<YOUR_API_TOKEN>');
    
    • Replace <YOUR_USERNAME> and <YOUR_API_TOKEN> with your TextMagic account credentials (found in your TextMagic dashboard).
  3. Send a Test SMS:

    $result = $client->messages->create([
        'text' => 'Hello from Laravel!',
        'phones' => '1234567890'
    ]);
    
    • Verify the response contains a success key or an error message.
  4. Key Files to Explore:

    • src/TextmagicRestClient.php: Core client logic.
    • src/Exceptions/RestException.php: Error handling.
    • src/Resources/Message.php: Message-related methods.

Implementation Patterns

Common Workflows

  1. Sending SMS:

    • Use messages->create() for one-time sends or bulk messages.
    • Example: Send to multiple recipients:
      $phones = ['1234567890', '0987654321'];
      $result = $client->messages->create([
          'text' => 'Your OTP is 1234',
          'phones' => implode(',', $phones)
      ]);
      
  2. Retrieving Messages:

    • Fetch sent messages with messages->get():
      $sentMessages = $client->messages->get(['limit' => 10]);
      
  3. Handling Responses:

    • Always wrap calls in try-catch to handle RestException:
      try {
          $result = $client->messages->create([...]);
      } catch (\Textmagic\Exceptions\RestException $e) {
          Log::error('TextMagic Error: ' . $e->getMessage());
      }
      
  4. Bulk Operations:

    • Use messages->create() with comma-separated phone numbers for bulk sends.
    • For large volumes, consider batching requests (e.g., 100 phones per call).
  5. Webhooks:

    • Configure webhooks in your TextMagic dashboard to receive delivery reports.
    • Validate incoming webhook payloads using the Webhook class:
      $webhook = new \Textmagic\Webhook($payload);
      if ($webhook->isValid()) {
          // Process delivery status
      }
      

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    $this->app->singleton(\TextmagicRestClient::class, function ($app) {
        return new \TextmagicRestClient(config('services.textmagic.username'), config('services.textmagic.token'));
    });
    

    Configure credentials in config/services.php:

    'textmagic' => [
        'username' => env('TEXTMAGIC_USERNAME'),
        'token' => env('TEXTMAGIC_API_TOKEN'),
    ],
    
  • Queued Jobs: Dispatch SMS sends as Laravel jobs for async processing:

    SendSmsJob::dispatch($client, $messageData);
    

    Example job:

    public function handle(TextmagicRestClient $client, array $data) {
        $client->messages->create($data);
    }
    
  • Logging: Log all API responses/errors for debugging:

    try {
        $result = $client->messages->create([...]);
        Log::info('SMS sent', ['message_id' => $result['id']]);
    } catch (\Exception $e) {
        Log::error('SMS failed', ['error' => $e->getMessage()]);
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits:

    • TextMagic enforces rate limits (e.g., 1 SMS/second for free plans).
    • Handle 429 Too Many Requests errors gracefully with exponential backoff:
      if ($e->getStatusCode() === 429) {
          sleep(2); // Retry after delay
      }
      
  2. Phone Number Formatting:

    • Ensure phone numbers are in E.164 format (e.g., +1234567890).
    • Strip non-numeric characters before sending:
      $cleanedPhone = preg_replace('/[^0-9]/', '', $phone);
      
  3. Character Limits:

    • SMS text is limited to 160 characters (70 for Unicode).
    • Longer messages auto-split; test with text field to confirm.
  4. API Token Exposure:

    • Never hardcode tokens in source files. Use Laravel’s .env:
      TEXTMAGIC_USERNAME=your_username
      TEXTMAGIC_API_TOKEN=your_token_here
      
  5. Webhook Validation:

    • Always validate webhook signatures to prevent spoofing:
      $webhook = new \Textmagic\Webhook($payload, config('services.textmagic.webhook_secret'));
      if (!$webhook->isValid()) {
          abort(403, 'Invalid webhook');
      }
      

Debugging

  • Enable Debug Mode: Set the client’s debug flag to log raw API requests/responses:

    $client = new \TextmagicRestClient($username, $token, [
        'debug' => true,
        'logger' => new \Textmagic\Logger\FileLogger('/path/to/logs.txt')
    ]);
    
  • Common Errors:

    • 401 Unauthorized: Invalid username/token.
    • 400 Bad Request: Malformed phone numbers or text.
    • 500 Server Error: Contact TextMagic support.

Extension Points

  1. Custom Response Handling:

    • Extend the Message class to add domain-specific logic:
      class CustomMessage extends \Textmagic\Resources\Message {
          public function sendWithTemplate($templateId) {
              return $this->create([
                  'text' => $this->getTemplateText($templateId),
                  'phones' => $this->phones
              ]);
          }
      }
      
  2. Mocking for Tests:

    • Use PHP’s Mockery to stub API calls:
      $mockClient = Mockery::mock(\TextmagicRestClient::class);
      $mockClient->shouldReceive('messages->create')
          ->once()
          ->andReturn(['id' => '123']);
      
  3. Adding New Endpoints:

    • The SDK follows a RESTful pattern. To add support for a new endpoint (e.g., contacts):
      $client->contacts->create(['name' => 'John', 'phone' => '123']);
      
    • Extend TextmagicRestClient to include the new resource:
      $this->contacts = new \Textmagic\Resources\Contact($this);
      
  4. Retry Logic:

    • Implement a retry decorator for transient failures:
      class RetryClient {
          public function create($data, $maxRetries = 3) {
              $retries = 0;
              while ($retries < $maxRetries) {
                  try {
                      return $client->messages->create($data);
                  } catch (\Textmagic\Exceptions\RestException $e) {
                      if ($e->getStatusCode() !== 429) throw $e;
                      sleep(2 ** $retries);
                      $retries++;
                  }
              }
              throw new \RuntimeException('Max retries exceeded');
          }
      }
      
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.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
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