WxController.php 24 KB

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