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 Onesignal Sdk Laravel Package

namnv609/php-onesignal-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require namnv609/php-onesignal-sdk
    

    Note: Due to PHP 5.5+ requirement, ensure your Laravel app uses PHP 5.6+ or configure a compatibility layer.

  2. Configure OneSignal: Add your credentials to .env:

    ONESIGNAL_AUTH_KEY=your_auth_key_here
    ONESIGNAL_APP_ID=your_app_id
    ONESIGNAL_REST_KEY=your_rest_key
    
  3. Initialize the SDK: Create a service class (e.g., app/Services/OneSignalService.php):

    namespace App\Services;
    
    use NNV\OneSignal\OneSignal;
    
    class OneSignalService
    {
        protected $client;
    
        public function __construct()
        {
            $this->client = new OneSignal(
                env('ONESIGNAL_AUTH_KEY'),
                env('ONESIGNAL_APP_ID'),
                env('ONESIGNAL_REST_KEY')
            );
        }
    
        // Delegate methods (e.g., sendNotification) here
    }
    
  4. Register the Service: Bind the service in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(OneSignalService::class, function ($app) {
            return new OneSignalService();
        });
    }
    
  5. First Use Case: Send a test notification:

    use App\Services\OneSignalService;
    use NNV\OneSignal\API\Notification;
    
    public function sendTestNotification(OneSignalService $service)
    {
        $notification = new Notification($service->getClient());
        $notification->create([
            'included_segments' => ['All'],
            'contents' => ['en' => 'Hello from Laravel!'],
        ]);
    }
    

Implementation Patterns

Core Workflows

1. Device Management

  • Register a Device:

    $player = new Player($service->getClient());
    $player->create(\NNV\OneSignal\Constants\DeviceTypes::CHROME_WEBSITE, [
        'language' => 'en',
        'tags' => ['user_id' => auth()->id()],
    ]);
    

    Use Case: Track user devices for targeted notifications (e.g., web push, mobile).

  • Update Device Tags:

    $player->update($playerId, [
        'tags' => ['new_tag' => 'value'],
    ]);
    

    Use Case: Dynamic segmentation (e.g., "premium_users").

2. Notification Campaigns

  • Send a Scheduled Notification:

    $notification = new Notification($service->getClient());
    $notification->create([
        'included_segments' => ['Active Users'],
        'contents' => ['en' => 'Your order is shipping!'],
        'send_after' => '2023-12-31 12:00:00', // ISO format
    ]);
    

    Use Case: Marketing campaigns, order updates.

  • Cancel a Notification:

    $notification->cancel($notificationId);
    

    Use Case: Emergency overrides (e.g., recall a promotional message).

3. Analytics & Tracking

  • Track Notification Opens:

    $notification->trackOpen($notificationId);
    

    Use Case: Measure engagement (e.g., "Did users click the discount notification?").

  • Export Player Data (CSV):

    $player->csvExport(['email', 'created_at']);
    

    Use Case: Audits, user segmentation for CRM.


Laravel-Specific Patterns

1. Event-Driven Notifications

  • Trigger notifications from Laravel events (e.g., OrderShipped):
    use Illuminate\Support\Facades\Event;
    
    Event::listen(OrderShipped::class, function ($order) {
        $service->sendNotification([
            'included_segments' => ['user_' . $order->user_id],
            'contents' => ['en' => 'Your order #' . $order->id . ' is shipped!'],
        ]);
    });
    

2. Middleware for Authenticated Devices

  • Attach device IDs to authenticated users:
    // In Authenticate.php middleware
    public function handle($request, Closure $next)
    {
        if ($request->user()) {
            $player = new Player($service->getClient());
            $player->update($request->user()->device_id, [
                'tags' => ['authenticated' => 'true'],
            ]);
        }
        return $next($request);
    }
    

3. Queue Background Jobs

  • Offload notification sends to queues:
    use Illuminate\Support\Facades\Queue;
    
    Queue::push(new SendOneSignalNotification($data));
    
    Job Class:
    class SendOneSignalNotification implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle(OneSignalService $service)
        {
            $notification = new Notification($service->getClient());
            $notification->create($this->data);
        }
    }
    

4. API Resource Responses

  • Format OneSignal responses for Laravel APIs:
    public function getPlayers()
    {
        $player = new Player($service->getClient());
        $response = $player->all();
    
        return response()->json([
            'data' => $response->response->players,
            'meta' => ['count' => count($response->response->players)],
        ]);
    }
    

Integration Tips

1. Error Handling

  • Wrap SDK calls in try-catch blocks:
    try {
        $response = $player->create($deviceType, $data);
        if (!$response->status) {
            throw new \Exception("OneSignal error: " . $response->code);
        }
    } catch (\Exception $e) {
        \Log::error("OneSignal failed: " . $e->getMessage());
        // Retry or notify admins
    }
    

2. Configuration Management

  • Use Laravel’s config:
    // config/onesignal.php
    return [
        'auth_key' => env('ONESIGNAL_AUTH_KEY'),
        'app_id' => env('ONESIGNAL_APP_ID'),
        'rest_key' => env('ONESIGNAL_REST_KEY'),
        'default_segment' => 'All',
    ];
    
    Access via:
    config('onesignal.default_segment')
    

3. Testing

  • Mock the SDK in PHPUnit:
    $mock = Mockery::mock(OneSignal::class);
    $mock->shouldReceive('create')->andReturn((object) [
        'status' => true,
        'code' => 200,
        'response' => (object) ['id' => 123],
    ]);
    $this->app->instance(OneSignal::class, $mock);
    

4. Environment-Specific Configs

  • Use .env for different stages:
    # .env.staging
    ONESIGNAL_AUTH_KEY=staging_key
    ONESIGNAL_APP_ID=staging_app_id
    

Gotchas and Tips

Pitfalls

1. PHP Version Incompatibility

  • Issue: The SDK requires PHP 5.5+, but Laravel 10+ needs PHP 8.1+.
    • Fix: Use a compatibility layer like php-compatibility or fork the SDK to update dependencies.
    • Alternative: Replace Guzzle v6 with Laravel’s HttpClient (see "Tips" below).

2. Deprecated OneSignal API

  • Issue: OneSignal deprecated v1 API in 2022. The SDK may fail with v2 endpoints.
    • Fix: Check OneSignal’s API changelog and update endpoints manually or switch to Laravel’s HttpClient.

3. Rate Limiting

  • Issue: OneSignal throttles requests (e.g., 1000 requests/hour for free tier).
    • Fix: Implement exponential backoff in retries:
      use Illuminate\Support\Facades\Http;
      
      $response = Http::retry(3, 100)->post('...');
      

4. Device ID Management

  • Issue: Device IDs may change (e.g., browser cache clears, app reinstalls).
    • Fix: Store device IDs in your database and sync with OneSignal:
      $user->device_id = $player->create(...)->response->id;
      $user->save();
      

5. Timezone Handling

  • Issue: send_after timestamps must be in GMT.
    • Fix: Use Carbon to format timestamps:
      $sendAfter = now()->timezone('GMT')->toDateTimeString();
      

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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime