在php中为推送器创建私有通道身份验证流

问题描述 投票:0回答:1

我想使用pusher PHP / JS API实现私人消息聊天。我需要一些帮助来设置专用频道和使用php的身份验证端点,从文档中尚不清楚是否存在管理专用频道的用户身份验证的默认方法。我用谷歌搜索了一些示例,但是我没有使用laravel,所以我不能应用它们。任何建议将不胜感激。

JS

Pusher.logToConsole = true;

          var pusher = new Pusher('12xxxxxx', {
            cluster: 'us',
            forceTLS: true
          });

          var channel = pusher.subscribe('private-encrypted-test-channel');
          channel.bind('message-event', function(data) {
            alert(JSON.stringify(data));
          });

          channel.bind('pusher:subscription_succeeded', function(members) {
            console.log(members);
            console.log('successfully subscribed!');
          });

PHP

require_once __DIR__.'/vendor/autoload.php';

$options = array(
  'cluster' => 'eu',
  'useTLS' => true
);
$pusher = new Pusher\Pusher(
  '12xxxxx',
  '2xxxxxx',
  '8xxxxxx',
  $options
);

$data['message'] = 'hello world';
$pusher->trigger('private-encrypted-test-channel', 'message-event', $data);

什么是在php中验证用户的正确方法,以后又在js中为推送者API验证用户的正确方法?

php pusher pusher-js
1个回答
0
投票

您将需要创建另一个PHP文件(例如pusher_auth.php)来执行身份验证。使用此代码作为起点(根据您的代码和Pusher的WordPress文档进行了修改,因为引擎盖下的WordPress只是PHP的各个层):

require_once __DIR__.'/vendor/autoload.php';

$options = array(
  'cluster' => 'eu',
  'useTLS' => true
);

$pusher = new Pusher\Pusher(
  '12xxxxx',
  '2xxxxxx',
  '8xxxxxx',
  $options
);

// You need to define this function for your application, but for testing purposes, it always returns true

function user_is_authenticated(){
    // Insert your logic here
    return true;
}

if ( user_is_authenticated() )
{
  echo $pusher->socket_auth($_POST['channel_name'], $_POST['socket_id']);
}
else
{
  header('', true, 403);
  echo "Forbidden";
}

现在像这样修改您的JS代码以添加authEndpoint参数(更改名称和相对路径以匹配您的PHP身份验证文件)

var pusher = new Pusher('12xxxxxx', {
    cluster: 'us',
    authEndpoint: '/pusher_auth.php',
    forceTLS: true
});
© www.soinside.com 2019 - 2024. All rights reserved.