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

Onesignal Bundle Laravel Package

birkof/onesignal-bundle

Symfony bundle integrating the norkunas/onesignal-php-api library. Configure your OneSignal application/user keys and use the onesignal.api service from the container to manage notifications and other OneSignal API resources.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Integration

  1. Install the Bundle:

    composer require birkof/onesignal-bundle
    

    Note: Laravel’s autoloading handles bundle registration automatically (no manual AppKernel edits needed).

  2. Configure OneSignal: Add to .env (Laravel’s preferred config method):

    ONESIGNAL_APPLICATION_ID=your_app_id
    ONESIGNAL_APPLICATION_AUTH_KEY=your_auth_key
    ONESIGNAL_USER_AUTH_KEY=your_user_auth_key
    

    Or publish the config:

    php artisan vendor:publish --tag=onesignal-config
    

    Then update config/onesignal.php.

  3. First Use Case: Send a Notification Inject the service into a controller or command:

    use Adelplace\OneSignalBundle\Service\OneSignalApi;
    
    public function sendNotification(OneSignalApi $onesignal)
    {
        $response = $onesignal->notifications->create([
            'app_id' => config('onesignal.application_id'),
            'include_player_ids' => ['player_id_123'],
            'contents' => ['en' => 'Hello from Laravel!'],
        ]);
        return $response->json();
    }
    
  4. Verify Setup: Check the OneSignal Dashboard for delivered notifications or debug with:

    $onesignal->notifications->getAll(); // List recent notifications
    

Implementation Patterns

Core Workflows

  1. Notification Management:

    • Create/Schedule:
      $onesignal->notifications->create([
          'contents' => ['en' => 'Your order is shipping!'],
          'headings' => ['en' => 'Shipping Alert'],
          'data' => ['custom_key' => 'value'], // Deep linking
          'send_after' => '2024-12-31T00:00:00.000Z', // Scheduled
      ]);
      
    • Targeting: Use OneSignal’s segmentation via filter:
      $onesignal->notifications->create([
          'filters' => [
              ['field' => 'tag', 'key' => 'user_type', 'relation' => '==', 'value' => 'premium']
          ]
      ]);
      
  2. User Management:

    • Subscribe/Unsubscribe:
      $onesignal->players->create(['player_id' => 'user123', 'tags' => ['active_user']]);
      $onesignal->players->delete('user123'); // Unsubscribe
      
    • Tag Management:
      $onesignal->players->updateTags('user123', ['new_tag' => 'vip']);
      
  3. Event-Driven Integrations:

    • Laravel Events: Bind OneSignal actions to Laravel events (e.g., user.registered):
      use Illuminate\Support\Facades\Event;
      
      Event::listen('user.registered', function ($user) {
          $onesignal->players->create([
              'player_id' => $user->device_id,
              'tags' => ['user_id' => $user->id]
          ]);
      });
      
    • Queued Notifications: Use Laravel Queues to avoid timeouts for large campaigns:
      dispatch(new SendOneSignalNotification($recipients, $message));
      
  4. Template-Based Notifications:

    • Store notification templates in the database (e.g., notifications table) and hydrate dynamically:
      $template = NotificationTemplate::find(1);
      $onesignal->notifications->create([
          'contents' => ['en' => $template->message],
          'data' => ['url' => route('user.profile', $user->id)],
      ]);
      

Integration Tips

  • Laravel Service Container: Bind custom OneSignal services for reusable logic:

    $this->app->bind('onesignal.notification', function ($app) {
        return new class($app['onesignal.api']) {
            public function __construct(private OneSignalApi $api) {}
            public function sendWelcome($user) {
                return $this->api->notifications->create([
                    'contents' => ['en' => "Welcome, {$user->name}!"]
                ]);
            }
        };
    });
    
  • API Rate Limiting: Implement Laravel’s throttle middleware for OneSignal API calls:

    Route::middleware(['throttle:10,1'])->group(function () {
        Route::post('/send-notification', [NotificationController::class, 'send']);
    });
    
  • Testing: Use Laravel’s HTTP testing to mock OneSignal responses:

    $this->mock(OneSignalApi::class, function ($mock) {
        $mock->shouldReceive('notifications->create')
             ->once()
             ->andReturn((object) ['id' => 123]);
    });
    
  • Logging: Log OneSignal API responses for debugging:

    $response = $onesignal->notifications->create([...]);
    \Log::debug('OneSignal Response', ['data' => $response->json()]);
    

Gotchas and Tips

Pitfalls

  1. Authentication Issues:

    • Symptom: 401 Unauthorized errors despite correct keys.
    • Cause: The bundle uses application_auth_key for API auth and user_auth_key for user management. Ensure both are set in config.
    • Fix: Verify keys in .env or config/onesignal.php:
      'auth' => [
          'application' => env('ONESIGNAL_APPLICATION_AUTH_KEY'),
          'user' => env('ONESIGNAL_USER_AUTH_KEY'),
      ]
      
  2. PHP 8 Type Strictness:

    • Symptom: TypeError when calling methods like getAll().
    • Cause: The underlying norkunas/onesignal-php-api may return loosely typed data (e.g., mixed).
    • Fix: Cast responses explicitly:
      $notifications = (array) $onesignal->notifications->getAll()->json();
      
  3. Deprecated Laravel Facades:

    • Symptom: Class 'Facade\Ignition' not found in Laravel 9+.
    • Cause: The bundle may rely on older Facade patterns.
    • Fix: Use dependency injection instead:
      // ❌ Avoid
      $api = \OneSignal::api();
      
      // ✅ Use
      $api = app(OneSignalApi::class);
      
  4. Rate Limits:

    • Symptom: 429 Too Many Requests during bulk operations.
    • Cause: OneSignal’s rate limits (e.g., 1000 requests/minute).
    • Fix: Implement exponential backoff:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = $onesignal->getClient();
      $client->setOptions([
          'timeout' => 30,
          'max_duration' => 60,
          'retry_strategy' => new RetryStrategy(3, 1000, null, true),
      ]);
      
  5. Player ID Management:

    • Symptom: Duplicate player_ids or missing subscriptions.
    • Cause: Race conditions when creating/updating players.
    • Fix: Use Laravel’s database transactions:
      DB::transaction(function () use ($user, $onesignal) {
          $onesignal->players->create(['player_id' => $user->device_id]);
      });
      

Debugging Tips

  • Enable Verbose Logging: Configure the Symfony HTTP client to log requests:

    $onesignal->getClient()->setOptions([
        'headers' => ['User-Agent' => 'Laravel/OneSignal'],
        'debug' => true,
    ]);
    

    Check logs in storage/logs/laravel.log for raw API calls.

  • Validate Payloads: Use OneSignal’s payload validator to catch malformed requests early:

    $payload = [
        'app_id' => config('onesignal.application_id'),
        'contents' => ['en' => 'Test'],
    ];
    if (!isset($payload['contents']['en'])) {
        throw new \InvalidArgumentException('Missing notification content');
    }
    
  • Test with Sandbox: Use OneSignal’s sandbox environment for testing:

    $onesignal->setAppId('sandbox_app_id'); // Override in tests
    

Extension Points

  1. Custom Notification Channels: Extend Laravel’s notification system to use OneSignal:
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui