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

Mobyt Notifier Laravel Package

symfony/mobyt-notifier

Symfony Notifier bridge for Mobyt SMS. Configure via MOBYT_DSN with user key, access token, sender, and message quality. Supports MobytOptions to customize message type and other delivery parameters when sending SmsMessage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package alongside Symfony Notifier (Laravel’s Notifications already includes it):

    composer require symfony/notifier mobyt/mobyt-notifier
    
  2. Add DSN to .env:

    MOBYT_DSN=mobyt://USER_KEY:ACCESS_TOKEN@default?from=+391234567890&type_quality=L
    
    • Replace USER_KEY, ACCESS_TOKEN, and from with Mobyt credentials.
    • type_quality defaults to L (medium); use N for high priority or LL for low cost.
  3. Create a Mobyt SMS Notification:

    use Illuminate\Notifications\Notification;
    use Symfony\Component\Notifier\Message\SmsMessage;
    use Symfony\Component\Notifier\Bridge\Mobyt\MobytOptions;
    
    class MobytSmsNotification extends Notification
    {
        public function via($notifiable)
        {
            return ['mobyt']; // Requires custom channel registration
        }
    
        public function toMobyt($notifiable)
        {
            $message = new SmsMessage(
                recipient: $notifiable->phone,
                text: 'Hello from Mobyt!'
            );
    
            // Optional: Set Mobyt-specific options
            $message->options(
                (new MobytOptions())
                    ->messageType(MobytOptions::MESSAGE_TYPE_QUALITY_HIGH)
            );
    
            return $message;
        }
    }
    
  4. Register the Mobyt Channel (if not auto-detected):

    // config/services.php
    'notifications' => [
        'channels' => [
            'mobyt' => [
                'dsn' => env('MOBYT_DSN'),
            ],
        ],
    ];
    

First Use Case: Sending a Transactional SMS

use App\Notifications\MobytSmsNotification;
use App\Models\User;

$user = User::find(1);
$user->notify(new MobytSmsNotification());

Implementation Patterns

1. Channel Registration

Leverage Laravel’s custom notification channels to integrate Mobyt:

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Notification;
use Symfony\Component\Notifier\Notifier;
use Symfony\Component\Notifier\Transport\Dsn;

public function boot()
{
    Notification::extend('mobyt', function ($app) {
        $dsn = new Dsn(env('MOBYT_DSN'));
        $notifier = new Notifier([$dsn]);

        return new class($notifier) implements Illuminate\Notifications\Channel {
            public function __construct(private Notifier $notifier) {}

            public function send($notifiable, $notification)
            {
                $message = $notification->toMobyt($notifiable);
                $this->notifier->send($message);
            }
        };
    });
}

2. Dynamic Options

Use MobytOptions for Mobyt-specific features:

$options = (new MobytOptions())
    ->messageType(MobytOptions::MESSAGE_TYPE_QUALITY_HIGH)
    ->reference('ORDER_12345') // Mobyt’s reference ID
    ->validity(24); // Message validity in hours

$sms->options($options);

3. Batch Sending

For bulk SMS (e.g., marketing campaigns), use Laravel’s queued notifications:

$user->notify(new MobytSmsNotification())->onQueue('mobyt');
  • Queue Setup: Configure mobyt queue in config/queue.php:
    'connections' => [
        'mobyt' => [
            'driver' => 'sync', // Or 'database', 'redis', etc.
            'notifier' => true, // Custom logic to batch Mobyt requests
        ],
    ],
    

4. Fallback Mechanism

Handle Mobyt API failures gracefully:

public function send($notifiable, $notification)
{
    try {
        $message = $notification->toMobyt($notifiable);
        $this->notifier->send($message);
    } catch (\Exception $e) {
        // Fallback to another channel (e.g., email)
        $notifiable->notify(new FallbackNotification());
    }
}

5. Testing

Mock Mobyt responses in tests:

use Symfony\Component\Notifier\Test\TransportTestCase;

public function testMobytNotification()
{
    $transport = new MobytTransport(new Dsn(env('MOBYT_DSN')));
    $this->assertInstanceOf(SmsMessage::class, $transport->send(new SmsMessage('+123', 'Test')));

    // Assert Mobyt-specific options were applied
    $this->assertEquals(
        MobytOptions::MESSAGE_TYPE_QUALITY_HIGH,
        $transport->getLastMessage()->options()->messageType()
    );
}

Gotchas and Tips

Pitfalls

  1. DSN Configuration Errors:

    • Issue: MOBYT_DSN must include from (sender phone) and type_quality.
    • Fix: Validate DSN format in .env:
      MOBYT_DSN=mobyt://USER_KEY:ACCESS_TOKEN@default?from=+391234567890&type_quality=L
      
    • Debug: Check Symfony Notifier logs for malformed DSN errors.
  2. PHP Version Mismatch:

    • Issue: The package requires PHP 8.4+ (Symfony 8.0+). Laravel 10 uses Symfony 6.4+, which may cause conflicts.
    • Fix: Pin symfony/notifier to ^6.4 in composer.json:
      "require": {
          "symfony/notifier": "^6.4",
          "mobyt/mobyt-notifier": "^7.4"
      }
      
  3. Recipient Format:

    • Issue: Mobyt expects international phone numbers (e.g., +393451234567). Local formats (e.g., 3451234567) may fail.
    • Fix: Normalize phone numbers using libphonenumber:
      use libphonenumber\PhoneNumberUtil;
      use libphonenumber\PhoneNumberFormat;
      
      $phone = PhoneNumberUtil::getInstance()->parse($user->phone, 'IT');
      $recipient = $phone->format(PhoneNumberFormat::E164);
      
  4. Rate Limits and Costs:

    • Issue: Mobyt’s TYPE_QUALITY affects delivery speed and cost. N (high) is faster but pricier.
    • Tip: Use L (medium) for bulk messages and N for urgent alerts (e.g., password resets).
  5. No Async Support by Default:

    • Issue: Symfony Notifier sends messages synchronously by default.
    • Fix: Use Laravel’s queues to batch requests:
      // config/queue.php
      'connections' => [
          'mobyt' => [
              'driver' => 'database',
              'table' => 'mobyt_jobs',
              'notifier' => true,
          ],
      ];
      

Debugging Tips

  1. Enable Symfony Notifier Debugging:

    // config/services.php
    'notifier' => [
        'debug' => env('APP_DEBUG', false),
    ];
    
    • Logs will include Mobyt API responses/errors.
  2. Check Mobyt API Status:

    • Verify Mobyt’s system status if messages fail silently.
    • Workaround: Implement retry logic with exponential backoff.
  3. Validate Phone Numbers:

Extension Points

  1. Custom Transport: Extend MobytTransport to add features like:

    class CustomMobytTransport extends MobytTransport
    {
        public function __construct(Dsn $dsn, private array $customHeaders = [])
        {
            parent::__construct($dsn);
        }
    
        protected function getHeaders(): array
        {
            return array_merge(parent::getHeaders(), $this->customHeaders);
        }
    }
    
  2. Webhook Integration: Listen to Mobyt’s delivery reports via webhooks:

    Route::post('/mobyt/webhook', function (Request $request) {
        $event = $request->json()->all();
        // Log or process delivery status (e.g., 'delivered', 'failed')
    });
    
  3. Message Templates: Use Mobyt’s template system for consistent formatting:

    $options = (new MobytOptions())
        ->templateId('TEMPLATE_123')
        ->templateParams(['name'
    
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.
terminal42/code-quality-tools
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