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

Pusher Php Server Laravel Package

pusher/pusher-php-server

PHP server library for Pusher Channels HTTP API. Send events, trigger broadcasts, authenticate private/presence channels, and manage webhooks/requests from your PHP app. Supports PHP 7.3–8.4 and integrates with Laravel broadcasting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require pusher/pusher-php-server
    

    Add to composer.json if preferred:

    "require": {
        "pusher/pusher-php-server": "^7.2"
    }
    
  2. Initialize Pusher Client:

    use Pusher\Pusher;
    
    $pusher = new Pusher(
        env('PUSHER_APP_KEY'),
        env('PUSHER_APP_SECRET'),
        env('PUSHER_APP_ID'),
        ['cluster' => env('PUSHER_APP_CLUSTER')]
    );
    
  3. First Use Case: Trigger an event to a channel:

    $pusher->trigger('notifications', 'new-message', ['content' => 'Hello World']);
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Event Triggering:

    • Single Channel:
      $pusher->trigger('channel-name', 'event-name', ['data' => 'value']);
      
    • Multiple Channels:
      $pusher->trigger(['channel-1', 'channel-2'], 'event-name', ['data' => 'value']);
      
    • Batched Events (max 10 events per call):
      $batch = [
          ['channel' => 'channel-1', 'name' => 'event-1', 'data' => ['key' => 'value']],
          ['channel' => 'channel-2', 'name' => 'event-2', 'data' => ['key' => 'value']],
      ];
      $pusher->triggerBatch($batch);
      
  2. Authentication:

    • Private Channels:
      $pusher->authorizeChannel('private-channel', $socketId);
      
    • Presence Channels:
      $pusher->authorizePresenceChannel('presence-channel', $socketId, $userId, ['user_data']);
      
    • User Authentication:
      $pusher->authenticateUser($socketId, $userId);
      
  3. Channel Management:

    • Fetch Channel Info:
      $info = $pusher->getChannelInfo('channel-name', ['info' => 'subscription_count,user_count']);
      
    • List Channels:
      $channels = $pusher->getChannels(['filter_by_prefix' => 'private-']);
      
  4. Webhooks:

    • Verify and parse incoming webhooks:
      $webhook = $pusher->webhook($requestHeaders, $requestBody);
      foreach ($webhook->get_events() as $event) {
          // Process event
      }
      
  5. Asynchronous Operations:

    • Use triggerAsync/triggerBatchAsync for non-blocking calls:
      $promise = $pusher->triggerAsync('channel', 'event', ['data']);
      $promise->then(function($result) { /* Handle result */ });
      

Laravel Integration Tips

  • Broadcasting Driver: Configure Laravel’s broadcasting to use Pusher:
    // config/broadcasting.php
    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => ['cluster' => env('PUSHER_APP_CLUSTER')],
    ],
    
  • Events: Extend Laravel’s Broadcasts trait to events:
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Queue\SerializesModels;
    
    class NewMessage implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public function broadcastOn()
        {
            return new Channel('notifications');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Encryption Limitations:

    • Mixing encrypted (private-encrypted-) and unencrypted channels in a single trigger call fails. Use separate calls or batches.
    • Ensure the encryption_master_key_base64 is 32 bytes (base64-encoded). Generate it securely:
      openssl rand -base64 32
      
  2. Async Operations:

    • triggerAsync returns a Guzzle Promise. Always handle it with .then() or .wait() to avoid silent failures.
    • Example of proper async handling:
      $pusher->triggerAsync('channel', 'event', ['data'])
          ->then(function($result) {
              // Success
          })
          ->otherwise(function($error) {
              // Error handling
          });
      
  3. Webhook Validation:

    • Always validate webhook signatures. The library throws an exception if validation fails:
      try {
          $webhook = $pusher->webhook($headers, $body);
      } catch (\Pusher\Exceptions\WebhookException $e) {
          // Handle invalid signature
      }
      
  4. Rate Limiting:

    • Pusher enforces rate limits. Batch events to reduce API calls:
      // Instead of:
      $pusher->trigger('channel', 'event1', ['data']);
      $pusher->trigger('channel', 'event2', ['data']);
      // Use:
      $pusher->triggerBatch([
          ['channel' => 'channel', 'name' => 'event1', 'data' => ['data']],
          ['channel' => 'channel', 'name' => 'event2', 'data' => ['data']],
      ]);
      
  5. Socket ID Handling:

    • Omitting socket_id in trigger sends events to all subscribers. Include it to exclude the sender:
      $pusher->trigger('channel', 'event', ['data'], ['socket_id' => $socketId]);
      
  6. Cluster Configuration:

    • Always specify the cluster in options (e.g., 'cluster' => 'mt1'). Defaults to us2 if omitted, which may cause misrouting.

Debugging Tips

  1. Logging:

    • Attach a PSR-3 logger (e.g., Monolog) to debug HTTP requests:
      $logger = new Monolog\Logger('pusher');
      $pusher->setLogger($logger);
      
    • Log level: Set to DEBUG for verbose output.
  2. HTTP Errors:

    • Check Guzzle’s underlying HTTP client for errors. Wrap calls in try-catch:
      try {
          $pusher->trigger('channel', 'event', ['data']);
      } catch (\Pusher\Exceptions\PusherException $e) {
          \Log::error('Pusher error: ' . $e->getMessage());
      }
      
  3. Channel Info Quirks:

    • getChannelInfo may return null for non-existent channels. Always check:
      $info = $pusher->getChannelInfo('nonexistent-channel');
      if (!$info) {
          // Handle error
      }
      
  4. Environment Variables:

    • Use Laravel’s .env or a similar system for credentials. Never hardcode:
      PUSHER_APP_KEY=your_key
      PUSHER_APP_SECRET=your_secret
      PUSHER_APP_ID=your_app_id
      PUSHER_APP_CLUSTER=your_cluster
      

Extension Points

  1. Custom Guzzle Client:

    • Inject middleware (e.g., retry logic) via a custom Guzzle client:
      $client = new GuzzleHttp\Client([
          'timeout' => 10,
          'headers' => ['User-Agent' => 'MyApp/1.0'],
      ]);
      $pusher = new Pusher($key, $secret, $appId, [], $client);
      
  2. Event Data Transformation:

    • Pre-process data before triggering:
      $data = ['original' => 'data'];
      $processedData = json_encode($data); // Or any transformation
      $pusher->trigger('channel', 'event', $processedData, [], true); // true = already JSON
      
  3. Presence Channel Data:

    • Customize presence channel data dynamically:
      $userData = ['name' => auth()->user()->name, 'role' => auth()->user()->role];
      $p
      
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.
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core