You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Pusher Beams推送Laravel通知、配置兴趣组及调试验证?

Pusher Beams 兴趣组配置与调试指南

一、后端指定兴趣组并在React中监听

后端配置步骤

  1. 存储用户的Beams设备ID
    先给users表添加beams_device_id字段(创建迁移文件),用于保存前端注册Beams后返回的设备ID:

    // 迁移文件示例
    Schema::table('users', function (Blueprint $table) {
        $table->string('beams_device_id')->nullable();
    });
    

    前端完成Beams注册后,将设备ID发送到后端接口,存入用户模型的对应字段。

  2. 订阅兴趣组
    借助Pusher Beams SDK让用户设备订阅指定兴趣组,可在控制器或模型方法中实现:

    use Pusher\PushNotifications\PushNotifications;
    
    // 示例:给指定用户订阅"news"兴趣组
    public function subscribeToInterest(User $user, string $interest)
    {
        if (!$user->beams_device_id) {
            throw new \Exception('用户未注册Beams设备');
        }
    
        $beamsClient = new PushNotifications([
            'instanceId' => config('services.pusher.beams_instance_id'),
            'secretKey' => config('services.pusher.beams_secret_key'),
        ]);
    
        // 为用户设备添加兴趣组订阅
        $beamsClient->addDeviceInterest($user->beams_device_id, $interest);
    }
    
  3. 给兴趣组推送通知
    若需主动给兴趣组发送通知,直接调用Beams的发布API即可:

    $beamsClient = new PushNotifications([
        'instanceId' => config('services.pusher.beams_instance_id'),
        'secretKey' => config('services.pusher.beams_secret_key'),
    ]);
    
    // 向"news"和"sports"兴趣组推送通知
    $response = $beamsClient->publishToInterests(
        ['news', 'sports'],
        [
            'web' => [
                'notification' => [
                    'title' => '最新资讯',
                    'body' => '兴趣组专属通知内容',
                    'deep_link' => '/news'
                ]
            ]
        ]
    );
    

React前端监听兴趣组

初始化Beams客户端并订阅目标兴趣组,同时监听通知接收事件:

import PusherPushNotifications from "@pusher/push-notifications-web";

// 初始化Beams客户端
const beamsClient = new PusherPushNotifications({
  instanceId: "你的Beams实例ID",
});

// 启动客户端并订阅兴趣组
beamsClient.start()
  .then(() => beamsClient.subscribe("news"))
  .then(() => console.log("成功订阅news兴趣组"))
  .catch(err => console.error("订阅失败:", err));

// 监听通知
beamsClient.onNotificationReceived = ({ notification }) => {
  console.log("收到兴趣组通知:", notification);
  // 可在此添加自定义通知展示逻辑,比如弹窗提示
};

二、使用Pusher Beams调试控制台验证通知

  1. 登录Pusher控制台,进入你的Beams实例页面。
  2. 打开Debug Console(调试控制台)选项卡,这里会展示所有通知的发送记录。
  3. 触发Laravel中的通知后,在控制台可查看:
    • 通知的整体发送状态(成功/失败)
    • 目标订阅设备的数量
    • 单个设备的送达详情(若失败会显示具体错误原因,比如设备未注册、兴趣组无订阅者等)
  4. 额外验证方式:
    • 查看Laravel日志文件(storage/logs/laravel.log),通知发送过程中的错误会在这里记录详细信息。
    • 在发送通知的代码中捕获返回结果,直接打印确认状态:
      $response = $beamsClient->publishToInterests(...);
      dd($response); // 打印响应数据,确认通知是否成功发布
      

内容的提问来源于stack exchange,提问作者Mohammed AL MahmoOd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:45:15