| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453 |
- <?php
- namespace backend\controllers;
- use Yii;
- use yii\helpers\Json;
- use common\components\weixinUtil;
- use common\components\qqFaceUtil;
- use common\components\stringUtil;
- use common\components\util;
- use common\services\xhUserTagClassService;
- use common\services\xhUserService;
- use common\services\xhTMessageService;
- use common\components\configDict;
- use common\components\chuanglanSMS;
- class ChatController extends BackendController
- {
- const CUSTOMER = 'customer';
- const MERCHANT = 'merchant';
- /**
- * 商家访问的聊天页
- * @return string
- */
- public function actionIndex()
- {
- $get = Yii::$app->request->get();
- $customId = isset($get['customId']) ? $get['customId'] : 0;
- $custom = xhUserService::getById($customId);
- $merchantId = $this->merchantId;
- $adminId = $this->adminId;
- $merchant = $this->merchant;
- if(empty($custom)){
- util::stop("没有用户信息哦");
- }
- if(isset($custom['merchantId']) == false || $custom['merchantId'] != $merchantId){
- util::stop("非法用户");
- }
- $chatLogKey = "merchant_history_{$merchantId}_{$customId}";
- $themself = ['avatar' => $custom['avatar'],'userName' => $custom['userName']];
- $ourself = ['uid'=>$merchantId, 'chatUid'=>$customId, 'avatar' => $merchant['logo'],'userName' => $merchant['merchantName'], 'chatLogKey' => $chatLogKey, 'role'=>'merchant'];
- $emojiCode = qqFaceUtil::getEmojiCode();
- $hasHistoryPage = isset($get['hasHistoryPage']) ? $get['hasHistoryPage'] : '';
- $userTagStr = isset($custom['tag']) ? $custom['tag'] : '';
- $userTag = explode(',',trim($userTagStr));
- $merchantTag = xhUserTagClassService::getMerchantTag($merchantId);
- //swoole:客户是否在线
- $clientKey = self::CUSTOMER . ':customer_'.$customId.':merchant_' . $merchantId;
- /*$clientId = Yii::$app->redis->executeCommand('GET', [$clientKey]);
- $clientId = empty($clientId) ? 0 : $clientId;*/
- $existClientId = Yii::$app->redis->executeCommand('SCARD', [$clientKey]);
- $clientId = empty($existClientId) ? 0 : 1;
- $swooleUrl = substr($this->frontUrl, 7);
- $account = $merchant['id'];
- return $this->renderPartial('index', ['isWeixin' => $this->isWeixin,'customId' => $customId,'adminId' => $adminId,'merchantTag' => $merchantTag,'userTag' => $userTag,'hasHistoryPage' => $hasHistoryPage,'customId' => $customId, 'account'=>$account, 'themself' => $themself,'ourself' => $ourself,'emojiCode' => json_encode($emojiCode), 'clientId' => $clientId, 'swooleUrl'=>$swooleUrl]);
- }
- /**
- * 商家给客户发的模板消息,客户打开
- */
- public function actionTempletMsg(){
- $userId = Yii::$app->request->get('customId');
- $user = xhUserService::getById($userId);
- $merchant = $this->merchant;
- $merchantId = $this->merchantId;
- if(!empty($user)){
- $now = time();
- $userOpenId = $user['openId'];
- //获取最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
- $connect = Yii::$app->redis->executeCommand('GET', ["customer_{$userId}:merchant_{$merchantId}_new_msg_last_time"]);
- if(empty($connect) || ($now - $connect) > 100){
- $allTM = xhTMessageService::getList($merchantId);
- $shortTempId = 'OPENTM200605630';
- $tempId = $allTM[$shortTempId];
- $data = [
- "touser" => $userOpenId,"template_id" => $tempId,"url" => Yii::$app->params['frontUrl']."/chat/index?account=".$merchant['id'],
- "data" => ["first" => ["value" => "商家({$merchant['merchantName']}) 向您发来新消息","color" => "#173177"],
- "keyword1" => ["value" => '新消息',"color" => "#173177"],
- "keyword2" => ["value" => '文字',"color" => "#173177"],
- "remark" => ["value" => '点击查看详情',"color" => "#173177"]
- ]
- ];
- weixinUtil::sendTaskInform($data, $merchant);
- $now = (string)$now;
- Yii::$app->redis->executeCommand('SET', ["customer_{$userId}:merchant_{$merchantId}_new_msg_last_time", $now]);
- Yii::$app->redis->executeCommand('EXPIRE', ["customer_{$userId}:merchant_{$merchantId}_new_msg_last_time", 100]);//过期
- /*Yii::$app->redis->set("customer_{$userId}:merchant_{$merchantId}_new_msg_last_time", $now);
- Yii::$app->redis->expire("customer_{$userId}:merchant_{$merchantId}_new_msg_last_time", 100);*/
- }
- util::successInfo();
- //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
- //表情替换
- /*$imgUrl = $this->imgUrl;
- $emotionCode = qqFaceUtil::getEmojiCode($imgUrl);
- foreach($emotionCode as $key => $val){
- $zz = $val[0];
- $img = $val[1];
- $name = $val[2];
- $Content = str_replace($zz,$img,$Content);
- }
- Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now.'{~CHAT~}themself{~CHAT~}'.$Content]);
- util::end();*/
- }
- }
- /**
- * swoole进程崩了,发送手机短信
- */
- public function actionSwooleProcessDead(){
- if(Yii::$app->request->isAjax){//判断ajax提交
- $swooleMsgKey = configDict::getCacheKey('swoolePhoneMsg');
- $sendTime = Yii::$app->redis->executeCommand('GET', [$swooleMsgKey]);
- if(empty($sendTime)){
- $error = Yii::$app->request->post('error');
- $error = empty($error) ? '未传递错误信息' : $error;
- Yii::$app->redis->executeCommand('SET', [$swooleMsgKey, time()]);
- Yii::$app->redis->executeCommand('EXPIRE', [$swooleMsgKey, 60*30]);//30分钟过期
- $mobile = '18259179840';
- $serverIp = util::serverIp();
- $msg = '服务器IP:' . $serverIp . '的Swoole进程中断,请登录服务器查看,报错:'.$error.'!';//避免用户过长时间无法正常使用相应功能
- $sms = new chuanglanSMS('N2890342','abc178c7');
- $re = $sms->send($mobile, $msg);
- }
- }
- }
- /**
- * 商家管理员发送消息
- */
- public function actionSendMsg()
- {
- $merchantId = $this->merchantId;
- $get = Yii::$app->request->get();
- if(isset($get['content']) == false || empty($get['content'])){
- echo Json::encode(['code' => 'A0002','msg' => 'content empty','data' => '']);
- Yii::$app->end();
- }
- if(isset($get['customId']) == false || empty($get['customId'])){
- echo Json::encode(['code' => 'A0002','msg' => 'customId empty','data' => '']);
- Yii::$app->end();
- }
- $customId = $get['customId'];
- $content = $get['content'];
- $now = time();
- $user = xhUserService::getById($customId);
- if(empty($user)){
- echo Json::encode(['code' => 'A0002','msg' => '消息发送失败,没有用户信息','data' => $data]);
- Yii::$app->end();
- }
- if($user['merchantId'] != $this->merchantId){
- echo Json::encode(['code' => 'A0002','msg' => '非法访问','data' => $data]);
- Yii::$app->end();
- }
- if(empty($user['subscribe'])){
- echo Json::encode(['code' => 'A0002','msg' => '消息发送失败,用户没有关注公众号','data' => $data]);
- Yii::$app->end();
- }
- $customOpenId = $user['openId'];
- $r = weixinUtil::sendMsg($content,$this->merchant,$customOpenId);
- if($r['errcode'] != 0){
- if($r['errcode'] == '45015'){
- echo Json::encode(['code' => 'A0002','msg' => '消息发送失败,超过48小时未跟对方联系,需对方主动与你联系','data' => $data]);
- Yii::$app->end();
- }
- echo Json::encode(['code' => 'A0002','msg' => '消息发送失败,原因未知','data' => $data]);
- Yii::$app->end();
- }
- //商家的历史消息
- Yii::$app->redis->executeCommand('ZADD', ["merchant_history_{$merchantId}_{$customId}", $now, $now.'{~CHAT~}ourself{~CHAT~}'.$content]);
- $createTime = date("Y-m-d H:i:s");
- $msg = $content;
- $data = ['msgBelongTo' => 'ourself','content' => $msg,'createTime' =>$createTime];
- echo Json::encode(['code' => 'A0001','msg' => 'success','data' => $data]);
- }
- /**
- * 商家管理员获取消息
- */
- public function actionGetMsg()
- {
- $get = Yii::$app->request->get();
- if(isset($get['customId']) == false || empty($get['customId'])){
- echo Json::encode(['code' => 'A0002','msg' => 'customId empty','data' => '']);
- Yii::$app->end();
- }
- $customId = $get['customId'];
- $merchantId = $this->merchantId;
- $conList = [];
- /*$content = Yii::$app->redis->executeCommand('RPOP', ["merchant_get_{$merchantId}_{$customId}"]);
- //已经获取此用户消息,将用户从新消息列表删除
- Yii::$app->redis->executeCommand('ZREM', ["merchant_{$merchantId}_new_msg", "{$customId}"]);
- if(!empty($content)){
- do{
- $arr = explode('{~CHAT~}',trim($content));
- if(count($arr) == 3){
- $time = $arr[0];
- $createTime = date("Y-m-d H:i:s",$time);
- $msgBelongTo = $arr[1];
- $msg = $arr[2];
- $conArr = ['msgBelongTo' => $msgBelongTo,'content' => $msg,'createTime' =>$createTime];
- $conList[] = $conArr;
- //商家的历史消息
- $r = Yii::$app->redis->executeCommand('ZADD', ["merchant_history_{$merchantId}_{$customId}",$time, $time.'{~CHAT~}'.$msgBelongTo.'{~CHAT~}'.$msg]);
- }
- $content = Yii::$app->redis->executeCommand('RPOP', ["merchant_get_{$merchantId}_{$customId}"]);
- }while(!empty($content));
- }*/
- while($content = Yii::$app->redis->executeCommand('RPOP', ["merchant_get_{$merchantId}_{$customId}"])){
- $arr = explode('{~CHAT~}',trim($content));
- if(count($arr) == 3){
- $time = $arr[0];
- $createTime = date("Y-m-d H:i:s",$time);
- $msgBelongTo = $arr[1];
- $msg = $arr[2];
- $conArr = ['msgBelongTo' => $msgBelongTo,'content' => $msg,'createTime' =>$createTime];
- $conList[] = $conArr;
- //保存客户发来的消息
- Yii::$app->redis->executeCommand('ZADD', ["merchant_history_{$merchantId}_{$customId}",$time, $time.'{~CHAT~}'.$msgBelongTo.'{~CHAT~}'.$msg]);
- }
- }
- echo Json::encode(['code' => 'A0001','msg' => 'success','data' => $conList]);
- }
- /**
- * 获取新消息用户 最近联系人
- */
- public function actionGetUser()
- {
- $merchantId = $this->merchantId;
- $userId = $this->adminId;
- //打开二维码的用户
- /*$callUserReturn = Yii::$app->redis->executeCommand('ZREVRANGE', ["merchant_{$merchantId}_new_call", 0, -1, 'WITHSCORES']);
- $callUserList = [];
- if(!empty($callUserReturn)){
- $i = 0;
- $x = 0;
- foreach($callUserReturn as $key => $val){
- $i++;
- if($i%2 == 0){
- $callUserList[$x]['time'] = $val;
- $x++;
- }else{
- $user = xhUserService::getById($val);
- $callUserList[$x]['userId'] = $val;
- $callUserList[$x]['userName'] = $user['userName'];
- }
- }
- //只显示最近一分查看二维码的用户
- $nowTime = time();
- foreach($callUserList as $cuKey => $cuVal){
- $cuTime = $cuVal['time'];
- $cuUserId = $cuVal['userId'];
- if(($nowTime - $cuTime) > 120 ){
- unset($callUserList[$cuKey]);
- Yii::$app->redis->executeCommand('ZREM', ["merchant_{$merchantId}_new_call", "{$cuUserId}"]);
- }
- }
- }*/
- //新消息
- $newUserReturn = Yii::$app->redis->executeCommand('ZREVRANGE', ["merchant_{$merchantId}_new_msg", 0,-1, 'WITHSCORES']);
- $newUserList = [];
- if(!empty($newUserReturn)){
- $i = 0;
- $x = 0;
- foreach($newUserReturn as $key => $val){
- $i++;
- if($i%2 == 0){
- $newUserList[$x]['time'] = $val;
- $x++;
- }else{
- $user = xhUserService::getById($val);
- $newUserList[$x]['userId'] = $val;
- $newUserList[$x]['userName'] = $user['userName'];
- }
- }
- }
- $historyUserList = [];
- //最近联系人保留最近30天的,更早的删除
- $now = time();
- $maxTime = $now - 2592000;
- $historyUserReturn = Yii::$app->redis->executeCommand('ZREMRANGEBYSCORE', ["merchant_{$merchantId}_history_chat_user", 0,$maxTime]);
- //最近联系
- $historyUserReturn = Yii::$app->redis->executeCommand('ZREVRANGE', ["merchant_{$merchantId}_history_chat_user", 0,-1, 'WITHSCORES']);
- if(!empty($historyUserReturn)){
- $i = 0;
- $x = 0;
- foreach($historyUserReturn as $key => $val){
- $i++;
- if($i%2 == 0){
- $historyUserList[$x]['time'] = $val;
- $x++;
- }else{
- $user = xhUserService::getById($val);
- $historyUserList[$x]['userId'] = $val;
- $historyUserList[$x]['userName'] = $user['userName'];
- }
- }
- }
- echo Json::encode(['code' => 'A0001','msg' => '','data' => ['new' => $newUserList,'history' =>$historyUserList]]);
- }
- /**
- * 获取我的消息历史
- */
- public function actionGetMyHistory()
- {
- $get = Yii::$app->request->get();
- if(isset($get['customId']) == false || empty($get['customId'])){
- echo Json::encode(['code' => 'A0002','msg' => 'customId empty','data' => '']);
- Yii::$app->end();
- }
- $customId = $get['customId'];
- $merchantId = $this->merchantId;
- $get = Yii::$app->request->get();
- //历史消息保留全部
- $now = time();
- $conList = [];
- $return = Yii::$app->redis->executeCommand('ZRANGE', ["merchant_history_{$merchantId}_{$customId}",0,-1,'WITHSCORES']);
- $conList = [];
- if(!empty($return)){
- $i = 0;
- $x = 0;
- $list = [];
- foreach($return as $key => $val){
- $i++;
- if($i%2 == 0){
- $list[$x]['time'] = $val;
- $x++;
- }else{
- $list[$x]['content'] = $val;
- }
- }
- foreach($list as $key => $val){
- $time = $val['time'];
- $content = $val['content'];
- $arr = explode('{~CHAT~}',trim($content));
- if(count($arr) == 3){
- $createTime = date("Y-m-d H:i:s",$arr[0]);
- $msgBelongTo = $arr[1];
- $msg = $arr[2];
- $conArr = ['msgBelongTo' => $msgBelongTo,'content' => $msg,'createTime' =>$createTime];
- $conList[] = $conArr;
- }
- }
- }
- echo Json::encode(['code' => 'A0001','msg' => 'success','data' => $conList]);
- }
- public function actionUploadFile() {
- $fileInfo = array('url' => '');
- if (empty ( $_FILES )) {
- $fileInfo = ['code' => 'A0002','msg' => '没有图片资源上传'];
- echo Json::encode($fileInfo);
- Yii::$app->end();
- }
- $post = Yii::$app->request->post();
- $userId = isset($post['userId']) ? $post['userId'] : 0;
- $customId = isset($post['customId']) ? $post['customId'] : 0;
- $customInfo = xhUserService::getById($customId);
- $merchantId = $this->merchantId;
- $now = time();
- if(isset($customInfo['merchantId']) == false || $customInfo['merchantId'] != $merchantId){
- $fileInfo = ['code' => 'A0002','msg' => '聊天对象非法'];
- echo Json::encode($fileInfo);
- Yii::$app->end();
- }
- $preFileName = substr(md5($userId),-4);
- $fileName = $preFileName.stringUtil::buildOrderNo();
- $tempFile = $_FILES['Filedata']['tmp_name'];
- $fileParts = explode('.',$_FILES["Filedata"]['name']);
- $extName = $fileParts [1];
- $webRoot = Yii::getAlias('@webroot').'/../../images';
- $folder = '/weixinChat/'. date ('Y').'/'.date('m').'/'.date("d").'/';
- if (! file_exists ($webRoot.$folder))
- mkdir ($webRoot.$folder, 0777,true);
- $saveFile = $webRoot.$folder.$fileName.'.'.$extName;
- move_uploaded_file($tempFile, $saveFile);
- //生成300缩略图
- $dstImg300 = $webRoot.$folder.$fileName.'_300.'.$extName;
- $img2thumbReturn = util::img2thumb($saveFile, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
- $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
- $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
- //上传图片到微信
- $return = weixinUtil::uploadTempMedia($this->merchant,$saveFile);
- if(isset($return['errcode'])){
- $errCode = $return['errcode'];
- $errList = weixinUtil::$errCode;
- $msg = isset($errList[$errCode]) ? $errList[$errCode] : '{上传图片失败}';
- echo Json::encode(['code' => 'A0002','msg' => $msg,'data' => $data]);
- Yii::$app->end();
- }
- if(isset($return['media_id'])){
- $mediaId = $return['media_id'];
- $customOpenId = $customInfo['openId'];
- $r = weixinUtil::sendImgMsg($mediaId, $this->merchant,$customOpenId);
- if($r['errcode'] != 0){
- $errCode = $r['errcode'];
- $errList = weixinUtil::$errCode;
- $msg = isset($errList[$errCode]) ? $errList[$errCode] : '{发送消息失败}';
- echo Json::encode(['code' => 'A0002','msg' => $msg,'data' => $data]);
- Yii::$app->end();
- }
- $invalid = '/images/invalid.jpg';
- $content = '<img widthNum="'.$srcImgWidth.'" heightNum="'.$srcImgHeight.'" style="width:100px;height:auto;" onclick="previewImg(this)" onerror="javascript:this.src=\''.$invalid.'\'" src="'.$this->imgUrl.$folder.$fileName.'_300.'.$extName.'" bigImgSrc="'.$this->imgUrl.$folder.$fileName.'.'.$extName.'" />';
- //商家的历史消息
- Yii::$app->redis->executeCommand('ZADD', ["merchant_history_{$merchantId}_{$customId}", $now, $now.'{~CHAT~}ourself{~CHAT~}'.$content]);
- $createTime = date("Y-m-d H:i:s");
- $data = [
- 'msgBelongTo' => 'ourself',
- 'content' => $content,
- 'createTime' =>$createTime,
- 'imgUrl' => $folder.$fileName.'.'.$extName,
- 'imgPreUrl' =>$folder.$fileName,
- 'extName' =>'.'.$extName,
- ];
- echo Json::encode(['code' => 'A0001','msg' => 'success','data' => $data]);
- Yii::$app->end();
- }
- echo Json::encode(['code' => 'A0002','msg' => '操作没有成功……','data' => []]);
- }
- public function actionGetChatVoice()
- {
- $get = Yii::$app->request->get();
- $voiceId = isset($get['voiceId']) ? $get['voiceId'] : '';
- $return = weixinUtil::getTempMaterial($this->merchant, $voiceId);
- echo Json::encode($return);
- }
- }
|