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 Rest Api Laravel Package

messagebird/php-rest-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require messagebird/php-rest-api
    

    Add your API key to .env:

    MESSAGEBIRD_API_KEY=your_api_key_here
    
  2. First Use Case: Sending an SMS

    use MessageBird\Client;
    use MessageBird\Objects\Message;
    
    $client = new Client(config('messagebird.api_key'));
    $message = $client->messages->create([
        'originator' => 'YourBrand',
        'recipients' => ['447123456789'],
        'body' => 'Hello from MessageBird!'
    ]);
    
  3. Configuration Place API key in config/services.php:

    'messagebird' => [
        'api_key' => env('MESSAGEBIRD_API_KEY'),
    ],
    

    Access via config('messagebird.api_key').


Implementation Patterns

Common Workflows

1. Sending Messages

  • Basic SMS

    $client->messages->create([
        'originator' => 'Support',
        'recipients' => ['+1234567890'],
        'body' => 'Your verification code is 12345.'
    ]);
    
  • Transactional Messages (with Template)

    $client->messages->create([
        'originator' => 'AppName',
        'recipients' => ['+1234567890'],
        'body' => 'Your order #{{orderId}} is confirmed!',
        'template' => 'ORDER_CONFIRMATION'
    ]);
    
  • Multipart Messages (Long SMS)

    $client->messages->create([
        'originator' => 'News',
        'recipients' => ['+1234567890'],
        'body' => 'Part 1... [LONG_MESSAGE] Part 2...',
        'multipart' => true
    ]);
    

2. Retrieving Message Status

$message = $client->messages->get('message_id');
$status = $message->getStatus(); // 'scheduled', 'sent', 'delivered', etc.

3. Batch Processing

$recipients = ['+1234567890', '+1987654321'];
foreach ($recipients as $phone) {
    $client->messages->create([
        'originator' => 'BatchSend',
        'recipients' => [$phone],
        'body' => 'Batch message for ' . $phone
    ]);
}

4. Webhooks (Event Handling)

  • Configure webhook URL in MessageBird dashboard.
  • Validate signatures in Laravel middleware:
    public function handle($request, Closure $next) {
        $signature = $request->header('X-MessageBird-Signature');
        $payload = $request->getContent();
        $expectedSignature = hash_hmac(
            'sha256',
            $payload,
            config('messagebird.webhook_secret')
        );
        if (!hash_equals($expectedSignature, $signature)) {
            abort(401, 'Invalid signature');
        }
        return $next($request);
    }
    
  • Route webhook payloads:
    Route::post('/messagebird/webhook', [MessageWebhookController::class, 'handle']);
    

5. Rate Limiting & Retries

  • Use Laravel’s retry helper for transient failures:
    use Illuminate\Support\Facades\Retry;
    
    Retry::retry(3, function () use ($client, $messageData) {
        try {
            $client->messages->create($messageData);
        } catch (Exception $e) {
            if ($e->getCode() !== 429) { // Rate limited
                throw $e;
            }
            sleep(1); // Backoff
        }
    });
    

Gotchas and Tips

Common Pitfalls

  1. Phone Number Formatting

    • Always include country code (e.g., +1234567890, not 234567890).
    • Use E.164 format for reliability.
  2. Originator Length

    • Maximum 11 characters (including spaces).
    • Avoid special characters or emojis.
  3. Character Limits

    • SMS: 1600 characters (70 chars per segment for multipart).
    • MMS: 300KB max (including media).
  4. Webhook Delays

    • MessageBird may take up to 30 seconds to deliver webhooks.
    • Use exponential backoff for retries.
  5. API Key Exposure

    • Never commit .env to version control.
    • Restrict API key permissions in MessageBird dashboard.

Debugging Tips

  1. Enable Debug Mode

    $client = new Client(config('messagebird.api_key'), [
        'debug' => true,
        'logger' => new \Monolog\Logger('messagebird')
    ]);
    
  2. Inspect Raw Responses

    try {
        $response = $client->messages->create($data);
    } catch (\MessageBird\Exceptions\MessageBirdException $e) {
        \Log::error('MessageBird Error:', [
            'code' => $e->getCode(),
            'message' => $e->getMessage(),
            'raw_response' => $e->getResponseData()
        ]);
    }
    
  3. Test in Sandbox

    • Use MessageBird’s sandbox environment for testing:
      $client = new Client(config('messagebird.api_key'), [
          'environment' => 'sandbox'
      ]);
      

Extension Points

  1. Custom Response Handling

    • Extend the MessageBird\Client class to add middleware:
      class CustomClient extends \MessageBird\Client {
          public function __construct($apiKey, array $options = []) {
              parent::__construct($apiKey, $options);
              $this->addMiddleware(new \App\MessageBird\LoggingMiddleware());
          }
      }
      
  2. Queue Delayed Messages

    • Dispatch jobs with delays:
      SendSmsJob::dispatch($recipient, $message)
          ->delay(now()->addMinutes(5)); // Schedule for later
      
  3. Template Management

    • Fetch and cache templates:
      $templates = $client->messages->templates->get();
      $template = $templates->find(fn($t) => $t->getName() === 'ORDER_CONFIRMATION');
      
  4. Fallback for Failed Messages

    • Implement a retry queue or fallback (e.g., email):
      if ($message->getStatus() === 'failed') {
          Mail::to($user->email)->send(new SmsFallbackMail($message));
      }
      

Configuration Quirks

  • Environment-Specific Keys Use Laravel’s env() with fallbacks:

    'api_key' => env('MESSAGEBIRD_API_KEY', env('MESSAGEBIRD_SANDBOX_KEY')),
    
  • Proxy Support Configure proxy in client options:

    $client = new Client($apiKey, [
        'proxy' => 'http://proxy.example.com:8080'
    ]);
    
  • Timeouts Adjust HTTP client timeout (default: 30s):

    $client = new Client($apiKey, [
        'timeout' => 60 // 60 seconds
    ]);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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