• Stars
    star
    1,355
  • Rank 33,350 (Top 0.7 %)
  • Language
    PHP
  • Created almost 12 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP library for interacting with the Pusher Channels HTTP API

Pusher Channels HTTP PHP Library

Tests Packagist Version Packagist License Packagist Downloads

PHP library for interacting with the Pusher Channels HTTP API.

Register at https://pusher.com and use the application credentials within your app as shown below.

Installation

You can get the Pusher Channels PHP library via a composer package called pusher-php-server. See https://packagist.org/packages/pusher/pusher-php-server

$ composer require pusher/pusher-php-server

Or add to composer.json:

"require": {
    "pusher/pusher-php-server": "^7.2"
}

then run composer update.

Supported platforms

  • PHP - supports PHP versions 7.3, 7.4, 8.0, and 8.1.
  • Laravel - version 8.29 and above has built-in support for Pusher Channels as a Broadcasting backend.
  • Other PHP frameworks - supported provided you are using a supported version of PHP.

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_base64 - 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

The recommended approach of logging is to use a PSR-3 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

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.

Publishing/Triggering events

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

A single channel

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

Multiple channels

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

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

Both trigger and triggerBatch have asynchronous counterparts in triggerAsync and triggerBatchAsync. These functions return 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 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

In order to avoid duplicates you can optionally specify the sender's socket id 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]

It is possible to request for attributes about the channels that were published to with the info param:

$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

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 users

To authenticate users on Pusher Channels on your application, you can use the authenticateUser function:

$pusher->authenticateUser('socket_id', 'user-id');

For more information see authenticating users.

Authorizing Private channels

To authorize your users to access private channels on Pusher, you can use the authorizeChannel function:

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

For more information see authorizing users.

Authorizing Presence channels

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

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

For more information see authorizing users.

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

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 authorization endpoint on your server.

  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' => "<your base64 encoded master key>"
        ]
     );
  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/ 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 a mixture of unencrypted and encrypted 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

First set the channel authorization endpoint in your JS app when creating the Pusher object:

var pusher = new Pusher("app_key",
  // ...
  channelAuthorization: {
    endpoint: "/presenceAuth.php",
  },
);

Next, create the following in presenceAuth.php:

<?php

header('Content-Type: application/json');

if (isset($_SESSION['user_id'])) {
  $stmt = $pdo->prepare("SELECT * FROM `users` WHERE id = :id");
  $stmt->bindValue(':id', $_SESSION['user_id'], PDO::PARAM_INT);
  $stmt->execute();
  $user = $stmt->fetch();
} else {
  die(json_encode('no-one is logged in'));
}

$pusher = new Pusher\Pusher($key, $secret, $app_id);
$presence_data = ['name' => $user['name']];

echo $pusher->authorizePresenceChannel($_POST['channel_name'], $_POST['socket_id'], $user['id'], $presence_data);

Note: this assumes that you store your users in a table called users and that those users have a name column. It also assumes that you have a login mechanism that stores the user_id of the logged in user in the session.

Application State Queries

Get information about a channel

$pusher->getChannelInfo($name);

It's also possible to get information about a channel from the Channels HTTP API.

$info = $pusher->getChannelInfo('channel-name');
$channel_occupied = $info->occupied;

For presence channels you can also query the number of distinct users currently subscribed to this channel (a single user may be subscribed many times, but will only count as one):

$info = $pusher->getChannelInfo('presence-channel-name', ['info' => 'user_count']);
$user_count = $info->user_count;

If you have enabled the ability to query the subscription_count (the number of connections currently subscribed to this channel) then you can query this value as follows:

$info = $pusher->getChannelInfo('presence-channel-name', ['info' => 'subscription_count']);
$subscription_count = $info->subscription_count;

Get a list of application channels

$pusher->getChannels();

It's also possible to get a list of channels for an application from the Channels HTTP API.

$result = $pusher->getChannels();
$channel_count = count($result->channels); // $channels is an Array

Get a filtered list of application channels

$pusher->getChannels(['filter_by_prefix' => 'some_filter']);

