WxController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. namespace open\controllers;
  3. use biz\promote\services\GuaGuaService;
  4. use biz\user\classes\UserClass;
  5. use biz\user\services\UserService;
  6. use biz\weixin\services\WxSceneService;
  7. use Yii;
  8. use common\services\xhCouponService;
  9. use common\services\xhMerchantExtendService;
  10. use common\services\xhShopService;
  11. use common\services\xhWxMenuService;
  12. use common\services\xhAdminService;
  13. use common\services\xhUserAssetService;
  14. use common\services\xhWxOpenService;
  15. use common\components\wxUtil;
  16. use common\components\configDict;
  17. use common\components\stringUtil;
  18. use common\components\util;
  19. use common\services\xhMerchantService;
  20. use common\services\xhUserService;
  21. use common\services\xhTMessageService;
  22. use linslin\yii2\curl;
  23. use common\services\xhAdminToMerchantService;
  24. use common\components\qqFaceUtil;
  25. /**
  26. * 微信公众号相关
  27. */
  28. class WxController extends PublicController
  29. {
  30. public $fromUsername, $toUsername, $msgType;
  31. /**
  32. * 首页入口地址
  33. */
  34. public function actionApi()
  35. {
  36. $postData = file_get_contents('php://input');
  37. if (isset ($postData) == false || empty($postData)) {
  38. util::stop('没有接收到POST数据');
  39. }
  40. $get = Yii::$app->request->get();
  41. if (isset($get['appId']) == false || empty($get['appId'])) {
  42. util::stop('没有取到公众号的appId');
  43. }
  44. $weixinSecret = Yii::getAlias("@vendor/weixinSecret");
  45. require_once($weixinSecret . '/wxBizMsgCrypt.php');
  46. $appId = $get['appId'];//公众号appId
  47. $encryptMsg = $postData;
  48. //取开放平台信息
  49. $openId = configDict::getConfig('openId');
  50. $open = xhWxOpenService::getById($openId);
  51. $encodingAesKey = $open['aesKey'];
  52. $openToken = $open['token'];
  53. $openAppId = $open['appId'];
  54. $signature = isset($get['signature']) ? $get['signature'] : '';
  55. $encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';//签名串,对应URL参数的msg_signature
  56. $msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
  57. $timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
  58. $nonce = isset($get['nonce']) ? $get['nonce'] : '';
  59. $xml_tree = new \DOMDocument();
  60. $xml_tree->loadXML($encryptMsg);
  61. $array_e = $xml_tree->getElementsByTagName('Encrypt');
  62. $encrypt = $array_e->item(0)->nodeValue;
  63. $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
  64. $from_xml = sprintf($format, $encrypt);
  65. //签名串,对应URL参数的msg_signature -- (接收微信传过来的加密会出问题,故只在自己测试时打开以下注释)
  66. /*$array_s = $xml_tree->getElementsByTagName('MsgSignature');
  67. $msg_sign = $array_s->item(0)->nodeValue;
  68. if($msg_signature == ''){
  69. $msg_signature = $msg_sign;
  70. }*/
  71. // 第三方收到公众号平台发送的消息
  72. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  73. $msg = '';//解密后的消息
  74. $errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);//解密
  75. if ($errCode != 0) {
  76. $errMsg = '商户:' . $open['openName'] . ",解密未成功,错误代码:" . $errCode;
  77. Yii::warning($errMsg, __METHOD__);
  78. Yii::$app->end();
  79. }
  80. $postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
  81. $this->fromUsername = $postObj->FromUserName; // 发送方账号 openId
  82. $this->toUsername = $postObj->ToUserName; // 开发者微信账号
  83. $times = $postObj->CreateTime; // 消息创建时间
  84. $Location_X = $postObj->Location_X; // 地理位置纬度(用户主动发送)
  85. $Location_Y = $postObj->Location_Y; // 地理位置经度(用户主动发送)
  86. $Scale = $postObj->Scale; // 地图缩放大小(用户主动发送)
  87. $Label = $postObj->Label; // 地理位置信息(用户主动发送)
  88. $PicUrl = $postObj->PicUrl; // 图片链接
  89. $this->msgType = $postObj->MsgType; // 消息类型
  90. $MsgId = $postObj->MsgId; // 消息ID
  91. $Url = $postObj->Url; // 消息链接
  92. $Event = strtolower($postObj->Event); // 事件类型
  93. $EventKey = $postObj->EventKey; // 事件KEY值
  94. $ticket = $postObj->Ticket;//扫描二维码的TICKET
  95. $Latitude = $postObj->Latitude; // 地理位置纬度(自动获取)
  96. $Longitude = $postObj->Longitude;//地理位置经度(自动获取)
  97. $Precision = $postObj->Precision;//地理位置精度(自动获取)
  98. $MediaId = $postObj->MediaId;//图片媒体id
  99. $Content = trim($postObj->Content); // 消息内容
  100. $merchant = xhMerchantService::getByAppId($appId);
  101. $account = 0;
  102. $merchantId = 0;
  103. $merchantExtend = [];
  104. $now = time();
  105. if (!empty($merchant)) {
  106. $account = $merchant['id'];
  107. $merchantId = $merchant['id'];
  108. $merchantExtend = xhMerchantExtendService::getByMerchantId($merchantId);
  109. }
  110. $user = xhUserService::getByOpenId($this->fromUsername, $merchantId);
  111. $userId = 0;
  112. $userAsset = [];
  113. if (!empty($user)) {
  114. $userId = $user['id'];
  115. $userAsset = xhUserAssetService::getByUserId($userId);
  116. }
  117. if ($this->msgType == 'event') {
  118. /*
  119. //全网发布,1 事件消息响应
  120. $content = $postObj->Event."from_callback";
  121. $createTime = time (); // 响应当前时间
  122. $type = "text";
  123. $text = "<xml>
  124. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  125. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  126. <CreateTime>{$createTime}</CreateTime>
  127. <MsgType><![CDATA[{$type}]]></MsgType>
  128. <Content><![CDATA[{$content}]]></Content>
  129. </xml>";
  130. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  131. $encryptMsg = '';
  132. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  133. echo $encryptMsg;
  134. Yii::$app->end();
  135. */
  136. switch ($Event) {
  137. //关注
  138. case 'subscribe':
  139. $getUserInfo = wxUtil::userInfo($this->fromUsername, $merchant);//从微信接口获取用户信息
  140. $source = UserClass::$userSourceId['official']['name'];
  141. Yii::info('关注公众号,获得用户信息:' . json_encode($getUserInfo));
  142. $user = UserService::replaceUser($getUserInfo, $source, $merchantId);
  143. $userId = $user['id'];
  144. $text = $this->replyTextContent("等您好久,终于等到您~\n\n注册会员享折扣哦,<a href='" . Yii::$app->params['frontUrl'] . "/center/right?account={$merchant['id']}'>详情</a>");
  145. if ($merchant['merchantName'] == '花卉宝') {
  146. $text = $this->replyTextContent("等您好久,终于等到您 /::)");
  147. }
  148. //响应扫码的场景事件 shish 2019.9.5
  149. if (strstr($EventKey, 'qrscene_')) {
  150. Yii::info($EventKey);
  151. $sceneId = str_replace('qrscene_', '', $EventKey);
  152. WxSceneService::respondScanEvent($merchant, $user, (string)$sceneId);
  153. }
  154. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  155. $encryptMsg = '';
  156. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  157. echo $encryptMsg;
  158. $admin = xhAdminService::getByOpenId($this->fromUsername);
  159. if (!empty($admin)) {
  160. $adminId = $admin['id'];
  161. xhAdminService::updateById($adminId, ['subscribe' => 1]);
  162. }
  163. break;
  164. //取消关注
  165. case 'unsubscribe':
  166. UserService::unFocus($userId, $merchantId);
  167. break;
  168. //自定义菜单回复
  169. case 'click':
  170. $menuKey = $EventKey;
  171. $menu = xhWxMenuService::getByMenuKey($menuKey);
  172. $wxMenuOption = $menu['menuOption'];
  173. $wxMenuOptionList = configDict::getConfig('wxMenuOption');
  174. switch ($wxMenuOption) {
  175. case $wxMenuOptionList['showText']://链接到-文字
  176. $replyContent = $menu['replyText'];
  177. $text = $this->replyTextContent($replyContent);
  178. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  179. $encryptMsg = '';
  180. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  181. echo $encryptMsg;
  182. break;
  183. default:
  184. }
  185. break;
  186. //门店申请
  187. case 'poi_check_notify':
  188. if ($postObj->Result == 'succ') {
  189. $shop['status'] = 2;
  190. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  191. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  192. } elseif ($postObj->Result == 'fail') {
  193. $shop['status'] = 4;
  194. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  195. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核失败: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  196. } else {
  197. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核异常记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  198. throw new \Exception('微信门店申请返回异常');
  199. }
  200. break;
  201. case 'view':
  202. break;
  203. case 'scan':
  204. //响应扫码的场景事件 shish 2019.9.5
  205. Yii::info('a' . $EventKey);
  206. WxSceneService::respondScanEvent($merchant, $user, (string)$EventKey);
  207. break;
  208. default:
  209. Yii::warning("该EVENT类型未定义,EVENT:" . $Event);
  210. }
  211. } elseif ($this->msgType == 'text') {
  212. /*
  213. //全网发布,3 api客服接口回应
  214. if(strpos($Content,'QUERY_AUTH_CODE:') !== false){
  215. //返回空字符,表示暂不回复
  216. $content = "";
  217. $FuncFlag = 0;
  218. $type = "text";
  219. $createTime = time (); // 响应当前时间
  220. $text = "<xml>
  221. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  222. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  223. <CreateTime>{$createTime}</CreateTime>
  224. <MsgType><![CDATA[{$type}]]></MsgType>
  225. <Content><![CDATA[{$content}]]></Content>
  226. </xml>";
  227. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  228. $encryptMsg = '';
  229. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  230. echo $encryptMsg;
  231. $ticket = str_replace('QUERY_AUTH_CODE:','',$Content);
  232. $authorizer = wxUtil::getAuthorizer($ticket);
  233. //Yii::warning("authorizer:".json_encode($authorizer));
  234. $info = $authorizer['authorization_info'];
  235. $authorizer_appid = $info['authorizer_appid'];
  236. $authorizer_access_token = $info['authorizer_access_token'];
  237. //Yii::warning("authorizer_access_token:".$authorizer_access_token);
  238. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$authorizer_access_token}";
  239. $con = $ticket."_from_api";
  240. $data = ["touser" => "{$this->fromUsername}","msgtype" => "text","text"=>["content" => $con]];
  241. $curl = new curl\Curl();
  242. $result = $curl->setOption(CURLOPT_POSTFIELDS,json_encode($data))->post($url);
  243. $result = Json::decode($result);
  244. //Yii::warning("fromUsername:".$this->fromUsername.' toUsername:'.$this->toUsername);
  245. //Yii::warning(" ticket: ~ ".$ticket.' | json:'.json_encode($result),__METHOD__);
  246. Yii::$app->end();
  247. }
  248. switch($Content){
  249. //全网发布,2 发送文本消息
  250. case 'TESTCOMPONENT_MSG_TYPE_TEXT':
  251. $content = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
  252. $FuncFlag = 0;
  253. $type = "text";
  254. $createTime = time ();
  255. $text = "<xml>
  256. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  257. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  258. <CreateTime>{$createTime}</CreateTime>
  259. <MsgType><![CDATA[{$type}]]></MsgType>
  260. <Content><![CDATA[{$content}]]></Content>
  261. </xml>";
  262. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  263. $encryptMsg = '';
  264. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);
  265. echo $encryptMsg;
  266. break;
  267. }
  268. */
  269. $adminSendMsg = false;
  270. $openMerchant = xhWxOpenService::getMerchant();
  271. $openMerchantId = $openMerchant['id'];
  272. if ($adminSendMsg == false) {
  273. $lastTimeKey = "customer_{$userId}:merchant_{$merchantId}_new_msg_last_time";//最后一次会话时间key
  274. //将消息内容转发到管理员微信上
  275. $admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
  276. if (!empty($admin)) {
  277. $adminOpenId = $admin['openId'];
  278. $adminId = $admin['id'];
  279. //获取最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  280. $connect = Yii::$app->redis->executeCommand('GET', [$lastTimeKey]);
  281. if (empty($connect) || ($now - $connect) >= 100) {
  282. $allTM = xhTMessageService::getList($openMerchantId);
  283. $shortTempId = 'OPENTM200605630';
  284. if (isset($allTM[$shortTempId])) {
  285. $tempId = $allTM[$shortTempId];
  286. $data = [
  287. "touser" => $adminOpenId,
  288. "template_id" => $tempId,
  289. "url" => Yii::$app->params['adminUrl'] . "/chat/index?customId=" . $userId,
  290. "data" => ["first" => ["value" => "{$user['userName']} 向您的公众号发来新消息", "color" => "#173177"],
  291. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  292. "keyword2" => ["value" => '文字', "color" => "#173177"],
  293. "remark" => ["value" => '点击查看详情', "color" => "#173177"]
  294. ]
  295. ];
  296. wxUtil::sendTaskInform($data, $openMerchant);
  297. }
  298. //设置商家与用户最后一次会话时间。
  299. Yii::$app->redis->executeCommand('SET', [$lastTimeKey, $now]);
  300. Yii::$app->redis->executeCommand('EXPIRE', [$lastTimeKey, 100]);//过期
  301. }
  302. //swoole:商家是否在线
  303. $customId = $userId;//客户uid
  304. xhUserService::getById($customId);//把客户用户数据存入缓存,预防清缓存,取不到客户数据
  305. //在线,通过socket给商家发消息
  306. define('WEBPATH', __DIR__);
  307. define('ROOT_PATH', __DIR__);
  308. //Swoole框架自动载入器初始化
  309. // \Swoole\Loader::vendorInit();
  310. // $serverIp = util::serverIP();
  311. // $client = new \Swoole\Client\WebSocket($serverIp, 9503, '/');
  312. // if (!$client->connect()) {
  313. // echo "connect to server failed.\n";
  314. // exit;
  315. // }
  316. //from: 客户的clientId(无); to:商家的clientId
  317. $sendData = [
  318. 'cmd' => 'sendMsgC2M',
  319. 'from' => -1,//可能未在线
  320. 'to' => 0,
  321. 'uid' => $customId,//客户id
  322. 'chatUid' => $merchantId,//商家id
  323. 'chatLogKey' => "merchant_history_{$merchantId}_{$customId}",//消息记录缓存key
  324. 'channal' => 1,
  325. 'data' => $Content,
  326. 'type' => 'text'
  327. ];
  328. // $client->send(json_encode($sendData));
  329. //$message = $client->recv();
  330. //表情替换
  331. /*$imgUrl = $this->imgUrl;
  332. $emotionCode = qqFaceUtil::getEmojiCode($imgUrl);
  333. foreach($emotionCode as $key => $val){
  334. $zz = $val[0];
  335. $img = $val[1];
  336. $name = $val[2];
  337. $Content = str_replace($zz,$img,$Content);
  338. }
  339. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now.'{~CHAT~}themself{~CHAT~}'.$Content]);*/
  340. //util::end();
  341. }
  342. //给客户微信返回(打开聊天界面的模板消息通知)
  343. $userTest = false;
  344. if (!empty($userTest)) {
  345. $userOpenId = $user['openId'];
  346. $allTM = xhTMessageService::getList($merchantId);
  347. $shortTempId = 'OPENTM200605630';
  348. if (isset($allTM[$shortTempId])) {
  349. $tempId = $allTM[$shortTempId];
  350. $data = [
  351. "touser" => $userOpenId,
  352. "template_id" => $tempId,
  353. "url" => Yii::$app->params['frontUrl'] . "/chat/index?account=" . $account,
  354. "data" => ["first" => ["value" => "亲,有什么需要可以帮到您,点此联系客服。", "color" => "#173177"],
  355. "keyword1" => ["value" => '前往聊天页', "color" => "#173177"],
  356. "keyword2" => ["value" => '文字', "color" => "#173177"],
  357. "remark" => ["value" => '点击与客服聊天', "color" => "#173177"]
  358. ]
  359. ];
  360. wxUtil::sendTaskInform($data, $merchant);
  361. }
  362. util::end();
  363. }
  364. //刮刮卡
  365. if ($Content == '我要花') {
  366. $id = GuaGuaService::getNewestId();//取最新的活动id
  367. $text = $this->replyTextContent("会员日抽奖链接:".Yii::$app->params['mobileUrl']."/gua/index?account={$merchantId}&id=" . $id);//没有管理员返回的信息
  368. } else {
  369. $text = $this->replyTextContent("^_^");//没有管理员返回的信息
  370. }
  371. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  372. $encryptMsg = '';
  373. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  374. echo $encryptMsg;
  375. }
  376. } elseif ($this->msgType == 'image') {
  377. $PicUrl = (string)$PicUrl;
  378. if (empty($PicUrl)) {
  379. util::end();
  380. }
  381. $folder = Yii::getAlias('@webroot') . '/../../images';
  382. $pre = '/weixinChat/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  383. if (!file_exists($folder . $pre)) {
  384. mkdir($folder . $pre, 0777, true);
  385. }
  386. $preFileName = substr(md5($userId), -4);
  387. $preName = $preFileName . stringUtil::buildOrderNo();
  388. $extName = '.jpg';
  389. $name = $preName . $extName;
  390. $fullFileName = $folder . $pre . $name;
  391. $fileName = $pre . $name;
  392. $curl = new curl\Curl();
  393. $result = $curl->get($PicUrl);
  394. $fp2 = @fopen($fullFileName, 'a');//文件大小
  395. fwrite($fp2, $result);
  396. fclose($fp2);
  397. //生成300缩略图
  398. $dstImg300 = $folder . $pre . $preName . '_300.' . $extName;
  399. $img2thumbReturn = util::img2thumb($fullFileName, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
  400. $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
  401. $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
  402. $invalid = '/images/invalid.jpg';
  403. $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;" />';
  404. //将图片转发到管理员微信上
  405. $adminId = $merchant['adminId'];
  406. $admin = xhAdminService::getById($adminId);
  407. if (empty($admin)) {
  408. util::stop('没有管理员');
  409. }
  410. $adminOpenId = $admin['openId'];
  411. $adminId = $admin['id'];
  412. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  413. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  414. if (empty($connect) || ($now - $connect) > 100) {
  415. $allTM = xhTMessageService::getList($merchantId);
  416. $shortTempId = 'OPENTM200605630';
  417. if (isset($allTM[$shortTempId])) {
  418. $tempId = $allTM[$shortTempId];
  419. $data = [
  420. "touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  421. "data" => ["first" => ["value" => "{$user['userName']} 发来图片", "color" => "#173177"],
  422. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  423. "keyword2" => ["value" => '图片', "color" => "#173177"],
  424. "remark" => ["value" => '请登陆后台查看', "color" => "#173177"]]];
  425. wxUtil::sendTaskInform($data, $merchant);
  426. }
  427. }
  428. //记录商家的新消息用户有谁。
  429. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  430. //记录商家的最近联系人
  431. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  432. //设置商家与用户最后一次会话时间。
  433. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  434. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  435. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  436. } elseif ($this->msgType == 'voice') {
  437. $Content = '<span voiceId="' . $MediaId . '">【提示】客户发来一条语音消息,请登陆微信公众号后台查看。</span>';
  438. $adminId = $merchant['adminId'];
  439. $admin = xhAdminService::getById($adminId);
  440. if (empty($admin)) {
  441. Yii::warning("没有管理员,merchantId:" . $merchantId);
  442. util::end();
  443. }
  444. $adminOpenId = $admin['openId'];
  445. $adminId = $admin['id'];
  446. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  447. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  448. if (empty($connect) || ($now - $connect) > 100) {
  449. $allTM = xhTMessageService::getList($merchantId);
  450. $shortTempId = 'OPENTM200605630';
  451. if (isset($allTM[$shortTempId])) {
  452. $tempId = $allTM[$shortTempId];
  453. $data = ["touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  454. "data" => [
  455. "first" => ["value" => "{$user['userName']} 发来语音", "color" => "#173177"],
  456. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  457. "keyword2" => ["value" => '语音', "color" => "#173177"],
  458. "remark" => ["value" => '消息内容:请登陆后台查看', "color" => "#173177"]]];
  459. wxUtil::sendTaskInform($data, $merchant);
  460. }
  461. }
  462. //记录商家的新消息用户有谁。
  463. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  464. //记录商家的最近联系人
  465. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  466. //设置商家与用户最后一次会话时间。
  467. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  468. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  469. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  470. } elseif ($this->msgType == 'video') {
  471. } elseif ($this->msgType == 'location') {
  472. } elseif ($this->msgType == 'link') {
  473. } else {
  474. }
  475. }
  476. /**
  477. * 回复文字消息
  478. */
  479. private function replyTextContent($content)
  480. {
  481. $createTime = time();//响应当前时间
  482. $con = "<xml>
  483. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  484. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  485. <CreateTime>{$createTime}</CreateTime>
  486. <MsgType><![CDATA[text]]></MsgType>
  487. <Content><![CDATA[{$content}]]></Content>
  488. </xml>";
  489. return $con;
  490. }
  491. /**
  492. * 回复图片消息
  493. */
  494. private function replyPicContent($media_id)
  495. {
  496. $createTime = time();
  497. $con = "<xml>
  498. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  499. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  500. <CreateTime>{$createTime}</CreateTime>
  501. <MsgType><![CDATA[image]]></MsgType>
  502. <Image>
  503. <MediaId><![CDATA[{$media_id}]]></MediaId>
  504. </Image>
  505. </xml>";
  506. return $con;
  507. }
  508. /**
  509. * 回复单图文消息
  510. */
  511. private function replyNewsContent($title, $desc, $picUrl, $url)
  512. {
  513. $createTime = time();//响应当前时间
  514. $con = "<xml>
  515. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  516. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  517. <CreateTime>{$createTime}</CreateTime>
  518. <MsgType><![CDATA[news]]></MsgType>
  519. <ArticleCount>1</ArticleCount><Articles>
  520. <item>
  521. <Title><![CDATA[{$title}]]></Title>
  522. <Description><![CDATA[{$desc}]]></Description>
  523. <PicUrl><![CDATA[{$picUrl}]]></PicUrl>
  524. <Url><![CDATA[{$url}]]></Url>
  525. </item>
  526. </Articles></xml>";
  527. return $con;
  528. }
  529. /**
  530. * 回复视频消息
  531. * @param $title
  532. * @param $media_id
  533. * @param $description
  534. * @return string
  535. */
  536. private function replyVideoContent($title, $media_id, $description)
  537. {
  538. $createTime = time();//响应当前时间
  539. $con = "<xml>
  540. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  541. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  542. <CreateTime>{$createTime}</CreateTime>
  543. <MsgType><![CDATA[video]]></MsgType>
  544. <Video>
  545. <MediaId><![CDATA[{$media_id}]]></MediaId>
  546. <Title><![CDATA[{$title}]]></Title>
  547. <Description><![CDATA[{$description}]]></Description>
  548. </Video>
  549. </xml>";
  550. return $con;
  551. }
  552. }