| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666 |
- <?php
- namespace pt\controllers;
- use bizHd\admin\services\AdminService;
- use bizHd\coupon\services\CouponAssetService;
- use bizHd\user\classes\UserClass;
- use bizHd\user\services\UserService;
- use bizHd\wx\classes\WxBaseClass;
- use bizHd\wx\classes\WxOpenClass;
- use bizHd\wx\services\WxBaseService;
- use bizHd\wx\services\WxOpenService;
- use bizHd\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\dict;
- 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');
- }
- $wxSecret = Yii::getAlias("@vendor/weixinSecret");
- require_once($wxSecret . '/wxBizMsgCrypt.php');
- $appId = $get['appId'];//公众号appId
- $encryptMsg = $postData;
- //取开放平台信息
- $style = $get['style'] ?? \biz\wx\classes\WxOpenClass::OPEN_STYLE_HD;
- $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => $style]);
- if (empty($open)) {
- util::stop('没有找到平台信息');
- }
- //零售appId
- $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0;
- $wxBase = WxBaseService::getById($wxBaseId);
- $wxBaseAppId = isset($wxBase['wxAppId']) ? $wxBase['wxAppId'] : '';
- //供货商appId
- $wxBaseId = $open['wxBaseId'] ?? 0;
- $wxGhsBase = WxBaseClass::getById($wxBaseId);
- $wxGhsBaseAppId = $wxGhsBase['wxAppId'] ?? 0;
-
- $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['name'] . ",解密未成功,错误代码:" . $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); // 消息内容
-
- Yii::info('$wxBaseAppId:' . $wxBaseAppId . " $appId:" . $appId);
-
- if ($wxBaseAppId == $appId) {
- //零售
- if ($this->msgType == 'event') {
-
- switch ($Event) {
- //关注
- case 'subscribe':
- $merchant = WxOpenService::getWxInfo();
- $getUserInfo = wxUtil::userInfo($this->fromUsername, $merchant, 1);
- $source = UserClass::$userSourceId['official']['name'];
- $getUserInfo['subscribe'] = 1;
- AdminService::replaceAdmin($getUserInfo, $source);
- $text = $this->replyTextContent("等您好久,终于等到您 /::)");
- $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
- $encryptMsg = '';
- $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
- echo $encryptMsg;
- break;
- //取消关注
- case 'unsubscribe':
- $admin = AdminService::getByOpenId($this->fromUsername);
- if (!empty($admin)) {
- $adminId = $admin['id'];
- AdminService::unFocus($adminId);
- }
- break;
- default:
- }
- }
- } elseif ($wxGhsBaseAppId == $appId) {
- //供货商
- if ($this->msgType == 'event') {
- switch ($Event) {
- //关注
- case 'subscribe':
- $merchant = WxOpenClass::getGhsWxInfo();
- $getUserInfo = wxUtil::userInfo($this->fromUsername, $merchant, 1);
- $source = UserClass::$userSourceId['official']['name'];
- $getUserInfo['subscribe'] = 1;
- \bizGhs\admin\services\AdminService::replaceAdmin($getUserInfo, $source);
- $text = $this->replyTextContent("等您好久,终于等到您 /::)");
- $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
- $encryptMsg = '';
- $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
- echo $encryptMsg;
- break;
- //取消关注
- case 'unsubscribe':
- $admin = \bizGhs\admin\services\AdminService::getByOpenId($this->fromUsername);
- if (!empty($admin)) {
- $adminId = $admin['id'];
- \bizGhs\admin\services\AdminService::unFocus($adminId);
- }
- break;
- default:
- }
- }
- } else {
- //其它
- $merchant = xhMerchantService::getByAppId($appId);
- $account = 0;
- $sjId = 0;
- $merchantExtend = [];
- $now = time();
- if (!empty($merchant)) {
- $account = $merchant['id'];
- $sjId = $merchant['id'];
- $merchantExtend = xhMerchantExtendService::getByMerchantId($sjId);
- }
- $user = xhUserService::getByOpenId($this->fromUsername, $sjId);
- $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);//从微信接口获取用户信息
- if (!empty($getUserInfo)) {
- $source = UserClass::$userSourceId['official']['name'];
- $user = UserService::replaceUser($getUserInfo, $source, $sjId);
- $userId = $user['id'];
- UserService::focus($user, $merchant);
- //响应扫码的场景事件 ssh 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 = '';
- $text = $this->replyTextContent("等您好久,终于等到您 /::)");
- $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
- echo $encryptMsg;
-
- //获得新优惠券通知
- CouponAssetService::hasNewCouponNotice($user, $merchant);
-
-
- break;
- //取消关注
- case 'unsubscribe':
-
-
- UserService::unFocus($userId, $sjId);
-
-
- break;
- //自定义菜单回复
- case 'click':
- $menuKey = $EventKey;
- $menu = xhWxMenuService::getByMenuKey($menuKey);
- $wxMenuOption = $menu['menuOption'];
- $wxMenuOptionList = dict::getDict('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':
- //响应扫码的场景事件 ssh 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,'xxxxxxxxxxxx');
- //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_{$sjId}_new_msg_last_time";//最后一次会话时间key
- //将消息内容转发到管理员微信上
- //$admin = xhAdminToMerchantService::getAdminByMerchantId($sjId);
- $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' => $sjId,//商家id
- 'chatLogKey' => "merchant_history_{$sjId}_{$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_{$sjId}_{$userId}", $now.'{~CHAT~}themself{~CHAT~}'.$Content]);*/
- //util::end();
- }
-
- //给客户微信返回(打开聊天界面的模板消息通知)
- $userTest = false;
- if (!empty($userTest)) {
- $userOpenId = $user['openId'];
-
- $allTM = xhTMessageService::getList($sjId);
- $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("^_^");
- $text = $this->replyTextContent(Yii::$app->params['mallDomain'] . '/#/?account=' . $sjId);
- $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_{$sjId}_new_msg_last_time"]);
- if (empty($connect) || ($now - $connect) > 100) {
- $allTM = xhTMessageService::getList($sjId);
- $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_{$sjId}_new_msg", $now, "{$userId}"]);
- //记录商家的最近联系人
- Yii::$app->redis->executeCommand('ZADD', ["merchant_{$sjId}_history_chat_user", $now, "{$userId}"]);
- //设置商家与用户最后一次会话时间。
- Yii::$app->redis->executeCommand('SETEX', ["merchant_{$sjId}_new_msg_last_time", 100, $now]);
- //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
- Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$sjId}_{$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("没有管理员,sjId:" . $sjId);
- util::end();
- }
- $adminOpenId = $admin['openId'];
- $adminId = $admin['id'];
- //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
- $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$sjId}_new_msg_last_time"]);
- if (empty($connect) || ($now - $connect) > 100) {
- $allTM = xhTMessageService::getList($sjId);
- $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_{$sjId}_new_msg", $now, "{$userId}"]);
- //记录商家的最近联系人
- Yii::$app->redis->executeCommand('ZADD', ["merchant_{$sjId}_history_chat_user", $now, "{$userId}"]);
- //设置商家与用户最后一次会话时间。
- Yii::$app->redis->executeCommand('SETEX', ["merchant_{$sjId}_new_msg_last_time", 100, $now]);
- //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
- Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$sjId}_{$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;
- }
- }
|