修复:私有频道改用数字 ID,解决中文用户名导致 Pusher 频道名非法
错误原因:Pusher 频道名只允许 [a-zA-Z0-9_\-=@,.],
中文用户名(如「超级舞魅」)用于 private-user.{username} 导致
PusherException: Invalid channel name。
修复方案(改用数字 ID):
- FriendAdded/FriendRemoved 构造加 toUserId 参数
- broadcastOn() 改为 PrivateChannel('user.' . $toUserId)
- FriendController 传入 $target->id / $targetUser->id
- channels.php 鉴权改为 'user.{id}',核对 $user->id 数字相等
- frame.blade.php chatContext 加 userId
- scripts.blade.php Echo.private 改用 userId 订阅
This commit is contained in:
@@ -3,10 +3,8 @@
|
||||
/**
|
||||
* 文件功能:好友添加广播事件
|
||||
*
|
||||
* 当用户 A 添加用户 B 为好友时,向 B 的私有频道广播此事件,
|
||||
* B 的客户端收到后展示弹窗通知。
|
||||
* 携带 has_added_back 字段:若 B 已将 A 加为好友则为 true(双向好友),
|
||||
* 否则为 false,前端提示 B 可以点击回加。
|
||||
* 当用户 A 添加用户 B 为好友时,向 B 的私有频道广播此事件。
|
||||
* 频道名使用数字 ID(user.{id}),避免中文用户名导致 Pusher 频道名验证失败。
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
@@ -30,28 +28,27 @@ class FriendAdded implements ShouldBroadcastNow
|
||||
* 构造好友添加事件。
|
||||
*
|
||||
* @param string $fromUsername 发起添加的用户名(A)
|
||||
* @param string $toUsername 被添加的用户名(B,接收通知方)
|
||||
* @param string $toUsername 被添加的用户名(B,用于消息显示)
|
||||
* @param int $toUserId 被添加用户的数字 ID(用于私有频道,避免中文名非法)
|
||||
* @param bool $hasAddedBack B 是否已将 A 加为好友(互相添加=true)
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $fromUsername,
|
||||
public readonly string $toUsername,
|
||||
public readonly int $toUserId,
|
||||
public readonly bool $hasAddedBack = false,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 广播到被添加用户的私有频道,仅本人可见。
|
||||
* 广播到被添加用户的私有频道(用数字 ID 命名,避免中文频道名不合法)。
|
||||
*/
|
||||
public function broadcastOn(): Channel
|
||||
{
|
||||
return new PrivateChannel('user.'.$this->toUsername);
|
||||
return new PrivateChannel('user.'.$this->toUserId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定广播事件名称(短名),供前端 listen('.FriendAdded') 匹配。
|
||||
*
|
||||
* 默认广播名为全类名 App\Events\FriendAdded,
|
||||
* 指定短名后前端只需 .listen('.FriendAdded')。
|
||||
*/
|
||||
public function broadcastAs(): string
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user