Browse Source

del chat part

master
chuan 4 weeks ago
parent
commit
d38c1af03b
  1. 2
      .gitignore
  2. 51
      app/admin/service/AdminService.php
  3. 24
      app/home/controller/News.php
  4. 130
      app/home/service/LoginService.php
  5. 50
      app/home/service/UserService.php
  6. 24
      app/utility/RequestChatServer.php

2
.gitignore

@ -2,6 +2,6 @@
/.vscode /.vscode
/runtime/ /runtime/
/vendor/ /vendor/
#*.log *.log
.env .env
composer.lock composer.lock

51
app/admin/service/AdminService.php

@ -29,49 +29,15 @@ class AdminService extends AdminBaseService
$username = $param['user_name']; $username = $param['user_name'];
$user = AdminModel::getByUserName($username); $user = AdminModel::getByUserName($username);
if (!empty($user)) { if (!empty($user)) {
return $this->toData('200100', '该用户已存在', []); return $this->toData('500', '该用户已存在');
} }
$param['password'] = (new UnqId())->encryptPassword($param['password'], env('ENCRYPT.ADMINSALT')); $param['password'] = (new UnqId())->encryptPassword($param['password'], env('ENCRYPT.ADMINSALT'));
$param['invite_code'] = (new BaseHomeService())->getUniqInviteCode(); $param['invite_code'] = (new BaseHomeService())->getUniqInviteCode();
$resAdmin = AdminModel::create($param); $resAdmin = AdminModel::create($param);
if (!$resAdmin) {
// 注册一下聊天账号 return $this->toData('500', '添加失败');
$chatData = [
'Username' => $resAdmin->id."_".$resAdmin->user_name, //用account.id + account.user_name 拼接作为聊天账号注册的Username
'Password' => '123456',
];
$chatUrl = env('CHAT_SERVER.BASE_URL') . '/api/user/register';
$regChat = (new \app\utility\RequestChatServer())->ReqChatServer($chatUrl, $chatData);
if (!isset($regChat['data']['uuid'])) {
return $this->toData('0', '注册聊天账号失败.', ['chat_response' => $regChat]);
} }
UserChatLinkModel::create([ return $this->toData('0', '添加成功', ['id' => $resAdmin->id]);
'user_id' => $resAdmin->id,
'user_type' => 2,
'chat_uuid' => $regChat['data']['uuid'],
'chat_name' => $regChat['data']['username']
]);
// 创建聊天群
$groupName = 'ivs-group'.$resAdmin->id;
$chatGroupData = [
'Name' => $groupName,
];
$chatGroupUrl = env('CHAT_SERVER.BASE_URL') . '/api/group/join/'.$regChat['data']['uuid'];
$chatGroupRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatGroupUrl, $chatGroupData);
if (!isset($chatGroupRes['data']['group_uuid'])) {
return $this->toData('100400', 'Failed to register a chat group.', []);
}
UserChatGroupModel::create([
'user_id' => $resAdmin->id,
'user_chat_uuid' => $regChat['data']['uuid'],
'group_name' => $groupName,
'group_uuid' => $chatGroupRes['data']['group_uuid']
]);
return $this->toData('0', '添加成功.', ['chatData' => $regChat]);
} catch (ValidateException $validateException) { } catch (ValidateException $validateException) {
$message = $validateException->getError(); $message = $validateException->getError();
return $this->toData('100400', $message); return $this->toData('100400', $message);
@ -142,15 +108,6 @@ class AdminService extends AdminBaseService
return $this->toData('100400', 'The user does not exist.', []); return $this->toData('100400', 'The user does not exist.', []);
} }
$infoArr = $info->toArray(); $infoArr = $info->toArray();
// 获取用户的聊天账号信息
$chatInfo = UserChatLinkModel::where(['user_id'=>$userId, 'user_type'=>2])->find();
$chat_uuid = 0;
if (!empty($chatInfo)) {
$chat_uuid = $chatInfo->chat_uuid;
}
$infoArr['chat_uuid'] = $chat_uuid;
// 返回数据 // 返回数据
return $this->toData('0', 'Modification successful.', $infoArr); return $this->toData('0', 'Modification successful.', $infoArr);
} catch (\Exception $exception) { } catch (\Exception $exception) {

24
app/home/controller/News.php

@ -93,31 +93,9 @@ class News extends HomeBaseController
*/ */
public function testApi() public function testApi()
{ {
$chatData = [
'Username' => "ccc333519",
'Password' => '123456',
];
$chatUrl = env('CHAT_SERVER.BASE_URL') . '/user/register';
$res = (new \app\utility\RequestChatServer())->ReqChatServer($chatUrl, $chatData);
if (!isset($res['data']['uuid'])) {
return json([
'code' => '-1',
'message' => '注册聊天账号失败',
]);
}
//将客服账号与聊天账号关联
UserChatLinkModel::create([
'user_id' => 999,
'user_type' => 1,
'chat_uuid' => $res['data']['uuid'],
]);
return json([ return json([
'code' => '0', 'code' => '0',
'message' => 'successful', 'message' => 'successful'
'data' => $res,
'uuid' => $res['data']['uuid']
]); ]);
} }

130
app/home/service/LoginService.php

@ -172,79 +172,12 @@ class LoginService extends BaseHomeService
$userId = UserModel::emailRegister($email, $userNo, $userInviteCode, $parentUserId, $password, $ip, $salt, 1, $agentId); $userId = UserModel::emailRegister($email, $userNo, $userInviteCode, $parentUserId, $password, $ip, $salt, 1, $agentId);
// 生成钱包地址 // 生成钱包地址
(new UserService())->doRegInitUserInfo($userId, $parentUserId); (new UserService())->doRegInitUserInfo($userId, $parentUserId);
// 注册聊天账号
$chatData = [
'Username' => $userNo,
'Password' => '123456',
];
$chatUrl = env('CHAT_SERVER.BASE_URL') . '/api/user/register';
$chatRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatUrl, $chatData);
if (!isset($chatRes['data']['uuid'])) {
return $this->toData('100400', 'Failed to register a chat account.', []);
}
// 绑定注册账号与聊天账号
UserChatLinkModel::create([
'user_id' => $userId,
'user_type' => 1,
'chat_uuid' => $chatRes['data']['uuid'],
'chat_name' => $chatRes['data']['username']
]);
Log::info("邮箱注册 - 用户注册chat账号 - user_id=".$userId. " chat_uiud=".$chatRes['data']['uuid']);
// 如果有代理,绑定到代理下一个客服(轮询客服绑定)
if ($agentId > 0 ) {
$customerIds = AdminModel::getCustomerIdsByAgentId($agentId); // 获取代理下的所有客服ID
Log::info("邮箱注册 - 代理下客服ids=".json_encode($customerIds));
if (empty($customerIds)) {
return $this->toData('100400', 'There is no customer service account under the current agent', []);
}
$counterKey = 'counter_bind_customer:'.$agentId;
$counterIndex = Cache::store('redis')->get($counterKey); //客服绑定计数器索引
if (empty($counterIndex)) {
$counterIndex = 0;
Cache::store('redis')->set($counterKey, $counterIndex);
$tagCustomerId = $customerIds[0];
} else {
Cache::store('redis')->inc($counterKey); //更新计数器索引
$tagIndex = $counterIndex % count($customerIds);
$tagCustomerId = $customerIds[$tagIndex];
}
Log::info("邮箱注册 - 要绑定的客服id=".$tagCustomerId);
if ($tagCustomerId > 0) {
CustomerRelationalModel::create([
'user_id' => $userId,
'customer_id' => $tagCustomerId,
'agent_id' => $agentId,
]);
}
// 将注册账号的chat_id与绑定客服的chat_id加为好友
Log::info("邮箱注册 - 获取去客服聊天账号信息, $tagCustomerId=".$tagCustomerId);
$customerChatInfo = UserChatLinkModel::where(['user_id'=>$tagCustomerId, 'user_type'=>2])->find(); //查询客服的聊天账号uuid
if (empty($customerChatInfo)) {
return $this->toData('100400', 'The customer uuid is error.', []);
}
$chatFriendsData = [
'UserUuid' => $chatRes['data']['uuid'],
'CustomerUuid' => $customerChatInfo->chat_uuid,
];
Log::info("邮箱注册 - 请求聊天夫加好友=".$tagCustomerId);
$chatFriendsUrl = env('CHAT_SERVER.BASE_URL') . '/api/eachOtherFriends';
$chatFriendsRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatFriendsUrl, $chatFriendsData);
Log::info("邮箱注册 - chat服务加好友结果:".json_encode($chatFriendsRes));
// 将当前用户加入到代理创建的群聊中 【需要查出当前用户的代理创建的群聊信息】
$agentGroup = UserChatGroupModel::where(['user_id'=>$agentId])->find();
if (empty($agentGroup)) {
return $this->toData('100400', 'The chat group is error.', []);
}
$joinChatGroupUrl = env('CHAT_SERVER.BASE_URL') . '/api/group/join/'.$chatRes['data']['uuid'].'/'.$agentGroup->group_uuid;
$joinChatGroupRes = (new \app\utility\RequestChatServer())->ReqChatServer($joinChatGroupUrl, []);
}
}); });
// 删除缓存 // 删除缓存
$this->delCache($emailKey); $this->delCache($emailKey);
// 累加已经注册的个数 // 累加已经注册的个数
$this->updateHadRegisterNumCache($ipCanRegisterNumPerIpPerDay); $this->updateHadRegisterNumCache($ipCanRegisterNumPerIpPerDay);
return $this->toData('0', 'Registration Successful.', []); return $this->toData('0', 'Registration Successful.');
} catch (ValidateException $validateException) { } catch (ValidateException $validateException) {
// 参数校验失败 异常类 // 参数校验失败 异常类
$message = $validateException->getError(); $message = $validateException->getError();
@ -485,67 +418,6 @@ class LoginService extends BaseHomeService
$userId = UserModel::phoneRegister($param['nation'], $param['phone'], $userNo, $userInviteCode, $parentUserId, $password, $ip, $salt, 1, $agentId); $userId = UserModel::phoneRegister($param['nation'], $param['phone'], $userNo, $userInviteCode, $parentUserId, $password, $ip, $salt, 1, $agentId);
// 生成钱包地址 // 生成钱包地址
(new UserService())->doRegInitUserInfo($userId, $parentUserId); (new UserService())->doRegInitUserInfo($userId, $parentUserId);
// 注册聊天账号
$chatData = [
'Username' => $userNo,
'Password' => '123456',
];
$chatUrl = env('CHAT_SERVER.BASE_URL') . '/api/user/register';
$chatRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatUrl, $chatData);
if (!isset($chatRes['data']['uuid'])) {
return $this->toData('100400', 'Failed to register a chat account.', []);
}
// 绑定注册账号与聊天账号
UserChatLinkModel::create([
'user_id' => $userId,
'user_type' => 1,
'chat_uuid' => $chatRes['data']['uuid'],
'chat_name' => $chatRes['data']['username']
]);
// 如果有代理,绑定到代理下一个客服(轮询客服绑定)
if ($agentId > 0 ) {
$customerIds = AdminModel::getCustomerIdsByAgentId($agentId); // 获取代理下的所有客服ID
if (empty($customerIds)) {
return $this->toData('100400', 'There is no customer service account under the current agent', []);
}
$counterKey = 'counter_bind_customer:'.$agentId;
$counterIndex = Cache::store('redis')->get($counterKey); //客服绑定计数器索引
if (empty($counterIndex)) {
$counterIndex = 0;
Cache::store('redis')->set($counterKey, $counterIndex);
$tagCustomerId = $customerIds[0];
} else {
Cache::store('redis')->inc($counterKey); //更新计数器索引
$tagIndex = $counterIndex % count($customerIds);
$tagCustomerId = $customerIds[$tagIndex];
}
if ($tagCustomerId > 0) {
CustomerRelationalModel::create([
'user_id' => $userId,
'customer_id' => $tagCustomerId,
'agent_id' => $agentId,
]);
}
// 将注册账号的chat_id与绑定客服的chat_id加为好友
$customerChatInfo = UserChatLinkModel::where('user_id', $tagCustomerId)->find(); //查询客服的聊天账号uuid
if (empty($customerChatInfo)) {
return $this->toData('100400', 'The customer uuid is error.', []);
}
$chatFriendsData = [
'UserUuid' => $chatRes['data']['uuid'],
'CustomerUuid' => $customerChatInfo->chat_uuid,
];
$chatFriendsUrl = env('CHAT_SERVER.BASE_URL') . '/api/eachOtherFriends';
$chatFriendsRes = (new \app\utility\RequestChatServer())->ReqChatServer($chatFriendsUrl, $chatFriendsData);
Log::info("手机号注册 - chat服务加好友结果:".json_encode($chatFriendsRes));
// 将当前用户加入到代理创建的群聊中 【需要查出当前用户的代理创建的群聊信息】
$agentGroup = UserChatGroupModel::where(['user_id'=>$agentId])->find();
if (empty($agentGroup)) {
return $this->toData('100400', 'The chat group is error.', []);
}
$joinChatGroupUrl = env('CHAT_SERVER.BASE_URL') . '/api/group/join/'.$chatRes['data']['uuid'].'/'.$agentGroup->group_uuid;
$joinChatGroupRes = (new \app\utility\RequestChatServer())->ReqChatServer($joinChatGroupUrl, []);
}
}); });
// 删除缓存 // 删除缓存

