在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:pusher/pusher-http-php开源软件地址:https://github.com/pusher/pusher-http-php开源编程语言:PHP 100.0%开源软件介绍:Pusher Channels HTTP PHP LibraryPHP 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. InstallationYou can get the Pusher Channels PHP library via a composer package called $ composer require pusher/pusher-php-server Or add to "require": {
"pusher/pusher-php-server": "^7.0"
} then run Supported platforms
Pusher Channels constructorUse the credentials from your Pusher Channels application to create a new $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
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 configurationThe recommended approach of logging is to use a
PSR-3
compliant logger implementing // where $logger implements `LoggerInterface`
$pusher->setLogger($logger); Custom Guzzle clientThis 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 eventsTo trigger an event on one or more channels use the A single channel$pusher->trigger('my-channel', 'my_event', 'hello world'); Multiple channels$pusher->trigger([ 'channel-1', 'channel-2' ], 'my_event', 'hello world'); BatchesIt'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 interfaceBoth $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(); ArraysArrays 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 idIn 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); EXPERIMENTAL]Fetch channel info on publish [It is possible to request for attributes about the channels that were
published to with the
$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 formatIf 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 usersTo authenticate users on Pusher Channels on your application, you can use the $pusher->authenticateUser('socket_id', 'user-id'); For more information see authenticating users. Authorizing Private channelsTo authorize your users to access private channels on Pusher, you can use the
$pusher->authorizeChannel('private-my-channel','socket_id'); For more information see authorizing users. Authorizing Presence channelsUsing 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. WebhooksThis 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 = $pusher->webhook($request_headers, $request_body);
$number_of_events = count($webhook->get_events());
$time_received = $webhook->get_time_ms(); End to end encryptionThis 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:
Important note: This will not encrypt messages on channels that are not
prefixed by Limitation: you cannot trigger a single event on multiple channels in a
call to $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 exampleFirst 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 Application State QueriesGet 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 $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 $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('/channels', ['filter_by_prefix' => 'presence-']); Get a list of application channels with subscription countsThe 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 $response = $pusher->get('/channels/presence-channel-name/users'); The 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 Response is an associative array with a $response = $pusher->get('/channels');
$http_status_code = $response['status'];
$result = $response['result']; |