It's also possible to get a list of channels based on their name prefix. To do this you need to supply an $options parameter to the call. In the following example the call will return a list of all channels with a presence- prefix. This is idea for fetching a list of all presence channels.

$results = $pusher->getChannels(['filter_by_prefix' => 'presence-']);
$channel_count = count($result->channels); // $channels is an Array

This can also be achieved using the generic pusher->get function:

$pusher->get('/channels', ['filter_by_prefix' => 'presence-']);

Get a list of application channels with subscription counts

The HTTP API returning the channel list does not support returning the subscription count along with each channel. Instead, you can fetch this data by iterating over each channel and making another request. Be warned: this approach consumes (number of channels + 1) messages!

<?php
$subscription_counts = [];
foreach ($pusher->getChannels()->channels as $channel => $v) {
  $subscription_counts[$channel] =
    $pusher->getChannelInfo(
      $channel, ['info' => 'subscription_count']
    )->subscription_count;
}
var_dump($subscription_counts);

Get user information from a presence channel

$results = $pusher->getPresenceUsers('presence-channel-name');
$users_count = count($results->users); // $users is an Array

This can also be achieved using the generic pusher->get function:

$response = $pusher->get('/channels/presence-channel-name/users');

The $response is in the format:

Array (
	[body] => {"users":[{"id":"a_user_id"}]}
	[status] => 200
	[result] => Array (
		[users] => Array (
			[0] => Array (
				[id] => a_user_id
			),
			/* Additional users */
		)
	)
)

Generic get function

$pusher->get($path, $params);

Used to make GET queries against the Channels HTTP API. Handles authentication.

Response is an associative array with a result index. The contents of this index is dependent on the HTTP method that was called. However, a status property to allow the HTTP status code is always present and a result property will be set if the status code indicates a successful call to the API.

$response = $pusher->get('/channels');
$http_status_code = $response['status'];
$result = $response['result'];

Running the tests

Requires phpunit.

  • Run composer install
  • Go to the tests directory
  • Rename config.example.php and replace the values with valid Channels credentials or create environment variables.
  • Some tests require a client to be connected to the app you defined in the config; you can do this by opening https://dashboard.pusher.com/apps/<YOUR_TEST_APP_ID>/getting_started in the browser
  • From the root directory of the project, execute composer exec phpunit to run all the tests.

License

Copyright 2014, Pusher. Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php

Copyright 2010, Squeeks. Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-ruby

Ruby library for Pusher Channels HTTP API
Ruby
659
star
4

libPusher

An Objective-C interface to Pusher Channels
C
409
star
5

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
6

pusher-http-python

Pusher Channels HTTP API library for Python
Python
368
star
7

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
311
star
8

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
9

pusher-websocket-swift

Pusher Channels websocket library for Swift
Swift
267
star
10

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
11

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
12

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
13

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
14

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
112
star
15

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
16

pusher-http-dotnet

.NET library for interacting with the Pusher HTTP API
C#
109
star
17

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
108
star
18

pusher-websocket-dotnet

Pusher Channels Client Library for .NET
C#
107
star
19

faros

Faros is a CRD based GitOps controller
Go
100
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
89
star
22

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
23

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
67
star
24

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
25

backpusher

JavaScript
54
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
54
star
27

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
54
star
28

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

notify

Ruby
51
star
31

cli

A CLI for Pusher (beta)
Go
50
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
39
star
37

push-notifications-web

Beams Browser notifications
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher ✨
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

cide

Isolated test runner with Docker
Ruby
33
star
43

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
22
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
19
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

pusher-twilio-example

CSS
12
star
63

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
64

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
11
star
65

electron-desktop-starter-template

JavaScript
11
star
66

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

git-store

Go git abstraction for use in Kubernetes Controllers
Go
8
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

bridge-troll

A Troll that ensures files don't change
Go
5
star
87

navarchos

Node replacing controller
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
96

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

chatkit-android-public-demo

This will hold the demo app for chatkit android. Owner: @daniellevass
Kotlin
2
star