50
app/home/service/UserService.php

@ -281,31 +281,8 @@ class UserService extends BaseHomeService
return $this->toData('100400', ' The user USD balance is insufficient ', []); return $this->toData('100400', ' The user USD balance is insufficient ', []);
} }
// 查询是否有购买vip记录, 计算用户vip到期时间
$expireTime = date("Y-m-d H:i:s");
$vipLog = PurchaseVipModel::where(['user_id'=>$userId])->order('id', 'desc')->find();
if (!empty($vipLog)) {
if (empty($vipLog->expire)) {
return $this->toData('100400', ' The vip expire error ', []);
}
if ($vipLog->expire >= $expireTime) {
$expireTimestamp = strtotime('+30 days', strtotime($vipLog->expire));
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
}
} else {
$expireTimestamp = strtotime('+30 days', time());
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
}
// 记录购买vip信息, 扣除用户金额 // 记录购买vip信息, 扣除用户金额
Db::transaction(function () use ($userId, $userMoneyNum, $vipPrice, $expireTime, $stockId) { Db::transaction(function () use ($userId, $userMoneyNum, $vipPrice, $stockId) {
// 添加购买vip记录
PurchaseVipModel::create([
'user_id' => $userId,
'amount' => $vipPrice,
'stock_id' => $stockId,
'expire' => $expireTime
]);
// 扣除用户USD // 扣除用户USD
UserMoneyModel::where(['user_id'=>$userId,'stock_id'=>$stockId])->where('usable_num', ">=", $vipPrice)->dec('usable_num', $vipPrice)->update(); UserMoneyModel::where(['user_id'=>$userId,'stock_id'=>$stockId])->where('usable_num', ">=", $vipPrice)->dec('usable_num', $vipPrice)->update();
// 添加用户USD变更日志 // 添加用户USD变更日志
@ -317,8 +294,31 @@ class UserService extends BaseHomeService
'change_num' => -$vipPrice, 'change_num' => -$vipPrice,
'order_id' => uniqid('vip_', true), 'order_id' => uniqid('vip_', true),
]); ]);
// 查询用户是否开通过vip,更新用户vip到期时间
$vipLog = PurchaseVipModel::where(['user_id'=>$userId])->find();
$expireTime = date("Y-m-d H:i:s");
if (!empty($vipLog)) {
if (empty($vipLog->expire)) {
return $this->toData('100400', ' The vip expire error ');
}
if ($vipLog->expire >= $expireTime) {
$expireTimestamp = strtotime('+30 days', strtotime($vipLog->expire));
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
}
$vipLog->expire = $expireTime;
$vipLog->save();
} else {
$expireTimestamp = strtotime('+30 days', time());
$expireTime = date("Y-m-d H:i:s", $expireTimestamp);
PurchaseVipModel::create([
'user_id' => $userId,
'amount' => $vipPrice,
'stock_id' => $stockId,
'expire' => $expireTime
]);
}
}); });
return $this->toData('0', 'successful', ['expire'=>$expireTime]); return $this->toData('0', 'successful');
} catch (\Exception $exception) { } catch (\Exception $exception) {
return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]); return $this->toData('100500', 'The system is busy.', [$exception->getMessage(), $exception->getTrace()]);
} }

