WxController.php 29 KB

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