PHPackages                             sondt-1245/pusher-php-server - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. sondt-1245/pusher-php-server

ActiveLibrary[HTTP &amp; Networking](/categories/http)

sondt-1245/pusher-php-server
============================

Library for interacting with the Pusher REST API

v7.0.3(3y ago)048[1 PRs](https://github.com/sondt-1245/pusher-http-php/pulls)MITPHPPHP ^7.3|^8.0

Since Nov 18Pushed 3y agoCompare

[ Source](https://github.com/sondt-1245/pusher-http-php)[ Packagist](https://packagist.org/packages/sondt-1245/pusher-php-server)[ RSS](/packages/sondt-1245-pusher-php-server/feed)WikiDiscussions v7.0.2 Synced 4w ago

READMEChangelogDependencies (5)Versions (52)Used By (0)

Pusher Channels HTTP PHP Library
================================

[](#pusher-channels-http-php-library)

[![Tests](https://github.com/pusher/pusher-http-php/actions/workflows/test.yml/badge.svg)](https://github.com/pusher/pusher-http-php/actions/workflows/test.yml) [![Packagist Version](https://camo.githubusercontent.com/8f203d77e1267b26b201d6284dde9296d04d38253e887a1064c0d550414f8536/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7075736865722f7075736865722d7068702d736572766572)](https://packagist.org/packages/pusher/pusher-php-server) [![Packagist License](https://camo.githubusercontent.com/81ca376eb5fd3c6ae18478cacbc9e1597c6186bd4672db8d1d2b3b98d3b04b66/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7075736865722f7075736865722d7068702d736572766572)](https://packagist.org/packages/pusher/pusher-php-server) [![Packagist Downloads](https://camo.githubusercontent.com/95de78f520bbb9239da78238775ea103b4bcbd657288d99019b3dd34be73b42c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f7075736865722f7075736865722d7068702d736572766572)](https://packagist.org/packages/pusher/pusher-php-server)

PHP library for interacting with the Pusher Channels HTTP API.

Register at  and use the application credentials within your app as shown below.

Installation
------------

[](#installation)

You can get the Pusher Channels PHP library via a composer package called `pusher-php-server`. See

```
$ composer require pusher/pusher-php-server
```

Or add to `composer.json`:

```
"require": {
    "pusher/pusher-php-server": "^7.0"
}
```

then run `composer update`.

Supported platforms
-------------------

[](#supported-platforms)

- PHP - supports PHP versions 7.3, 7.4 and 8.0.
- Laravel - version 8.29 and above has built-in support for Pusher Channels as a [Broadcasting backend](https://laravel.com/docs/master/broadcasting).
- Other PHP frameworks - supported provided you are using a supported version of PHP.

Pusher Channels constructor
---------------------------

[](#pusher-channels-constructor)

Use the credentials from your Pusher Channels application to create a new `Pusher\Pusher` instance.

```
$app_id = 'YOUR_APP_ID';
$app_key = 'YOUR_APP_KEY';
$app_secret = 'YOUR_APP_SECRET';
$app_cluster = 'YOUR_APP_CLUSTER';

$pusher = new Pusher\Pusher($app_key, $app_secret, $app_id, ['cluster' => $app_cluster]);
```

The fourth parameter is an `$options` array. The additional options are:

- `scheme` - e.g. http or https
- `host` - the host e.g. api.pusherapp.com. No trailing forward slash
- `port` - the http port
- `path` - a prefix to append to all request paths. This is only useful if you are running the library against an endpoint you control yourself (e.g. a proxy that routes based on the path prefix).
- `timeout` - the HTTP timeout
- `useTLS` - quick option to use scheme of https and port 443.
- `cluster` - specify the cluster where the application is running from.
- `encryption_master_key` - a 32 char long key. This key, along with the channel name, are used to derive per-channel encryption keys. Per-channel keys are used encrypt event data on encrypted channels.

For example, by default calls will be made over HTTPS. To use plain HTTP you can set useTLS to false:

```
$options = [
  'cluster' => $app_cluster,
  'useTLS' => false
];
$pusher = new Pusher\Pusher($app_key, $app_secret, $app_id, $options);
```

Logging configuration
---------------------

[](#logging-configuration)

The recommended approach of logging is to use a [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)compliant logger implementing `Psr\Log\LoggerInterface`. The `Pusher` object implements `Psr\Log\LoggerAwareInterface`, meaning you call `setLogger(LoggerInterface $logger)` to set the logger instance.

```
// where $logger implements `LoggerInterface`

$pusher->setLogger($logger);
```

Custom Guzzle client
--------------------

[](#custom-guzzle-client)

This library uses Guzzle internally to make HTTP calls. You can pass your own Guzzle instance to the Pusher constructor:

```
$custom_client = new GuzzleHttp\Client();

$pusher = new Pusher\Pusher(
    $app_key,
    $app_secret,
    $app_id,
    [],
    $custom_client
);
```

This allows you to pass in your own middleware, see the tests for an [example](tests/acceptance/middlewareTest.php).

Publishing/Triggering events
----------------------------

[](#publishingtriggering-events)

To trigger an event on one or more channels use the `trigger` function.

### A single channel

[](#a-single-channel)

```
$pusher->trigger('my-channel', 'my_event', 'hello world');
```

### Multiple channels

[](#multiple-channels)

```
$pusher->trigger([ 'channel-1', 'channel-2' ], 'my_event', 'hello world');
```

### Batches

[](#batches)

It's also possible to send multiple events with a single API call (max 10 events per call on multi-tenant clusters):

```
$batch = [];
$batch[] = ['channel' => 'my-channel', 'name' => 'my_event', 'data' => ['hello' => 'world']];
$batch[] = ['channel' => 'my-channel', 'name' => 'my_event', 'data' => ['myname' => 'bob']];
$pusher->triggerBatch($batch);
```

### Asynchronous interface

[](#asynchronous-interface)

Both `trigger` and `triggerBatch` have asynchronous counterparts in `triggerAsync` and `triggerBatchAsync`. These functions return [Guzzle promises](https://github.com/guzzle/promises) which can be chained with `->then`:

```
$promise = $pusher->triggerAsync(['channel-1', 'channel-2'], 'my_event', 'hello world');

$promise->then(function($result) {
  // do something with $result
  return $result;
});

$final_result = $promise->wait();
```

### Arrays

[](#arrays)

Arrays are automatically converted to JSON format:

```
$array['name'] = 'joe';
$array['message_count'] = 23;

$pusher->trigger('my_channel', 'my_event', $array);
```

The output of this will be:

```
"{'name': 'joe', 'message_count': 23}"
```

### Socket id

[](#socket-id)

In order to avoid duplicates you can optionally [specify the sender's socket id](https://pusher.com/docs/channels/server_api/excluding-event-recipients)while triggering an event:

```
$pusher->trigger('my-channel', 'event', 'data', ['socket_id' => $socket_id]);
```

```
$batch = [];
$batch[] = ['channel' => 'my-channel', 'name' => 'my_event', 'data' => ['hello' => 'world'], ['socket_id' => $socket_id]];
$batch[] = ['channel' => 'my-channel', 'name' => 'my_event', 'data' => ['myname' => 'bob'], ['socket_id' => $socket_id]];
$pusher->triggerBatch($batch);
```

### Fetch channel info on publish \[[EXPERIMENTAL](https://pusher.com/docs/lab#experimental-program)\]

[](#fetch-channel-info-on-publish-experimental)

It is possible to request for attributes about the channels that were published to with the [`info` param](https://pusher.com/docs/channels/library_auth_reference/rest-api#request):

```
$result = $pusher->trigger('my-channel', 'my_event', 'hello world', ['info' => 'subscription_count']);
$subscription_count = $result->channels['my-channel']->subscription_count;
```

```
$batch = [];
$batch[] = ['channel' => 'my-channel', 'name' => 'my_event', 'data' => ['hello' => 'world'], 'info' => 'subscription_count'];
$batch[] = ['channel' => 'presence-my-channel', 'name' => 'my_event', 'data' => ['myname' => 'bob'], 'info' => 'user_count,subscription_count'];
$result = $pusher->triggerBatch($batch);

foreach ($result->batch as $i => $attributes) {
  echo "channel: {$batch[$i]['channel']}, name: {$batch[$i]['name']}";
  if (isset($attributes->subscription_count)) {
    echo ", subscription_count: {$attributes->subscription_count}";
  }
  if (isset($attributes->user_count)) {
    echo ", user_count: {$attributes->user_count}";
  }
  echo PHP_EOL;
}
```

### JSON format

[](#json-format)

If your data is already encoded in JSON format, you can avoid a second encoding step by setting the sixth argument true, like so:

```
$pusher->trigger('my-channel', 'event', 'data', [], true);
```

Authenticating Private channels
-------------------------------

[](#authenticating-private-channels)

To authorise your users to access private channels on Pusher, you can use the `socketAuth` function:

```
$pusher->socketAuth('private-my-channel','socket_id');
```

Authenticating Presence channels
--------------------------------

[](#authenticating-presence-channels)

Using presence channels is similar to private channels, but you can specify extra data to identify that particular user:

```
$pusher->presenceAuth('presence-my-channel','socket_id', 'user_id', 'user_info');
```

Webhooks
--------

[](#webhooks)

This library provides a way of verifying that webhooks you receive from Pusher are actually genuine webhooks from Pusher. It also provides a structure for storing them. A helper method called `webhook` enables this. Pass in the headers and body of the request, and it'll return a Webhook object with your verified events. If the library was unable to validate the signature, an exception is thrown instead.

```
$webhook = $pusher->webhook($request_headers, $request_body);
$number_of_events = count($webhook->get_events());
$time_received = $webhook->get_time_ms();
```

End to end encryption
---------------------

[](#end-to-end-encryption)

This library supports end to end encryption of your private channels. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them. You can enable this feature by following these steps:

1. You should first set up Private channels. This involves [creating an authentication endpoint on your server](https://pusher.com/docs/authenticating_users).
2. Next, generate your 32 byte master encryption key, base64 encode it and store it securely. This is secret and you should never share this with anyone. Not even Pusher.

    To generate an appropriate key from a good random source, you can use the `openssl` command:

    ```
    openssl rand -base64 32
    ```
3. Specify your master encryption key when creating your Pusher client:

    ```
    $pusher = new Pusher\Pusher(
        $app_key,
        $app_secret,
        $app_id,
        [
            'cluster' => $app_cluster,
            'encryption_master_key_base64' => ""
        ]
     );
    ```
4. Channels where you wish to use end to end encryption should be prefixed with `private-encrypted-`.
5. Subscribe to these channels in your client, and you're done! You can verify it is working by checking out the debug console on the [https://dashboard.pusher.com/](dashboard) and seeing the scrambled ciphertext.

**Important note: This will not encrypt messages on channels that are not prefixed by `private-encrypted-`.**

**Limitation**: you cannot trigger a single event on multiple channels in a call to `trigger`, e.g.

```
$data['name'] = 'joe';
$data['message_count'] = 23;

$pusher->trigger(['channel-1', 'private-encrypted-channel-2'], 'test_event', $data);
```

Rationale: the methods in this library map directly to individual Channels HTTP API requests. If we allowed triggering a single event on multiple channels (some encrypted, some unencrypted), then it would require two API requests: one where the event is encrypted to the encrypted channels, and one where the event is unencrypted for unencrypted channels.

### Presence example

[](#presence-example)

First set this variable in your JS app:

```
Pusher.channel_auth_endpoint = '/presenceAuth.php';
```

Next, create the following in presenceAuth.php:

```
