在ThinkPHP框架中实现客服系统,可以通过以下步骤:
创建customer_service
表,包含以下字段:
id
:主键,自增username
:客服用户名password
:客服密码create_time
:创建时间创建chat_log
表,包含以下字段:
id
:主键,自增from_user_id
:发送消息的用户IDto_user_id
:接收消息的客服IDcontent
:消息内容create_time
:消息创建时间在CustomerService
控制器中,创建login
方法,实现客服登录功能。在登录页面中,通过表单提交客服用户名和密码,后端通过查询数据库验证客服身份,如果验证通过则将客服ID存储到session中。
public function login()
{
if ($this->request->isPost()) {
$username = $this->request->post('username');
$password = $this->request->post('password');
$customerService = CustomerServiceModel::where('username', $username)
->where('password', md5($password))
->find();
if ($customerService) {
session('customer_service_id', $customerService->id);
$this->success('登录成功', 'Chat/index');
} else {
$this->error('用户名或密码错误');
}
}
return $this->fetch();
}
在Chat
控制器中,创建index
方法,实现客服聊天功能。在聊天页面中,客服可以看到当前在线用户列表,并选择一个用户进行聊天。客服发送消息时,后端将消息保存到chat_log
表中,并通过WebSocket向指定用户推送消息。
public function index()
{
$customerServiceId = session('customer_service_id');
if (!$customerServiceId) {
$this->error('请先登录', 'CustomerService/login');
}
// 查询当前在线用户列表
$userIds = Gateway::getUidList();
$users = UserModel::whereIn('id', $userIds)->select();
$this->assign('users', $users);
return $this->fetch();
}
public function sendMessage()
{
$customerServiceId = session('customer_service_id');
if (!$customerServiceId) {
$this->error('请先登录', 'CustomerService/login');
}
$toUserId = $this->request->post('to_user_id');
$content = $this->request->post('content');
// 保存聊天记录
$chatLog = new ChatLogModel();
$chatLog->from_user_id = $customerServiceId;
$chatLog->to_user_id = $toUserId;
$chatLog->content = $content;
$chatLog->save();
// 推送消息给指定用户
Gateway::sendToUid($toUserId, json_encode([
'type' => 'chatMessage',
'data' => [
'from_user_id' => $customerServiceId,
'content' => $content,
'create_time' => date('Y-m-d H:i:s'),
],
]));
}
需要注意的是,聊天页面需要使用WebSocket实现实时推送消息,可以使用GatewayWorker作为WebSocket服务器。同时,为了保证客服和用户之间的聊天记录不会混淆,需要在chat_log
表中增加from_type
和to_type
字段,分别表示发送消息的用户类型和接收消息的用户类型。在查询聊天记录时,需要根据当前用户类型进行过滤。