liufumingren e8605149c0 初始化
2026-08-06 17:04:35 +08:00

1288 lines
48 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
namespace app\index\controller\qiwe;
use \app\common\controller\Frontend;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
class Index extends Frontend
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
protected $layout = '';
private $redis;
private $guid;
private $roomModel;
private $logModel;
private $contactModel;
private $query;
public function _initialize()
{
parent::_initialize();
// Redis初始化
$this->redis = new \Redis();
$this->redis->connect('127.0.0.1', 6379);
$this->redis->auth('qwe2019@');
$this->redis->select(12);
// 获取配置
$this->tokenId = Config::get("site.tokenId");
$this->guid = Config::get("site.guid");
$options = ["tokenId" => $this->tokenId];
// 模型初始化
$this->roomModel = new \app\common\model\qiwe\Rooms();
$this->logModel = new \app\common\model\qiwe\chat\Log();
$this->contactModel = new \app\common\model\qiwe\Contacts();
$this->query = new \app\index\library\qiwe\Query($options);
}
/**
* 统一接收消息事件
*/
public function onMessage()
{
// 获取原始请求内容
$rawInput = file_get_contents('php://input');
// 记录原始请求(调试用)
\think\Log::error('原始请求: ' . $rawInput);
// 解析JSON数据
$postData = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$postData = $this->request->post(); // 降级处理
}
// 记录日志
\think\Log::error('接收到消息: ' . json_encode($postData, JSON_UNESCAPED_UNICODE));
// 同步处理(如果需要实时处理)
try {
$this->processMessages($postData);
} catch (\Exception $e) {
\think\Log::error('消息处理失败: ' . $e->getMessage());
}
// 返回成功响应(企业微信要求)
return response('', 200);
}
/**
* 消息处理 - 从队列中批量获取并发送,定时任务
*/
public function MessageHandleSend(){
$this->redis->select(2);
for($i=0;$i<5;$i++){
$message = $this->redis->rpop("QiweMessage");
if($message){
\think\Log::error("有消费信息:".$message);
$message = json_decode($message,true);
try {
//成品消息,直接调用发送
\think\Log::error("调用发送信息:");
$this->sendMessages(["msgs"=>[$message]], $message['receiver_name'] ?? "");
} catch (\Exception $e) {
\think\Log::error('消息处理失败: ' . $e->getMessage());
}
}else{
break;
}
}
}
/**
* 批量处理消息
* @param array $postData
*/
private function processMessages($postData)
{
if (empty($postData) || empty($postData['data']) || !is_array($postData['data'])) {
return;
}
Db::startTrans();
try {
foreach ($postData['data'] as $message) {
$this->processSingleMessage($message, $postData);
}
Db::commit();
} catch (\Exception $e) {
Db::rollback();
\think\Log::error('消息处理事务失败: ' . $e->getMessage());
}
}
/**
* 处理单条消息
* @param array $message
* @param array $parentData
*/
private function processSingleMessage($message, $parentData)
{
// 准备基础数据
$logData = $this->prepareBaseData($message, $parentData);
// 根据cmd处理不同的消息类型
switch ($logData['cmd']) {
case 11016: // 账号状态变化消息
$this->processAccountStatusMessage($logData, $message);
break;
case 20000: // API异步消息
$this->processApiAsyncMessage($logData, $message);
break;
case 15000: // 普通消息
$this->processNormalMessage($logData, $message);
break;
case 15500: // 系统消息
$this->processSystemMessage($logData, $message);
break;
default:
\think\Log::warning('未知消息类型: cmd=' . ($logData['cmd'] ?? 'unknown'));
break;
}
\think\Log::error('检查日志前: ');
// 检查是否已存在(防止重复)
//处理回复信息
$backMessage = $logData['back_content_json'] ?? null;
$backMessage = json_decode($backMessage, true);
if($backMessage){
$this->sendMessages($backMessage, $logData['contact_info']['nickname'] ?? $logData['contact_info']['real_name']?? "");
}
$exists = $this->logModel
->where('msg_unique_identifier', $logData['msg_unique_identifier'])
->find();
\think\Log::error('检查日志: ' . json_encode($exists));
//插入前格式化数据
$logData['contact_info'] = is_array($logData['contact_info']) ? json_encode($logData['contact_info'], JSON_UNESCAPED_UNICODE) : "{}";
$logData['room_info'] = is_array($logData['room_info']) ? json_encode($logData['room_info'], JSON_UNESCAPED_UNICODE) : "{}";
if ($exists) {
\think\Log::error('更新: ' . json_encode($exists));
// 更新
$logData['id'] = $exists['id'];
$this->logModel->isUpdate(true)->save($logData);
\think\Log::error('消息已更新: ' . $logData['msg_unique_identifier']);
} else {
\think\Log::error('插入: ');
// 插入
$this->logModel->isUpdate(false)->save($logData);
\think\Log::error('消息已保存: ' . $logData['msg_unique_identifier']);
}
}
/**
* 准备基础数据
* @param array $message
* @param array $parentData
* @return array
*/
private function prepareBaseData($message, $parentData)
{
$msgData = $message['msgData'] ?? [];
return [
// 基础字段
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
// 消息标识字段
'msg_unique_identifier' => $message['msgUniqueIdentifier'] ?? $message['msg_unique_identifier'] ?? '',
'request_id' => $message['requestId'] ?? $message['request_id'] ?? null,
'seq' => $message['seq'] ?? null,
'timestamp' => $message['timestamp'] ?? time(),
// 账号相关字段
'guid' => $message['guid'] ?? $this->guid,
'user_id' => $message['userId'] ?? $message['user_id'] ?? null,
'tenant_id' => $message['TenantId'] ?? $message['tenant_id'] ?? 0,
// 消息分类字段
'cmd' => $message['cmd'] ?? 0,
'msg_type' => $message['msgType'] ?? $message['msg_type'] ?? 0,
'msg_server_id' => $message['msgServerId'] ?? $message['msg_server_id'] ?? 0,
'sender_id' => $message['senderId'] ?? $message['sender_id'] ?? null,
'receiver_id' => $message['receiverId'] ?? $message['receiver_id'] ?? null,
// 会话相关字段
'from_room_id' => $message['fromRoomId'] ?? $message['from_room_id'] ?? null,
'is_room_notice' => $message['isRoomNotice'] ?? $message['is_room_notice'] ?? 0,
'sender_name' => $message['senderName'] ?? $message['sender_name'] ?? null,
// 业务状态字段
'status_code' => $msgData['code'] ?? null,
'status_desc' => $msgData['msg'] ?? null,
'qr_status' => $msgData['status'] ?? null,
// 系统消息字段
'base64_raw_data' => $msgData['base64RawData'] ?? $message['base64RawData'] ?? null,
'custom_param' => $message['customParam'] ?? $message['custom_param'] ?? null,
// 服务器维护标记
'server_reboot' => isset($msgData['serverReboot']) ? (int)$msgData['serverReboot'] : 0,
//联系人相关
'contact_info' => null, //后续处理时补充
'room_info' => null, //后续处理时补充
//返回内容json
'back_content_json' => null, //后续处理时补充
];
}
/**
* 处理账号状态消息
* @param array &$logData
* @param array $message
*/
private function processAccountStatusMessage(&$logData, $message)
{
$msgData = $message['msgData'] ?? [];
$logData['status_code'] = $msgData['code'] ?? null;
$logData['status_desc'] = $msgData['msg'] ?? null;
$logData['qr_status'] = $msgData['status'] ?? null;
// 特殊处理:如果是登录成功,可能需要更新群列表
if ($msgData['code'] == 11001) {
$this->handleLoginSuccess();
}
}
/**
* 处理登录成功
*/
private function handleLoginSuccess()
{
try {
// 异步触发群列表获取
$this->redis->lpush("qiweTask", json_encode([
'type' => 'sync_rooms',
'guid' => $this->guid,
'time' => time()
]));
} catch (\Exception $e) {
\think\Log::error('触发群同步失败: ' . $e->getMessage());
}
}
/**
* 处理API异步消息
* @param array &$logData
* @param array $message
*/
private function processApiAsyncMessage(&$logData, $message)
{
$msgData = $message['msgData'] ?? [];
$logData['cloud_url'] = $msgData['cloudUrl'] ?? null;
}
/**
* 处理普通消息
* @param array &$logData
* @param array $message
*/
private function processNormalMessage(&$logData, $message)
{
\think\Log::error('logdata: ' . json_encode($logData));
$msgData = $message['msgData'] ?? [];
// 群信息挂载:缓存 -> DB -> 远程同步 -> DB 回查
if (!empty($logData['from_room_id'])) {
\think\Log::error('判断是群: ');
$logData['room_info'] = $this->getRoomInfoForMessage($logData['from_room_id']);
}
\think\Log::error('自动处理群完成: ');
\think\Log::error('自动处理成员开始: ');
// 成员信息挂载:缓存 -> DB -> 远程同步 -> DB 回查
if (!empty($logData['sender_id'])) {
$logData['contact_info'] = $this->getContactInfoForMessage($logData['sender_id']);
}
// 文本消息
if (in_array($logData['msg_type'], [0, 2])) {
$logData['content'] = $msgData['content'] ?? null;
$logData['at_list'] = isset($msgData['atList']) ? json_encode($msgData['atList'], JSON_UNESCAPED_UNICODE) : null;
if($msgData['content']=="更新" && $logData["from_room_id"]){
$this->batchGetRoomDetail($logData["from_room_id"]);
}else if($logData["from_room_id"]){ //群文字信息,做业务处理
$ChatCon = new \app\index\controller\wms\Chat;
$result = $ChatCon->qiweOnMessage($logData,$this->tokenId);
$logData["back_content_json"] = json_encode($result, JSON_UNESCAPED_UNICODE);
\think\Log::error('业务处理结果: '.json_encode($result));
}
}
// 图片消息 (企微14, 个微101)
if (in_array($logData['msg_type'], [14, 101])) {
$this->processImageMessage($logData, $msgData);
}
// 视频消息 (企微23, 个微103)
if (in_array($logData['msg_type'], [23, 103])) {
$this->processVideoMessage($logData, $msgData);
}
// 文件消息 (企微15, 个微102)
if (in_array($logData['msg_type'], [15, 102])) {
$this->processFileMessage($logData, $msgData);
}
// 位置消息
if ($logData['msg_type'] == 6) {
$this->processLocationMessage($logData, $msgData);
}
// 链接消息
if ($logData['msg_type'] == 13) {
$this->processLinkMessage($logData, $msgData);
}
// 名片消息
if ($logData['msg_type'] == 41) {
$this->processBusinessCardMessage($logData, $msgData);
}
// 红包消息
if ($logData['msg_type'] == 26) {
$this->processRedPacketMessage($logData, $msgData);
}
// 语音消息
if ($logData['msg_type'] == 16) {
$this->processVoiceMessage($logData, $msgData);
}
// 小程序消息
if ($logData['msg_type'] == 78) {
$this->processMiniProgramMessage($logData, $msgData);
}
// 图文混合消息
if ($logData['msg_type'] == 123 && isset($message['msgData']) && is_array($message['msgData'])) {
$logData['mixed_data'] = json_encode($message['msgData'], JSON_UNESCAPED_UNICODE);
}
// 视频号消息
if ($logData['msg_type'] == 141) {
$this->processVideoChannelMessage($logData, $msgData);
}
// 消息已读/未读通知
if (in_array($logData['msg_type'], [2001, 2005])) {
$logData['content'] = $logData['msg_type'] == 2001 ? '消息已读' : '消息未读';
}
\think\Log::error('结果处理结束: '.json_encode($logData));
}
/**
* 取群信息并确保本次消息可用
*/
private function getRoomInfoForMessage($roomId)
{
$cacheKey = "room:{$roomId}";
$roomInfo = $this->redis->get($cacheKey);
if ($roomInfo) {
$decoded = json_decode($roomInfo, true);
if (is_array($decoded)) {
return $decoded;
}
}
\think\Log::error('缓存无记录: ');
$roomModel = $this->roomModel->where(['room_id' => $roomId])->find();
if (!$roomModel) {
\think\Log::error('数据库无记录: ');
$this->batchGetRoomDetail($roomId);
$roomModel = $this->roomModel->where(['room_id' => $roomId])->find();
} else {
\think\Log::error('数据库有记录: ');
}
if (!$roomModel) {
return null;
}
$roomData = is_array($roomModel) ? $roomModel : $roomModel->toArray();
$this->redis->set($cacheKey, json_encode($roomData, JSON_UNESCAPED_UNICODE), ['EX' => 300]);
return $roomData;
}
/**
* 取联系人信息并确保本次消息可用
*/
private function getContactInfoForMessage($userId)
{
$cacheKey = "contact:{$userId}";
$contactInfo = $this->redis->get($cacheKey);
if ($contactInfo) {
\think\Log::error('缓存有记录: '.json_encode($contactInfo));
$decoded = json_decode($contactInfo, true);
if (is_array($decoded)) {
return $decoded;
}
}
\think\Log::error('缓存无记录: ');
$contactModel = $this->contactModel->where(['user_id' => $userId])->find();
if (!$contactModel) {
\think\Log::error('数据库无记录: ');
$this->batchGetUserinfo([strval($userId)]);
$contactModel = $this->contactModel->where(['user_id' => $userId])->find();
\think\Log::error('数据库记录: '.json_encode($contactModel));
} else {
\think\Log::error('数据库有记录: '.json_encode($contactModel));
}
if (!$contactModel) {
return null;
}
$contactData = is_array($contactModel) ? $contactModel : $contactModel->toArray();
$this->redis->set($cacheKey, json_encode($contactData, JSON_UNESCAPED_UNICODE), ['EX' => 300]);
return $contactData;
}
/**
* 企微获取可下载的文件 - 返回cloudUrl
* @param string $fileAesKey 文件加密密钥
* @param string $fileId 文件ID
* @param int $fileSize 文件大小
* @param int $fileType 文件类型: 1-大图, 2-小图, 3-缩略图, 4-视频, 5-文件/语音
* @return string|false
*/
private function wxWorkDownload($fileAesKey, $fileId, $fileSize, $fileType)
{
$result = $this->query->query("wxWorkDownload", [$this->guid, $fileAesKey, $fileId, $fileSize, $fileType]);
$result = json_decode($result, true);
\think\Log::error('拉取图片返回的结果: ' . json_encode($result));
if ($result && $result["code"] == 0 && !empty($result["data"]["cloudUrl"])) {
return $result["data"]["cloudUrl"];
}
\think\Log::error('企业微信下载失败: ' . json_encode($result));
return false;
}
/**
* 个微获取可下载的文件 - 返回cloudUrl
* @param string $fileAesKey 文件加密密钥
* @param string $fileId 文件ID
* @param int $fileSize 文件大小
* @param int $fileType 文件类型: 1-大图, 2-小图, 3-缩略图, 4-视频, 5-文件/语音
* @return string|false
*/
private function wxDownload($fileAesKey,$fileAuthKey,$fileSize,$fileType,$fileUrl){
$result = $this->query->query("wxDownload", [$this->guid, $fileAesKey,$fileAuthKey,$fileSize,$fileType,$fileUrl]);
$result = json_decode($result, true);
\think\Log::error('拉取图片返回的结果: ' . json_encode($result)."\n\n\n\n");
if ($result && $result["code"] == 0 && !empty($result["data"]["cloudUrl"])) {
return $result["data"]["cloudUrl"];
}
\think\Log::error('企业微信下载失败: ' . json_encode($result));
return false;
}
/**
* 处理图片消息 - 统一使用URL下载
*/
private function processImageMessage(&$logData, $msgData)
{
\think\Log::error('开始处理图片消息: ' . json_encode($msgData));
$logData['file_id'] = $msgData['fileId'] ?? $msgData['file_id'] ?? null;
$logData['file_aeskey'] = $msgData['fileAesKey'] ?? $msgData['file_aeskey'] ?? null;
$logData['file_md5'] = $msgData['fileMd5'] ?? $msgData['file_md5'] ?? null;
$logData['file_name'] = $msgData['fileName'] ?? $msgData['file_name'] ?? null;
$logData['file_size'] = $msgData['fileSize'] ?? $msgData['file_size'] ?? null;
$logData['image_has_hd'] = isset($msgData['imageHasHd']) ? (int)$msgData['imageHasHd'] : null;
// 个微图片特有字段
if ($logData['msg_type'] == 101) {
$logData['file_http_url'] = $msgData['fileBigHttpUrl'] ?? null;
$logData['file_authkey'] = $msgData['fileAuthKey'] ?? $msgData['file_authkey'] ?? null;
}
// 初始化图片URL数组
$imageUrls = [];
$downloadTasks = [];
// 根据消息类型处理
switch ($logData['msg_type']) {
case 101: // 个微图片
\think\Log::error('处理个微图片1');
$this->processPersonalImage($logData, $msgData, $imageUrls, $downloadTasks);
//\think\Log::error('处理个微图片2',$logData, $msgData, $imageUrls, $downloadTasks);
break;
case 14: // 企微图片
\think\Log::error('处理企微图片');
$this->processWorkImage($logData, $msgData, $imageUrls, $downloadTasks);
break;
case 29: // 企微GIF
\think\Log::error('处理企微GIF图片');
case 104: // 个微GIF
\think\Log::error('处理GIF图片');
$this->processGifImage($logData, $msgData, $imageUrls, $downloadTasks);
break;
}
\think\Log::error('获取到的图片链接: ' . json_encode($imageUrls));
// 保存图片URL信息
if (!empty($imageUrls)) {
$logData['image_urls'] = json_encode($imageUrls, JSON_UNESCAPED_UNICODE);
}
// 加入下载队列
if (!empty($downloadTasks) && !empty($logData['msg_unique_identifier'])) {
$this->addToDownloadQueue($logData['msg_unique_identifier'], $downloadTasks);
}
}
/**
* 添加到下载队列
*/
private function addToDownloadQueue($msgId, $tasks)
{
if (empty($msgId) || empty($tasks)) {
return;
}
$this->redis->lpush("qiweImageDownload", json_encode([
'msg_id' => $msgId,
'tasks' => $tasks,
'time' => time()
]));
}
/**
* 处理个人微信图片 - 使用wxDownload获取cloudUrl
*/
private function processPersonalImage(&$logData, $msgData, &$imageUrls, &$downloadTasks)
{
\think\Log::error('执行了processPersonalImage1: '.json_encode($logData));
if (empty($logData['file_aeskey']) || empty($logData['file_authkey'])) {
\think\Log::error('缺少参数退出: ');
return;
}
\think\Log::error('判断入参完成'.json_encode($logData));
// 根据image_has_hd决定下载类型
// 1: 大图, 2: 小图
$hdType = ($logData['image_has_hd'] == 1) ? 1 : 2;
\think\Log::error('开始获取URL'.json_encode($hdType));
// 原图
if (!empty($logData['file_http_url'])) {
// 先保存原始URL
$imageUrls['original'] = [
'original_url' => $logData['file_http_url'],
'size' => $logData['file_size'],
'md5' => $logData['file_md5'],
'source' => 'personal',
'has_hd' => $logData['image_has_hd']
];
\think\Log::error('请求接口'.json_encode($logData));
// 通过接口获取cloudUrl
$cloudUrl = $this->wxDownload(
$logData['file_aeskey'],
$logData['file_authkey'],
$logData['file_size'],
$hdType,
$logData['file_http_url']
);
\think\Log::error('返回结果'.json_encode($cloudUrl));
if ($cloudUrl) {
$imageUrls['original']['cloud_url'] = $cloudUrl;
$downloadTasks['original'] = [
'url' => $cloudUrl,
'md5' => $logData['file_md5'],
'ext' => $this->getImageExt($cloudUrl),
'source' => 'personal'
];
} else {
// 获取失败,记录任务稍后重试
$downloadTasks['original'] = [
'type' => 'personal_retry',
'file_aeskey' => $logData['file_aeskey'],
'file_authkey' => $logData['file_authkey'],
'file_size' => $logData['file_size'],
'file_md5' => $logData['file_md5'],
'file_url' => $logData['file_http_url'],
'download_type' => $hdType,
'retry_count' => 0
];
}
\think\Log::error('请求接口完成'.json_encode($logData));
}
}
/**
* 获取图片扩展名
*/
private function getImageExt($url)
{
// 从URL中提取扩展名
$path = parse_url($url, PHP_URL_PATH);
$ext = pathinfo($path, PATHINFO_EXTENSION);
if (!empty($ext)) {
return strtolower($ext);
}
// 根据URL特征判断
if (strpos($url, '.jpg') !== false || strpos($url, '.jpeg') !== false) {
return 'jpg';
} elseif (strpos($url, '.png') !== false) {
return 'png';
} elseif (strpos($url, '.gif') !== false) {
return 'gif';
} elseif (strpos($url, '.webp') !== false) {
return 'webp';
}
return 'jpg'; // 默认
}
/**
* 处理企业微信图片 - 通过wxWorkDownload获取cloudUrl
*/
private function processWorkImage(&$logData, $msgData, &$imageUrls, &$downloadTasks)
{
if (empty($logData['file_id']) || empty($logData['file_aeskey'])) {
\think\Log::error('企微图片缺少必要参数');
return;
}
// 根据image_has_hd决定下载类型
// 1: 大图, 2: 小图
$hdType = ($logData['image_has_hd'] == 1) ? 1 : 2;
// 原图
$originalUrl = $this->wxWorkDownload(
$logData['file_aeskey'],
$logData['file_id'],
$logData['file_size'],
$hdType
);
if ($originalUrl) {
$imageUrls['original'] = [
'cloud_url' => $originalUrl,
'size' => $logData['file_size'],
'md5' => $logData['file_md5'],
'source' => 'work',
'download_type' => $hdType,
'has_hd' => $logData['image_has_hd']
];
$downloadTasks['original'] = [
'url' => $originalUrl,
'md5' => $logData['file_md5'],
'ext' => $this->getImageExt($originalUrl),
'source' => 'work'
];
} else {
// 获取失败,记录任务稍后重试
$downloadTasks['original'] = [
'type' => 'work_retry',
'file_id' => $logData['file_id'],
'file_aeskey' => $logData['file_aeskey'],
'file_size' => $logData['file_size'],
'file_md5' => $logData['file_md5'],
'download_type' => $hdType,
'retry_count' => 0
];
}
// 缩略图 (type=3)
if (!empty($msgData['fileThumbSize']) || !empty($logData['file_id'])) {
$thumbUrl = $this->wxWorkDownload(
$logData['file_aeskey'],
$logData['file_id'],
$msgData['fileThumbSize'] ?? $logData['file_size'],
3 // 缩略图类型
);
if ($thumbUrl) {
$thumbMd5 = $logData['file_md5'] . '_thumb';
$imageUrls['thumb'] = [
'cloud_url' => $thumbUrl,
'size' => $msgData['fileThumbSize'] ?? null,
'md5' => $thumbMd5,
'source' => 'work',
'download_type' => 3
];
$downloadTasks['thumb'] = [
'url' => $thumbUrl,
'md5' => $thumbMd5,
'ext' => $this->getImageExt($thumbUrl),
'source' => 'work'
];
}
}
}
/**
* 处理GIF图片
*/
private function processGifImage(&$logData, $msgData, &$imageUrls, &$downloadTasks)
{
$gifUrl = $msgData['fileHttpUrl'] ?? $msgData['file_http_url'] ?? null;
if (!empty($gifUrl)) {
$imageUrls['original'] = [
'original_url' => $gifUrl,
'size' => $logData['file_size'],
'md5' => $logData['file_md5'],
'source' => 'gif'
];
$downloadTasks['original'] = [
'url' => $gifUrl,
'md5' => $logData['file_md5'],
'ext' => 'gif',
'source' => 'gif'
];
}
}
/**
* 处理视频消息
*/
private function processVideoMessage(&$logData, $msgData)
{
$logData['file_id'] = $msgData['fileId'] ?? $msgData['file_id'] ?? null;
$logData['file_aeskey'] = $msgData['fileAesKey'] ?? $msgData['file_aeskey'] ?? null;
$logData['file_md5'] = $msgData['fileMd5'] ?? $msgData['file_md5'] ?? null;
$logData['file_name'] = $msgData['fileName'] ?? $msgData['file_name'] ?? null;
$logData['file_size'] = $msgData['fileSize'] ?? $msgData['file_size'] ?? null;
$logData['duration'] = $msgData['duration'] ?? null;
// 封面图信息
$logData['cover_image_id'] = $msgData['coverImageId'] ?? $msgData['cover_image_id'] ?? null;
$logData['cover_image_aeskey'] = $msgData['coverImageAeskey'] ?? $msgData['cover_image_aeskey'] ?? null;
$logData['cover_image_md5'] = $msgData['coverImageMd5'] ?? $msgData['cover_image_md5'] ?? null;
$logData['cover_image_size'] = $msgData['coverImageSize'] ?? $msgData['cover_image_size'] ?? null;
// 个微视频特有
if ($logData['msg_type'] == 103) {
$logData['cover_image_http_url'] = $msgData['coverImageHttpUrl'] ?? $msgData['cover_image_http_url'] ?? null;
$logData['file_http_url'] = $msgData['fileHttpUrl'] ?? $msgData['file_http_url'] ?? null;
$logData['file_authkey'] = $msgData['fileAuthkey'] ?? $msgData['file_authkey'] ?? null;
}
}
/**
* 处理文件消息
*/
private function processFileMessage(&$logData, $msgData)
{
$logData['file_id'] = $msgData['fileId'] ?? $msgData['file_id'] ?? null;
$logData['file_aeskey'] = $msgData['fileAesKey'] ?? $msgData['file_aeskey'] ?? null;
$logData['file_md5'] = $msgData['fileMd5'] ?? $msgData['file_md5'] ?? null;
$logData['file_name'] = $msgData['fileName'] ?? $msgData['file_name'] ?? null;
$logData['file_size'] = $msgData['fileSize'] ?? $msgData['file_size'] ?? null;
$logData['file_ext'] = $msgData['fileNameExt'] ?? $msgData['file_ext'] ?? null;
// 个微文件特有
if ($logData['msg_type'] == 102) {
$logData['file_http_url'] = $msgData['fileHttpUrl'] ?? $msgData['file_http_url'] ?? null;
$logData['file_authkey'] = $msgData['fileAuthkey'] ?? $msgData['file_authkey'] ?? null;
}
}
/**
* 处理位置消息
*/
private function processLocationMessage(&$logData, $msgData)
{
$logData['address'] = $msgData['address'] ?? null;
$logData['latitude'] = $msgData['latitude'] ?? null;
$logData['longitude'] = $msgData['longitude'] ?? null;
$logData['zoom'] = $msgData['zoom'] ?? null;
}
/**
* 处理链接消息
*/
private function processLinkMessage(&$logData, $msgData)
{
$linkInfo = [
'desc' => $msgData['desc'] ?? null,
'title' => $msgData['title'] ?? null,
'link_url' => $msgData['linkUrl'] ?? $msgData['link_url'] ?? null,
'icon_url' => $msgData['iconUrl'] ?? $msgData['icon_url'] ?? null,
'icon_aeskey' => $msgData['iconAeskey'] ?? $msgData['icon_aeskey'] ?? null,
'icon_size' => $msgData['iconSize'] ?? $msgData['icon_size'] ?? null,
];
$logData['link_info'] = json_encode($linkInfo, JSON_UNESCAPED_UNICODE);
}
/**
* 处理名片消息
*/
private function processBusinessCardMessage(&$logData, $msgData)
{
$businessCard = [
'shared_id' => $msgData['shared_id'] ?? null,
'nickname' => $msgData['nickname'] ?? null,
'real_name' => $msgData['realName'] ?? $msgData['real_name'] ?? null,
'avatar_url' => $msgData['avatarUrl'] ?? $msgData['avatar_url'] ?? null,
'corp_id' => $msgData['corpId'] ?? $msgData['corp_id'] ?? null,
'corp_name' => $msgData['corpName'] ?? $msgData['corp_name'] ?? null,
];
$logData['business_card'] = json_encode($businessCard, JSON_UNESCAPED_UNICODE);
}
/**
* 处理红包消息
*/
private function processRedPacketMessage(&$logData, $msgData)
{
$redPacket = [
'type' => $msgData['hongbaoType'] ?? $msgData['hongbao_type'] ?? null,
'subtype' => $msgData['hongbaoSubtype'] ?? $msgData['hongbao_subtype'] ?? null,
'order_id' => $msgData['orderId'] ?? $msgData['order_id'] ?? null,
'ticket' => $msgData['ticket'] ?? null,
'wishing' => $msgData['wishingContent'] ?? $msgData['wishing_content'] ?? null,
'amount' => $msgData['totalAmount'] ?? $msgData['total_amount'] ?? null,
'look_wording' => $msgData['lookWording'] ?? $msgData['look_wording'] ?? null,
'recv_wording' => $msgData['recvWording'] ?? $msgData['recv_wording'] ?? null,
'cover_1x' => $msgData['coverUrl1x'] ?? $msgData['cover_url_1x'] ?? null,
'cover_2x' => $msgData['coverUrl2x'] ?? $msgData['cover_url_2x'] ?? null,
'to_ids' => $msgData['toIdList'] ?? $msgData['to_id_list'] ?? null,
];
$logData['red_packet'] = json_encode($redPacket, JSON_UNESCAPED_UNICODE);
}
/**
* 处理语音消息
*/
private function processVoiceMessage(&$logData, $msgData)
{
$logData['file_id'] = $msgData['fileId'] ?? $msgData['file_id'] ?? null;
$logData['file_aeskey'] = $msgData['fileAesKey'] ?? $msgData['file_aeskey'] ?? null;
$logData['file_md5'] = $msgData['fileMd5'] ?? $msgData['file_md5'] ?? null;
$logData['file_size'] = $msgData['fileSize'] ?? $msgData['file_size'] ?? null;
$logData['voice_time'] = $msgData['voiceTime'] ?? $msgData['voice_time'] ?? null;
}
/**
* 处理小程序消息
*/
private function processMiniProgramMessage(&$logData, $msgData)
{
$logData['appid'] = $msgData['appid'] ?? null;
$logData['page_path'] = $msgData['pagepath'] ?? $msgData['page_path'] ?? null;
$logData['username'] = $msgData['username'] ?? null;
$logData['cover_image_id'] = $msgData['coverImageId'] ?? $msgData['cover_image_id'] ?? null;
$logData['cover_image_aeskey'] = $msgData['coverImageAeskey'] ?? $msgData['cover_image_aeskey'] ?? null;
$logData['cover_image_md5'] = $msgData['coverImage_md5'] ?? $msgData['cover_image_md5'] ?? null;
$logData['cover_image_size'] = $msgData['coverImageSize'] ?? $msgData['cover_image_size'] ?? null;
$linkInfo = [
'desc' => $msgData['desc'] ?? null,
'title' => $msgData['title'] ?? null,
'icon_url' => $msgData['iconUrl'] ?? $msgData['icon_url'] ?? null,
];
$logData['link_info'] = json_encode($linkInfo, JSON_UNESCAPED_UNICODE);
}
/**
* 处理视频号消息
*/
private function processVideoChannelMessage(&$logData, $msgData)
{
$videoChannel = [
'channel_name' => $msgData['channelName'] ?? $msgData['channel_name'] ?? null,
'channel_url' => $msgData['channelUrl'] ?? $msgData['channel_url'] ?? null,
'cover_url' => $msgData['coverUrl'] ?? $msgData['cover_url'] ?? null,
'head_img_url' => $msgData['headImgUrl'] ?? $msgData['head_img_url'] ?? null,
'encode_data' => $msgData['encodeData'] ?? $msgData['encode_data'] ?? null,
'username' => $msgData['username'] ?? null,
];
$logData['video_channel'] = json_encode($videoChannel, JSON_UNESCAPED_UNICODE);
}
/**
* 处理系统消息
* @param array &$logData
* @param array $message
*/
private function processSystemMessage(&$logData, $message)
{
$msgData = $message['msgData'] ?? [];
// 好友申请通知 (2357)
if ($logData['msg_type'] == 2357 && !empty($msgData)) {
$businessCard = [
'apply_time' => $msgData['applyTime'] ?? null,
'contact_id' => $msgData['contactId'] ?? null,
'contact_nickname' => $msgData['contactNickname'] ?? null,
'contact_type' => $msgData['contactType'] ?? null,
'user_id' => $msgData['userId'] ?? null,
];
$logData['business_card'] = json_encode($businessCard, JSON_UNESCAPED_UNICODE);
}
}
/**
* 获取群列表(原有方法)
*/
public function getRoomList($index = 0)
{
$result = $this->query->query("getRoomList", [$this->guid, $index]);
$result = json_decode($result, true);
if ($result["code"] == 0) {
$data = $result["data"];
$roomList = $data["roomList"];
$insertDatas = [];
foreach ($roomList as $room) {
// 检查群是否存在
$roomData = $this->roomModel->where(["room_id" => $room["roomId"]])->find();
if (!$roomData) {
$insertData = $this->convertWeWorkRoomToDbArray($room);
array_push($insertDatas, $insertData);
}
}
if (!empty($insertDatas)) {
$res = $this->roomModel->saveAll($insertDatas);
}
// 递归获取所有群
if ($data["hasMore"]) {
$this->getRoomList($data["nextStartIndex"]);
}
return json(['code' => 0, 'msg' => 'success', 'count' => count($insertDatas)]);
}
return json($result);
}
/**
* 获取单个群信息(原有方法)
*/
public function batchGetRoomDetail($id)
{
\think\Log::error('获取单个群信息: ');
return $this->batchGetRoomDetails([strval($id)]);
}
/**
* 获取多个群信息(原有方法)
*/
public function batchGetRoomDetails($ids)
{
\think\Log::error('获取多个群信息: ');
$result = $this->query->query("batchGetRoomDetail", [$this->guid, $ids]);
$result = json_decode($result, true);
$insertDatas = [];
if ($result['code'] == 0) {
\think\Log::error('返回结果正常: ');
$roomList = $result["data"]["roomList"];
foreach ($roomList as $room) {
$roomData = $this->roomModel->where(["room_id" => $room["roomId"]])->find();
if (!$roomData) {
$insertData = $this->convertWeWorkRoomToDbArray($room);
array_push($insertDatas, $insertData);
}else{
$updataData = $this->convertWeWorkRoomToDbArray($room);
$roomData->save($updataData);
}
}
if (!empty($insertDatas)) {
\think\Log::error('有数据要创建: ');
$res = $this->roomModel->saveAll($insertDatas);
}
}else{
\think\Log::error('返回结果异常: '.json_encode($result));
}
return json(['code' => 0, 'msg' => 'success', 'data' => $insertDatas]);
}
/**
* 格式化群信息(原有方法)
*/
function convertWeWorkRoomToDbArray($weWorkRoomData)
{
$fieldMapping = [
'roomId' => 'room_id',
'roomName' => 'room_name',
'roomAvatarUrl' => 'room_avatar_url',
'roomCreateTime' => 'room_create_time',
'roomUpdateTime' => 'room_update_time',
'roomOwnerId' => 'room_owner_id',
'roomMemberCount' => 'room_member_count',
'roomFlag' => 'room_flag',
'ticket' => 'ticket'
];
$dbData = [];
foreach ($fieldMapping as $weWorkField => $dbField) {
if (isset($weWorkRoomData[$weWorkField])) {
$dbData[$dbField] = $weWorkRoomData[$weWorkField];
}
}
return $dbData;
}
/**
* 获取多个联系人信息
*/
private function batchGetUserinfo($ids)
{
\think\Log::error('获取多个用户信息: ');
$result = $this->query->query("batchGetUserinfo", [$this->guid, $ids]);
$result = json_decode($result, true);
$insertDatas = [];
if ($result['code'] == 0) {
\think\Log::error('返回结果正常: ');
$contactList = $result["data"]["contactList"];
\think\Log::error('返回结果正常: '.json_encode($contactList));
foreach ($contactList as $contact) {
$contactId = $this->resolveWeWorkContactId($contact);
if (!$contactId) {
\think\Log::warning('联系人数据缺少标识: ' . json_encode($contact, JSON_UNESCAPED_UNICODE));
continue;
}
$contactData = $this->contactModel->where(["contact_id" => $contactId])->find();
if (!$contactData) {
$insertData = $this->convertWeWorkContactToDbArray($contact);
array_push($insertDatas, $insertData);
} else {
$updataData = $this->convertWeWorkContactToDbArray($contact);
$contactData->save($updataData);
}
}
\think\Log::error('需要创建的数据: '.json_encode($insertDatas));
if (!empty($insertDatas)) {
\think\Log::error('有数据要创建: ' . json_encode($insertDatas, JSON_UNESCAPED_UNICODE));
$this->contactModel->saveAll($insertDatas);
}
} else {
\think\Log::error('返回结果异常: ' . json_encode($result));
}
return json(['code' => 0, 'msg' => 'success', 'data' => $insertDatas]);
}
private function sendMessages($datas, $toName = ""){
\think\Log::error("调用发送信息2:");
$msgs = (is_array($datas) && isset($datas["msgs"]) && is_array($datas["msgs"])) ? $datas["msgs"] : [];
Log::error("过滤后的信息",json_encode($msgs));
if (empty($msgs)) {
return;
}
foreach ($msgs as $msg){
$this->sendMessage($msg, $toName);
}
}
/*
* 发送消息聚合处理
*/
private function sendMessage($data,$toName = ""){
\think\Log::error('发送聚合消息: ' . json_encode($data, JSON_UNESCAPED_UNICODE));
if (empty($data) || !is_array($data)) {
\think\Log::warning('sendMessage参数为空或格式错误: ' . json_encode($data, JSON_UNESCAPED_UNICODE));
return;
}
$data = array_merge([
'msg' => '',
'pid' => null,
'atid' => null,
'wxid' => '',
'method' => '',
'img' => null,
'file' => null
], $data);
['msg' => $msg, 'pid' => $pid,'atid' =>$atid,'wxid' =>$wxid, 'method'=>$method,'img'=>$imgUrl,'file'=>$fileUrl] = $data;
if ($wxid === '' || $method === '') {
\think\Log::warning('sendMessage缺少必要字段: ' . json_encode($data, JSON_UNESCAPED_UNICODE));
return;
}
$result = [];
switch($method){
case "sendText":
if(!$atid){
$this->query->query("sendText", [$this->guid, $wxid, $msg, false]);
}else{
//如果有@,要清理掉msg消息中的@+toName内容
$msg = str_replace("@".$toName, "", $msg);
$message = [
["subtype"=>1,"text"=>strval($atid)],
["subtype"=>0,"text"=>strval($msg)]
];
$result = $this->query->query("sendHyperText", [$this->guid, $wxid, $message]);
}
break;
case "sendImage":
//先通过URL上传文件获取fileId
$result = $this->query->query("cdnBigUploadByUrl", [$this->guid, "照片.png",$imgUrl,1]);
$result = json_decode($result, true);
if($result["code"] == 0){
$fileAesKey = $result["data"]["fileAesKey"];
$fileId = $result["data"]["fileId"];
$fileKey = $result["data"]["fileKey"];
$fileMd5 = $result["data"]["fileMd5"];
$fileSize = $result["data"]["fileSize"];
$fileThumbSize = $result["data"]["fileThumbSize"];
$durationTime = $result["data"]["durationTime"];
}else{
\think\Log::error('图片上传失败: ' . json_encode($result));
return;
}
$result = $this->query->query("sendImage", [$this->guid, $wxid,$fileAesKey,$fileId,$fileKey,$fileMd5,$fileSize,$filename]);
break;
case "sendFile":
//先通过URL上传文件获取fileId
//提取文件名
$filename = basename($fileUrl);
$result = $this->query->query("cdnBigUploadByUrl", [$this->guid, $filename,$fileUrl,5]);
$result = json_decode($result, true);
if($result["code"] == 0){
$fileAesKey = $result["data"]["fileAesKey"];
$fileId = $result["data"]["fileId"];
$fileKey = $result["data"]["fileKey"];
$fileMd5 = $result["data"]["fileMd5"];
$fileSize = $result["data"]["fileSize"];
}else{
\think\Log::error('文件上传失败: ' . json_encode($result));
return;
}
$result = $this->query->query("sendFile", [$this->guid, $wxid,$fileAesKey,$fileId,$fileSize,$filename]);
break;
}
\think\Log::error('sendMessage结果: ' . json_encode($result));
}
private function resolveWeWorkContactId($weWorkContactData)
{
return $weWorkContactData['userId'] ?? null;
}
private function convertWeWorkContactToDbArray($weWorkContactData)
{
$fieldMapping = [
'contactId' => 'contact_id',
'userId' => 'user_id',
'corpId' => 'corp_id',
'groupId' => 'group_id',
'nickname' => 'nickname',
'realName' => 'real_name',
'remark' => 'remark',
'avatarUrl' => 'avatar_url',
'alias' => 'alias',
'acctid' => 'acctid',
'mobile' => 'mobile',
'internationCode' => 'internation_code',
'gender' => 'gender',
];
$dbData = [];
foreach ($fieldMapping as $weWorkField => $dbField) {
if (array_key_exists($weWorkField, $weWorkContactData)) {
$dbData[$dbField] = $weWorkContactData[$weWorkField];
}
}
if (empty($dbData['contact_id']) && !empty($dbData['user_id'])) {
$dbData['contact_id'] = $dbData['user_id'];
}
return $dbData;
}
/**
* 异步任务处理(可以从队列中消费消息)
*/
public function consumeQueue()
{
set_time_limit(0);
while (true) {
try {
// 从队列中获取消息
$message = $this->redis->rpop("qiweMessage");
if ($message) {
$data = json_decode($message, true);
$this->processMessages($data);
} else {
// 没有消息时休眠1秒
sleep(1);
}
// 检查是否有同步任务
$task = $this->redis->rpop("qiweTask");
if ($task) {
$taskData = json_decode($task, true);
$this->handleTask($taskData);
}
} catch (\Exception $e) {
\think\Log::error('队列消费失败: ' . $e->getMessage());
sleep(5); // 出错后等待5秒
}
}
}
/**
* 处理异步任务
* @param array $taskData
*/
private function handleTask($taskData)
{
switch ($taskData['type'] ?? '') {
case 'sync_rooms':
$this->getRoomList(0);
\think\Log::info('群列表同步完成');
break;
default:
\think\Log::warning('未知任务类型: ' . ($taskData['type'] ?? 'unknown'));
break;
}
}
/**
* 健康检查接口
*/
public function health()
{
return json([
'code' => 0,
'msg' => 'ok',
'data' => [
'time' => time(),
'redis' => $this->redis->ping() ? 'connected' : 'disconnected'
]
]);
}
}