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

norkunas/onesignal-php-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require norkunas/onesignal-php-api
    

    Add to composer.json if using a custom package name.

  2. First Use Case: Sending a Push Notification

    use Norkunas\OneSignal\OneSignal;
    
    $oneSignal = new OneSignal('YOUR_ONESIGNAL_APP_ID', 'YOUR_ONESIGNAL_REST_API_KEY');
    $response = $oneSignal->sendNotification([
        'app_id' => 'YOUR_ONESIGNAL_APP_ID',
        'include_player_ids' => ['player_id_1', 'player_id_2'],
        'contents' => ['en' => 'Hello from Laravel!'],
    ]);
    
  3. Where to Look First

    • Documentation (if available)
    • src/Norkunas/OneSignal/OneSignal.php for core methods
    • tests/ for real-world usage examples

Implementation Patterns

Common Workflows

1. Sending Notifications

  • Basic Push
    $oneSignal->sendNotification([
        'contents' => ['en' => 'Your message'],
        'headings' => ['en' => 'Notification Title'],
        'include_player_ids' => [$playerId],
    ]);
    
  • Segmented Push (using filters)
    $oneSignal->sendNotification([
        'filters' => [
            ['field' => 'tag', 'key' => 'user_type', 'relation' => '=', 'value' => 'premium'],
        ],
        'contents' => ['en' => 'Exclusive offer!'],
    ]);
    

2. Managing Subscribers

  • Subscribe a Player
    $oneSignal->createPlayer([
        'player_id' => 'unique_id',
        'external_user_id' => 'user_id_from_your_db',
        'tags' => ['user_type' => 'premium'],
    ]);
    
  • Update Player Tags
    $oneSignal->updatePlayerTags('player_id', ['new_tag' => 'value']);
    

3. Handling Responses

  • Check for Success
    if ($response->isSuccess()) {
        $data = $response->getData();
    } else {
        $errors = $response->getErrors();
    }
    

4. Integration with Laravel

  • Service Provider Binding
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(OneSignal::class, function ($app) {
            return new OneSignal(
                config('services.onesignal.app_id'),
                config('services.onesignal.rest_key')
            );
        });
    }
    
  • Config File (config/services.php)
    'onesignal' => [
        'app_id' => env('ONESIGNAL_APP_ID'),
        'rest_key' => env('ONESIGNAL_REST_KEY'),
        'timezone' => 'UTC',
    ],
    

5. Batch Operations

  • Send to Multiple Segments
    $segments = ['segment1', 'segment2'];
    $oneSignal->sendNotificationToSegments($segments, [
        'contents' => ['en' => 'Batch message'],
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. API Rate Limits

    • OneSignal enforces 60 requests/minute. Cache responses or implement retries with exponential backoff.
    • Example:
      if ($attempts < 3) {
          sleep(2 ** $attempts); // Exponential backoff
          $response = $oneSignal->sendNotification(...);
      }
      
  2. Player ID vs. External ID

    • Player ID: Assigned by OneSignal (volatile, can change).
    • External ID: Your own ID (persistent, recommended for tracking).
    • Always use external_user_id for reliable targeting.
  3. Timezone Mismatches

    • OneSignal uses UTC by default. Ensure your scheduled notifications account for this:
      $oneSignal->sendNotification([
          'contents' => ['en' => 'Reminder'],
          'send_after' => now()->addHours(2)->timestamp, // UTC timestamp
      ]);
      
  4. Empty Responses

    • If sendNotification() returns no data, check:
      • Valid app_id and rest_key.
      • Correct include_player_ids or filters.
      • OneSignal dashboard for blocked IPs or rate limits.
  5. Webhook Verification

    • If using OneSignal webhooks (e.g., for subscription changes), verify the signature:
      $oneSignal->verifyWebhook($request->header('X-OneSignal-Key'), $request->getContent());
      

Debugging Tips

  • Enable Logging
    $oneSignal = new OneSignal($appId, $restKey, [
        'logger' => new \Monolog\Logger('onesignal', [
            new \Monolog\Handler\StreamHandler(storage_path('logs/onesignal.log')),
        ]),
    ]);
    
  • Check Raw Response
    $response = $oneSignal->sendNotification(...);
    \Log::debug('OneSignal Raw Response:', $response->getRawResponse());
    

Extension Points

  1. Custom HTTP Client Override the default Guzzle client for retry logic or middleware:

    $client = new \GuzzleHttp\Client(['timeout' => 30]);
    $oneSignal = new OneSignal($appId, $restKey, ['http_client' => $client]);
    
  2. Event Dispatching Trigger Laravel events after notifications:

    $response = $oneSignal->sendNotification(...);
    if ($response->isSuccess()) {
        event(new NotificationSent($response->getData()));
    }
    
  3. Mocking for Tests Use a mock HTTP client in tests:

    $mockClient = $this->createMock(\GuzzleHttp\Client::class);
    $mockClient->method('post')->willReturn(new \GuzzleHttp\Psr7\Response(200, [], json_encode(['success' => true])));
    $oneSignal = new OneSignal($appId, $restKey, ['http_client' => $mockClient]);
    

Pro Tips

  • Use sendAfter for Scheduled Notifications
    $oneSignal->sendNotification([
        'contents' => ['en' => 'Scheduled message'],
        'send_after' => strtotime('+1 hour'), // Unix timestamp
    ]);
    
  • Leverage data for Deep Links
    $oneSignal->sendNotification([
        'contents' => ['en' => 'Open app'],
        'data' => ['screen' => 'home', 'id' => '123'],
    ]);
    
    Handle in your app:
    // In your deep link handler
    $screen = $notification->data['screen'];
    
  • Batch Player Updates For bulk tag updates, use updatePlayersTags:
    $oneSignal->updatePlayersTags([
        'player_id_1' => ['tag1' => 'value1'],
        'player_id_2' => ['tag2' => 'value2'],
    ]);
    
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