Files
YwxAppThink/addon/wxchat/worker/ChatEvent.php
T

109 lines
3.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
/**
* GatewayWorker Events 增强版
* 功能:登录认证 / 单群聊转发 / 心跳 / 离线消息 / 消息持久化 / ACK / 状态(输入/已读/撤回) / 关系消息
* 依赖:GatewayWorker 3.0+
*/
namespace addon\wxchat\worker;
use addon\wxchat\worker\enum\MsgFrame;
use GatewayWorker\Lib\Gateway;
/**
* ChatEvent 类
*
* @author ywxapp <admin@ywxapp.cn>
*/
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;
}
}