// +---------------------------------------------------------------------- /** * GatewayWorker Events 增强版 * 功能:登录认证 / 单群聊转发 / 心跳 / 离线消息 / 消息持久化 / ACK / 状态(输入/已读/撤回) / 关系消息 * 依赖:GatewayWorker 3.0+ */ namespace addon\wxchat\worker; use addon\wxchat\worker\enum\MsgFrame; use GatewayWorker\Lib\Gateway; /** * ChatEvent 类 * * @author ywxapp */ class ChatEvent { /** * 当 GatewayWorker 业务进程启动时触发(初始化 ThinkPHP 容器) */ public static function onWorkerStart($businessWorker) { self::initApp(); } /** * 当客户端连接时触发 */ public static function onConnect($client_id) { echo "client connected: $client_id\n"; } /** * 当客户端发来消息时触发 */ public static function onMessage($client_id, $msgJson) { self::initApp(); echo "Received message: [$client_id] $msgJson \n"; $message = Message::fromJson($msgJson); $header = $message->header; $payload = $message->payload; // 顶层帧类型路由(MsgFrame) switch ($header->type) { case MsgFrame::PING->value: case MsgFrame::PONG->value: handle\Heartbeat::handle($client_id, $header, $payload); break; case MsgFrame::CHAT->value: handle\ChatHandle::handle($client_id, $header, $payload); break; case MsgFrame::SYSTEM->value: handle\SystemHandle::handle($client_id, $header, $payload); break; case MsgFrame::RELATION->value: handle\RelationHandle::handle($client_id, $header, $payload); break; case MsgFrame::STATUS->value: handle\StatusHandle::handle($client_id, $header, $payload); break; default: MsgReply::sendError($client_id, '不支持的消息协议: ' . ($header->type ?? '')); break; } } /** * 当用户断开连接时触发:更新在线状态 */ public static function onClose($client_id) { echo "onClose:> [$client_id] \n"; $uid = Gateway::getUidByClientId($client_id); if ($uid) { try { self::initApp(); \ywxapp\model\MemberProfile::where('uid', $uid) ->update(['online_status' => 0, 'last_active_at' => time()]); } catch (\Throwable $e) { echo "onClose update failed: " . $e->getMessage() . "\n"; } } } /** * 初始化 ThinkPHP 应用(供模型 / Db 门面使用) */ public static function initApp() { static $app = null; if ($app === null) { $app = new \think\App(); $app->initialize(); } return $app; } }