shish 6 lat temu
rodzic
commit
b063db1fa0

+ 581 - 0
app/saas/controllers/WxController.php

@@ -0,0 +1,581 @@
+<?php
+
+namespace saas\controllers;
+
+use biz\user\classes\UserClass;
+use biz\user\services\UserService;
+use biz\wx\services\WxSceneService;
+use Yii;
+use common\services\xhMerchantExtendService;
+use common\services\xhShopService;
+use common\services\xhWxMenuService;
+use common\services\xhAdminService;
+use common\services\xhUserAssetService;
+use common\services\xhWxOpenService;
+use common\components\wxUtil;
+use common\components\configDict;
+use common\components\stringUtil;
+use common\components\util;
+use common\services\xhMerchantService;
+use common\services\xhUserService;
+use common\services\xhTMessageService;
+use linslin\yii2\curl;
+
+/**
+ * 微信公众号相关
+ */
+class WxController extends PublicController
+{
+
+    public $fromUsername, $toUsername, $msgType;
+
+    /**
+     * 首页入口地址
+     */
+    public function actionApi()
+    {
+        $postData = file_get_contents('php://input');
+        if (isset ($postData) == false || empty($postData)) {
+            util::stop('没有接收到POST数据');
+        }
+        $get = Yii::$app->request->get();
+        if (isset($get['appId']) == false || empty($get['appId'])) {
+            util::stop('没有取到公众号的appId');
+        }
+        $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
+        require_once($weixinSecret . '/wxBizMsgCrypt.php');
+        $appId = $get['appId'];//公众号appId
+        $encryptMsg = $postData;
+        //取开放平台信息
+        $openId = configDict::getConfig('openId');
+        $open = xhWxOpenService::getById($openId);
+        $encodingAesKey = $open['aesKey'];
+        $openToken = $open['token'];
+        $openAppId = $open['appId'];
+        $signature = isset($get['signature']) ? $get['signature'] : '';
+        $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';//签名串,对应URL参数的msg_signature
+        $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
+        $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
+        $nonce = isset($get['nonce']) ? $get['nonce'] : '';
+        $xml_tree = new \DOMDocument();
+        $xml_tree->loadXML($encryptMsg);
+        $array_e = $xml_tree->getElementsByTagName('Encrypt');
+        $encrypt = $array_e->item(0)->nodeValue;
+        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
+        $from_xml = sprintf($format, $encrypt);
+
+        //签名串,对应URL参数的msg_signature -- (接收微信传过来的加密会出问题,故只在自己测试时打开以下注释)
+        /*$array_s = $xml_tree->getElementsByTagName('MsgSignature');
+        $msg_sign = $array_s->item(0)->nodeValue;
+        if($msg_signature == ''){
+            $msg_signature = $msg_sign;
+        }*/
+
+        // 第三方收到公众号平台发送的消息
+        $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+        $msg = '';//解密后的消息
+        $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);//解密
+        if ($errCode != 0) {
+            $errMsg = '商户:' . $open['openName'] . ",解密未成功,错误代码:" . $errCode;
+            Yii::warning($errMsg, __METHOD__);
+            Yii::$app->end();
+        }
+        $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
+        $this->fromUsername = $postObj->FromUserName; // 发送方账号 openId
+        $this->toUsername = $postObj->ToUserName; // 开发者微信账号
+        $times = $postObj->CreateTime; // 消息创建时间
+        $Location_X = $postObj->Location_X; // 地理位置纬度(用户主动发送)
+        $Location_Y = $postObj->Location_Y; // 地理位置经度(用户主动发送)
+        $Scale = $postObj->Scale; // 地图缩放大小(用户主动发送)
+        $Label = $postObj->Label; // 地理位置信息(用户主动发送)
+        $PicUrl = $postObj->PicUrl; // 图片链接
+        $this->msgType = $postObj->MsgType; // 消息类型
+        $MsgId = $postObj->MsgId; // 消息ID
+        $Url = $postObj->Url; // 消息链接
+        $Event = strtolower($postObj->Event); // 事件类型
+        $EventKey = $postObj->EventKey; // 事件KEY值
+        $ticket = $postObj->Ticket;//扫描二维码的TICKET
+        $Latitude = $postObj->Latitude; // 地理位置纬度(自动获取)
+        $Longitude = $postObj->Longitude;//地理位置经度(自动获取)
+        $Precision = $postObj->Precision;//地理位置精度(自动获取)
+        $MediaId = $postObj->MediaId;//图片媒体id
+        $Content = trim($postObj->Content); // 消息内容
+        $merchant = xhMerchantService::getByAppId($appId);
+        $account = 0;
+        $merchantId = 0;
+        $merchantExtend = [];
+        $now = time();
+        if (!empty($merchant)) {
+            $account = $merchant['id'];
+            $merchantId = $merchant['id'];
+            $merchantExtend = xhMerchantExtendService::getByMerchantId($merchantId);
+        }
+        $user = xhUserService::getByOpenId($this->fromUsername, $merchantId);
+        $userId = 0;
+        $userAsset = [];
+        if (!empty($user)) {
+            $userId = $user['id'];
+            $userAsset = xhUserAssetService::getByUserId($userId);
+        }
+        if ($this->msgType == 'event') {
+            /*
+                        //全网发布,1 事件消息响应
+                        $content = $postObj->Event."from_callback";
+                        $createTime = time (); // 响应当前时间
+                        $type = "text";
+                        $text = "<xml>
+                        <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
+                        <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
+                        <CreateTime>{$createTime}</CreateTime>
+                        <MsgType><![CDATA[{$type}]]></MsgType>
+                        <Content><![CDATA[{$content}]]></Content>
+                        </xml>";
+                        $pc									= new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                        $encryptMsg							= '';
+                        $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
+                        echo $encryptMsg;
+                        Yii::$app->end();
+            */
+            switch ($Event) {
+                //关注
+                case 'subscribe':
+                    $getUserInfo = wxUtil::userInfo($this->fromUsername, $merchant);//从微信接口获取用户信息
+                    $source = UserClass::$userSourceId['official']['name'];
+                    Yii::info('关注公众号,获得用户信息:' . json_encode($getUserInfo));
+                    $user = UserService::replaceUser($getUserInfo, $source, $merchantId);
+                    $userId = $user['id'];
+                    $text = $this->replyTextContent("等您好久,终于等到您~\n\n注册会员享折扣哦,<a href='" . Yii::$app->params['frontUrl'] . "/center/right?account={$merchant['id']}'>详情</a>");
+                    if ($merchant['merchantName'] == '花卉宝') {
+                        $text = $this->replyTextContent("等您好久,终于等到您 /::)");
+                    }
+
+                    //响应扫码的场景事件 shish 2019.9.5
+                    if (strstr($EventKey, 'qrscene_')) {
+                        Yii::info($EventKey);
+                        $sceneId = str_replace('qrscene_', '', $EventKey);
+                        WxSceneService::respondScanEvent($merchant, $user, (string)$sceneId);
+                    }
+
+                    $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                    $encryptMsg = '';
+                    $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
+                    echo $encryptMsg;
+
+                    $admin = xhAdminService::getByOpenId($this->fromUsername);
+                    if (!empty($admin)) {
+                        $adminId = $admin['id'];
+                        xhAdminService::updateById($adminId, ['subscribe' => 1]);
+                    }
+
+                    break;
+                //取消关注
+                case 'unsubscribe':
+                    UserService::unFocus($userId, $merchantId);
+                    break;
+                //自定义菜单回复
+                case 'click':
+                    $menuKey = $EventKey;
+                    $menu = xhWxMenuService::getByMenuKey($menuKey);
+                    $wxMenuOption = $menu['menuOption'];
+                    $wxMenuOptionList = configDict::getConfig('wxMenuOption');
+                    switch ($wxMenuOption) {
+                        case $wxMenuOptionList['showText']://链接到-文字
+                            $replyContent = $menu['replyText'];
+                            $text = $this->replyTextContent($replyContent);
+                            $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                            $encryptMsg = '';
+                            $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
+                            echo $encryptMsg;
+                            break;
+                        default:
+                    }
+                    break;
+
+                //门店申请
+                case 'poi_check_notify':
+                    if ($postObj->Result == 'succ') {
+                        $shop['status'] = 2;
+                        xhShopService::updateByPoiId($postObj->PoiId, $shop);
+                        Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
+                    } elseif ($postObj->Result == 'fail') {
+                        $shop['status'] = 4;
+                        xhShopService::updateByPoiId($postObj->PoiId, $shop);
+                        Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核失败: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
+                    } else {
+                        Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核异常记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
+                        throw new \Exception('微信门店申请返回异常');
+                    }
+                    break;
+
+                case 'view':
+                    break;
+                case 'scan':
+                    //响应扫码的场景事件 shish 2019.9.5
+                    Yii::info('a' . $EventKey);
+
+                    WxSceneService::respondScanEvent($merchant, $user, (string)$EventKey);
+                    break;
+                default:
+                    Yii::warning("该EVENT类型未定义,EVENT:" . $Event);
+            }
+
+        } elseif ($this->msgType == 'text') {
+            /*
+                        //全网发布,3 api客服接口回应
+                        if(strpos($Content,'QUERY_AUTH_CODE:') !== false){
+                            //返回空字符,表示暂不回复
+                            $content	= "";
+                            $FuncFlag = 0;
+                            $type	= "text";
+                            $createTime = time (); // 响应当前时间
+                            $text = "<xml>
+                            <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
+                            <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
+                            <CreateTime>{$createTime}</CreateTime>
+                            <MsgType><![CDATA[{$type}]]></MsgType>
+                            <Content><![CDATA[{$content}]]></Content>
+                            </xml>";
+                            $pc					= new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                            $encryptMsg			= '';
+                            $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
+                            echo $encryptMsg;
+
+                            $ticket = str_replace('QUERY_AUTH_CODE:','',$Content);
+                            $authorizer = wxUtil::getAuthorizer($ticket);
+                            //Yii::warning("authorizer:".json_encode($authorizer));
+                            $info 							= $authorizer['authorization_info'];
+                            $authorizer_appid				= $info['authorizer_appid'];
+                            $authorizer_access_token		= $info['authorizer_access_token'];
+                            //Yii::warning("authorizer_access_token:".$authorizer_access_token);
+                            $url		= "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$authorizer_access_token}";
+                            $con		= $ticket."_from_api";
+                            $data		= ["touser" => "{$this->fromUsername}","msgtype" => "text","text"=>["content" => $con]];
+                            $curl		= new curl\Curl();
+                            $result		= $curl->setOption(CURLOPT_POSTFIELDS,json_encode($data))->post($url);
+                            $result		= Json::decode($result);
+                            //Yii::warning("fromUsername:".$this->fromUsername.' toUsername:'.$this->toUsername);
+                            //Yii::warning(" ticket: ~ ".$ticket.' | json:'.json_encode($result),__METHOD__);
+                            Yii::$app->end();
+                        }
+
+                        switch($Content){
+                             //全网发布,2 发送文本消息
+                            case 'TESTCOMPONENT_MSG_TYPE_TEXT':
+                            $content	= "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
+                            $FuncFlag = 0;
+                            $type	= "text";
+                            $createTime = time ();
+                            $text = "<xml>
+                            <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
+                            <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
+                            <CreateTime>{$createTime}</CreateTime>
+                            <MsgType><![CDATA[{$type}]]></MsgType>
+                            <Content><![CDATA[{$content}]]></Content>
+                            </xml>";
+                            $pc					= new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                            $encryptMsg			= '';
+                            $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);
+                            echo $encryptMsg;
+                            break;
+
+                    }
+            */
+            $adminSendMsg = false;
+            $openMerchant = xhWxOpenService::getMerchant();
+            $openMerchantId = $openMerchant['id'];
+
+            if ($adminSendMsg == false) {
+                $lastTimeKey = "customer_{$userId}:merchant_{$merchantId}_new_msg_last_time";//最后一次会话时间key
+                //将消息内容转发到管理员微信上
+                //$admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
+                $admin = [];
+                if (!empty($admin)) {
+                    $adminOpenId = $admin['openId'];
+                    $adminId = $admin['id'];
+                    //获取最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
+                    $connect = Yii::$app->redis->executeCommand('GET', [$lastTimeKey]);
+                    if (empty($connect) || ($now - $connect) >= 100) {
+                        $allTM = xhTMessageService::getList($openMerchantId);
+                        $shortTempId = 'OPENTM200605630';
+                        if (isset($allTM[$shortTempId])) {
+                            $tempId = $allTM[$shortTempId];
+                            $data = [
+                                "touser" => $adminOpenId,
+                                "template_id" => $tempId,
+                                "url" => Yii::$app->params['adminUrl'] . "/chat/index?customId=" . $userId,
+                                "data" => ["first" => ["value" => "{$user['userName']} 向您的公众号发来新消息", "color" => "#173177"],
+                                    "keyword1" => ["value" => '新消息', "color" => "#173177"],
+                                    "keyword2" => ["value" => '文字', "color" => "#173177"],
+                                    "remark" => ["value" => '点击查看详情', "color" => "#173177"]
+                                ]
+                            ];
+                            wxUtil::sendTaskInform($data, $openMerchant);
+                        }
+                        //设置商家与用户最后一次会话时间。
+                        Yii::$app->redis->executeCommand('SET', [$lastTimeKey, $now]);
+                        Yii::$app->redis->executeCommand('EXPIRE', [$lastTimeKey, 100]);//过期
+                    }
+
+                    //swoole:商家是否在线
+                    $customId = $userId;//客户uid
+                    xhUserService::getById($customId);//把客户用户数据存入缓存,预防清缓存,取不到客户数据
+
+                    //在线,通过socket给商家发消息
+                    define('WEBPATH', __DIR__);
+                    define('ROOT_PATH', __DIR__);
+                    //Swoole框架自动载入器初始化
+//					\Swoole\Loader::vendorInit();
+//					$serverIp = util::serverIP();
+//					$client = new \Swoole\Client\WebSocket($serverIp, 9503, '/');
+//					if (!$client->connect()) {
+//						echo "connect to server failed.\n";
+//						exit;
+//					}
+                    //from: 客户的clientId(无); to:商家的clientId
+                    $sendData = [
+                        'cmd' => 'sendMsgC2M',
+                        'from' => -1,//可能未在线
+                        'to' => 0,
+                        'uid' => $customId,//客户id
+                        'chatUid' => $merchantId,//商家id
+                        'chatLogKey' => "merchant_history_{$merchantId}_{$customId}",//消息记录缓存key
+                        'channal' => 1,
+                        'data' => $Content,
+                        'type' => 'text'
+                    ];
+
+//					$client->send(json_encode($sendData));
+                    //$message = $client->recv();
+
+
+                    //表情替换
+                    /*$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();
+                }
+
+                //给客户微信返回(打开聊天界面的模板消息通知)
+                $userTest = false;
+                if (!empty($userTest)) {
+                    $userOpenId = $user['openId'];
+
+                    $allTM = xhTMessageService::getList($merchantId);
+                    $shortTempId = 'OPENTM200605630';
+                    if (isset($allTM[$shortTempId])) {
+                        $tempId = $allTM[$shortTempId];
+                        $data = [
+                            "touser" => $userOpenId,
+                            "template_id" => $tempId,
+                            "url" => Yii::$app->params['frontUrl'] . "/chat/index?account=" . $account,
+                            "data" => ["first" => ["value" => "亲,有什么需要可以帮到您,点此联系客服。", "color" => "#173177"],
+                                "keyword1" => ["value" => '前往聊天页', "color" => "#173177"],
+                                "keyword2" => ["value" => '文字', "color" => "#173177"],
+                                "remark" => ["value" => '点击与客服聊天', "color" => "#173177"]
+                            ]
+                        ];
+                        wxUtil::sendTaskInform($data, $merchant);
+                    }
+                    util::end();
+                }
+                $text = $this->replyTextContent("^_^");//没有管理员返回的信息
+                $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
+                $encryptMsg = '';
+                $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
+                echo $encryptMsg;
+
+            }
+
+        } elseif ($this->msgType == 'image') {
+            $PicUrl = (string)$PicUrl;
+            if (empty($PicUrl)) {
+                util::end();
+            }
+            $folder = Yii::getAlias('@webroot') . '/../../images';
+            $pre = '/weixinChat/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
+            if (!file_exists($folder . $pre)) {
+                mkdir($folder . $pre, 0777, true);
+            }
+            $preFileName = substr(md5($userId), -4);
+            $preName = $preFileName . stringUtil::buildOrderNo();
+            $extName = '.jpg';
+            $name = $preName . $extName;
+            $fullFileName = $folder . $pre . $name;
+            $fileName = $pre . $name;
+            $curl = new curl\Curl();
+            $result = $curl->get($PicUrl);
+            $fp2 = @fopen($fullFileName, 'a');//文件大小
+            fwrite($fp2, $result);
+            fclose($fp2);
+            //生成300缩略图
+            $dstImg300 = $folder . $pre . $preName . '_300.' . $extName;
+            $img2thumbReturn = util::img2thumb($fullFileName, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
+            $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
+            $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
+            $invalid = '/images/invalid.jpg';
+            $Content = '<img onclick="previewImg(this)" onerror="javascript:this.src=\'' . $invalid . '\'" src="' . $this->imgUrl . $pre . $preName . '_300.' . $extName . '" bigImgSrc="' . $this->imgUrl . $pre . $preName . $extName . '" widthNum="' . $srcImgWidth . '" heightNum="' . $srcImgHeight . '" style="width:100px;height:auto;"  />';
+            //将图片转发到管理员微信上
+            $adminId = $merchant['adminId'];
+            $admin = xhAdminService::getById($adminId);
+            if (empty($admin)) {
+                util::stop('没有管理员');
+            }
+            $adminOpenId = $admin['openId'];
+            $adminId = $admin['id'];
+            //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
+            $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
+            if (empty($connect) || ($now - $connect) > 100) {
+                $allTM = xhTMessageService::getList($merchantId);
+                $shortTempId = 'OPENTM200605630';
+                if (isset($allTM[$shortTempId])) {
+                    $tempId = $allTM[$shortTempId];
+                    $data = [
+                        "touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
+                        "data" => ["first" => ["value" => "{$user['userName']} 发来图片", "color" => "#173177"],
+                            "keyword1" => ["value" => '新消息', "color" => "#173177"],
+                            "keyword2" => ["value" => '图片', "color" => "#173177"],
+                            "remark" => ["value" => '请登陆后台查看', "color" => "#173177"]]];
+                    wxUtil::sendTaskInform($data, $merchant);
+                }
+            }
+            //记录商家的新消息用户有谁。
+            Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
+            //记录商家的最近联系人
+            Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
+            //设置商家与用户最后一次会话时间。
+            Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
+            //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
+            Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
+        } elseif ($this->msgType == 'voice') {
+            $Content = '<span voiceId="' . $MediaId . '">【提示】客户发来一条语音消息,请登陆微信公众号后台查看。</span>';
+            $adminId = $merchant['adminId'];
+            $admin = xhAdminService::getById($adminId);
+            if (empty($admin)) {
+                Yii::warning("没有管理员,merchantId:" . $merchantId);
+                util::end();
+            }
+            $adminOpenId = $admin['openId'];
+            $adminId = $admin['id'];
+            //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
+            $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
+            if (empty($connect) || ($now - $connect) > 100) {
+                $allTM = xhTMessageService::getList($merchantId);
+                $shortTempId = 'OPENTM200605630';
+                if (isset($allTM[$shortTempId])) {
+                    $tempId = $allTM[$shortTempId];
+                    $data = ["touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
+                        "data" => [
+                            "first" => ["value" => "{$user['userName']} 发来语音", "color" => "#173177"],
+                            "keyword1" => ["value" => '新消息', "color" => "#173177"],
+                            "keyword2" => ["value" => '语音', "color" => "#173177"],
+                            "remark" => ["value" => '消息内容:请登陆后台查看', "color" => "#173177"]]];
+                    wxUtil::sendTaskInform($data, $merchant);
+                }
+            }
+            //记录商家的新消息用户有谁。
+            Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
+            //记录商家的最近联系人
+            Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
+            //设置商家与用户最后一次会话时间。
+            Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
+            //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
+            Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
+        } elseif ($this->msgType == 'video') {
+
+        } elseif ($this->msgType == 'location') {
+
+        } elseif ($this->msgType == 'link') {
+
+        } else {
+
+        }
+    }
+
+    /**
+     * 回复文字消息
+     */
+    private function replyTextContent($content)
+    {
+        $createTime = time();//响应当前时间
+        $con = "<xml>
+		<ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
+		<FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
+		<CreateTime>{$createTime}</CreateTime>
+		<MsgType><![CDATA[text]]></MsgType>
+		<Content><![CDATA[{$content}]]></Content>
+		</xml>";
+        return $con;
+    }
+
+    /**
+     * 回复图片消息
+     */
+    private function replyPicContent($media_id)
+    {
+        $createTime = time();
+        $con = "<xml>
+        <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
+        <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
+        <CreateTime>{$createTime}</CreateTime>
+        <MsgType><![CDATA[image]]></MsgType>
+        <Image>
+        <MediaId><![CDATA[{$media_id}]]></MediaId>
+        </Image>
+        </xml>";
+        return $con;
+    }
+
+    /**
+     * 回复单图文消息
+     */
+    private function replyNewsContent($title, $desc, $picUrl, $url)
+    {
+        $createTime = time();//响应当前时间
+        $con = "<xml>
+		<ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
+		<FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
+		<CreateTime>{$createTime}</CreateTime>
+		<MsgType><![CDATA[news]]></MsgType>
+		<ArticleCount>1</ArticleCount><Articles>
+		<item>
+			<Title><![CDATA[{$title}]]></Title>
+			<Description><![CDATA[{$desc}]]></Description>
+			<PicUrl><![CDATA[{$picUrl}]]></PicUrl>
+			<Url><![CDATA[{$url}]]></Url>
+		</item>
+		</Articles></xml>";
+        return $con;
+    }
+
+    /**
+     * 回复视频消息
+     * @param $title
+     * @param $media_id
+     * @param $description
+     * @return string
+     */
+    private function replyVideoContent($title, $media_id, $description)
+    {
+
+        $createTime = time();//响应当前时间
+        $con = "<xml>
+        <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
+        <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
+        <CreateTime>{$createTime}</CreateTime>
+        <MsgType><![CDATA[video]]></MsgType>
+        <Video>
+        <MediaId><![CDATA[{$media_id}]]></MediaId>
+        <Title><![CDATA[{$title}]]></Title>
+        <Description><![CDATA[{$description}]]></Description>
+        </Video> 
+        </xml>";
+
+        return $con;
+    }
+}

+ 1 - 1
app/saas/controllers/WxOpenController.php

@@ -20,7 +20,7 @@ use common\services\xhInviteService;
 use common\components\configDict;
 use common\services\xhWxOpenService;
 
-class WxOpenController extends BaseController
+class WxOpenController extends PublicController
 {
 
     public $withoutLogin = ['bind-open'];