~/docs
Resonate
Resonate
1.x 1.5.0, current
Resonate
Toggle sidebar
Resonate
webpatser/resonate 1.5.0

Resonate 1.x

Examples

Complete setups taken from the Resonate sources, from a Reverb swap to a custom plugin, signed webhooks, token auth and an upstream feed.

Every example below comes from the documentation and READMEs of the tagged releases. Class names, config keys and environment variables match the source.

1. Swap from Laravel Reverb

Replace the package, restart through the same signal and update the process entrypoint.

composer remove laravel/reverb
composer require webpatser/resonate
php artisan resonate:restart

Your config/reverb.php, Echo setup and laravel:reverb:restart cache key stay as they are. Point supervisor, systemd or Docker at php artisan resonate:start.

For zero-downtime deploys use the reload command, and raise the open file limit for the server process:

php artisan resonate:reload
ulimit -n 65536

Behind a reverse proxy, bind to loopback and name the proxy ranges:

REVERB_SERVER_HOST=127.0.0.1
REVERB_TRUSTED_PROXIES=10.0.0.0/8,fd00::/8

2. A custom plugin

A plugin that answers a custom app:whoami event, tags every connection with the time it opened, and broadcasts a server heartbeat every 30 seconds.

<?php
 
namespace App\Resonate;
 
use Webpatser\Resonate\Contracts\Connection;
use Webpatser\Resonate\Plugins\Contracts\ConnectionLifecycle;
use Webpatser\Resonate\Plugins\Contracts\MessageInterceptor;
use Webpatser\Resonate\Plugins\Contracts\ServerPlugin;
use Webpatser\Resonate\Plugins\Contracts\TickScheduler;
use Webpatser\Resonate\Plugins\MessageDisposition;
use Webpatser\Resonate\Plugins\PluginContext;
use Webpatser\Resonate\Protocols\Pusher\Channels\Channel;
 
class HeartbeatPlugin implements ConnectionLifecycle, MessageInterceptor, ServerPlugin, TickScheduler
{
private PluginContext $context;
 
private int $online = 0;
 
// Dependencies are injected by the container, so constructor injection works.
public function __construct(private readonly \Psr\Log\LoggerInterface $log)
{
//
}
 
public function boot(PluginContext $context): void
{
// Keep the context; open long-lived resources (DB/Redis pools) here.
$this->context = $context;
}
 
public function onMessage(Connection $from, array $event): MessageDisposition
{
// Only act on the event you own; everything else relays untouched.
if ($event['event'] !== 'app:whoami') {
return MessageDisposition::Relay;
}
 
$this->context->sendTo($from, 'app:whoami:result', [
'socket_id' => $from->id(),
'connected_at' => $from->state('hb.connected_at'),
]);
 
return MessageDisposition::Handled;
}
 
public function onOpen(Connection $connection): void
{
$this->online++;
 
// Per-connection state: namespace your keys to avoid plugin collisions.
$connection->setState('hb.connected_at', now()->toIso8601String());
}
 
public function onClose(Connection $connection): void
{
$this->online--;
}
 
public function onSubscribe(Connection $connection, Channel $channel): void
{
$this->log->info('subscribed', ['channel' => $channel->name()]);
}
 
public function onUnsubscribe(Connection $connection, Channel $channel): void
{
$this->log->info('unsubscribed', ['channel' => $channel->name()]);
}
 
public function ticks(): array
{
return [
[
'interval' => 30.0,
'callback' => function (): void {
// No connection here, so let the context resolve the app.
$this->context->broadcast(null, 'system', 'app:heartbeat', [
'online' => $this->online,
'at' => now()->toIso8601String(),
]);
},
],
];
}
}

Register it in config/reverb.php:

'servers' => [
'reverb' => [
// ...
'plugins' => [
App\Resonate\HeartbeatPlugin::class,
],
],
],

3. Signed webhooks for channel activity

The webhooks plugin reads occupancy from the roster, so install both and list the roster first. See Webhooks and Roster.

composer require webpatser/resonate-webhooks
php artisan vendor:publish --tag=resonate-roster-config
php artisan vendor:publish --tag=resonate-webhooks-config
RESONATE_ROSTER_TRACK=all
// config/reverb.php
'servers' => [
'reverb' => [
// ...
'plugins' => [
\Webpatser\ResonateRoster\RedisRosterPlugin::class, // first
\Webpatser\ResonateWebhooks\WebhookPlugin::class, // second
],
],
],
// config/resonate-webhooks.php
'endpoints' => [
[
'url' => env('RESONATE_WEBHOOK_URL'),
'app_id' => '*', // or a specific application id
'events' => [
'channel_occupied', 'channel_vacated',
'member_added', 'member_removed', 'client_event',
],
],
],

Verify the signature in the receiving app before you trust the body:

$expected = hash_hmac('sha256', $request->getContent(), config('reverb.apps.apps.0.secret'));
 
abort_unless(hash_equals($expected, $request->header('X-Pusher-Signature')), 403);

4. Token auth for mobile clients

Set the JWT settings in the environment:

RESONATE_TOKEN_AUTH_ALG=HS256
RESONATE_TOKEN_AUTH_SECRET=your-shared-jwt-secret

Register \Webpatser\ResonateTokenAuth\TokenAuthPlugin::class in plugins, then mint a token in your Laravel app (with firebase/php-jwt):

use Firebase\JWT\JWT;
 
return JWT::encode([
'iss' => config('app.url'),
'aud' => 'resonate',
'sub' => (string) $user->id,
'app_id' => config('reverb.apps.apps.0.app_id'),
'user_info' => ['name' => $user->name],
'channels' => ['presence-chat.*', 'private-user.'.$user->id],
'iat' => time(),
'exp' => time() + 300,
], config('resonate-token-auth.secret'), 'HS256');

The client sends the token in the subscribe payload:

{"event": "pusher:subscribe", "data": {"channel": "presence-chat.42", "token": "..."}}

5. An external feed into a channel and a queue

The upstream plugin holds a Socket.IO connection inside the server process and passes each message to a channel, a queued Laravel event, or both. See Upstream.

// config/resonate-upstream.php
'sources' => [
'prices' => [
'driver' => 'socketio',
'url' => 'https://stream.example.com',
'headers' => ['User-Agent' => 'example-app (+https://example.com)'],
'rooms' => ['ticker'],
'room_resolver' => null,
'events' => ['price'],
'publish' => ['channel' => 'private-upstream.prices', 'event' => 'upstream.message'],
'dispatch' => true,
'queue' => ['connection' => 'redis', 'name' => 'upstream'],
'reconnect' => ['min' => 5, 'max' => 20, 'reset_after' => 30, 'refused' => 600],
],
],

Authorize the channel in routes/channels.php:

Broadcast::channel('upstream.prices', fn (User $user): bool => $user->can('view-prices'));

Handle messages in a queue worker:

use Webpatser\ResonateUpstream\Events\UpstreamMessageReceived;
 
final class UpdatePrice
{
public function handle(UpstreamMessageReceived $message): void
{
if ($message->source !== 'prices' || ! is_array($message->payload)) {
return;
}
 
Price::query()->updateOrCreate(
['symbol' => $message->payload['symbol']],
['price' => $message->payload['price'], 'seen_at' => $message->receivedAt],
);
}
}

Run a full sync after every reconnect:

use Webpatser\ResonateUpstream\Events\UpstreamConnected;
 
final class ResyncPrices
{
public function handle(UpstreamConnected $connected): void
{
if ($connected->source === 'prices') {
SyncAllPrices::dispatch();
}
}
}