24
app/utility/RequestChatServer.php

@ -8,28 +8,36 @@ use think\facade\Log;
class RequestChatServer class RequestChatServer
{ {
public function ReqChatServer(string $url, array $data): array public function ReqChatServer(string $url, array $data, string $method = 'POST'): array
{ {
try { try {
if (!in_array($method, ['POST','PUT'])) {
return $this->toData('400', '请求方法不在支持列表中');
}
Log::info("请求URL==".$url." 请求Param==".json_encode($data)); Log::info("请求URL==".$url." 请求Param==".json_encode($data));
$resBody = []; $resBody = [];
$client = new Client(); $client = new Client();
$response = $client->post($url, [ if ($method == 'PUT') {
'json' => $data, $response = $client->put($url, [
]); 'json' => $data,
]);
} else {
$response = $client->post($url, [
'json' => $data,
]);
}
$statusCode = $response->getStatusCode(); $statusCode = $response->getStatusCode();
Log::error("请求聊天服返回:code==".$statusCode); Log::error("请求聊天服返回:code==".$statusCode." body==". $response->getBody());
Log::error("请求聊天服返回:body==". $response->getBody());
if ($statusCode == 200) { if ($statusCode == 200) {
$resBody = json_decode($response->getBody(), true); // 转换为数组 $resBody = json_decode($response->getBody(), true); // 转换为数组
} }
return $resBody; return $resBody;
} catch (GuzzleException $e) { } catch (GuzzleException $e) {
Log::error("请求聊天服异常 - guzzle: " . $e->getMessage()); Log::error("请求聊天服异常 - guzzle: " . $e->getMessage());
return []; return $this->toData('500', $e->getMessage());
} catch (\Exception $exception) { } catch (\Exception $exception) {
Log::error("请求聊天服异常 - exc:" . $exception->getMessage()); Log::error("请求聊天服异常 - exc:" . $exception->getMessage());
return []; return $this->toData('500', $exception->getMessage());
} }
} }
} }
Loading…
Cancel
Save