WxController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. 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. Yii::$app->params['merchantId'] = $merchantId;
  105. $merchantExtend = xhMerchantExtendService::getByMerchantId($merchantId);
  106. }
  107. $user = xhUserService::getByOpenId($this->fromUsername, $merchantId);
  108. $userId = 0;
  109. $userAsset = [];
  110. if (!empty($user)) {
  111. $userId = $user['id'];
  112. $userAsset = xhUserAssetService::getByUserId($userId);
  113. }
  114. if ($this->msgType == 'event') {
  115. /*
  116. //全网发布,1 事件消息响应
  117. $content = $postObj->Event."from_callback";
  118. $createTime = time (); // 响应当前时间
  119. $type = "text";
  120. $text = "<xml>
  121. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  122. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  123. <CreateTime>{$createTime}</CreateTime>
  124. <MsgType><![CDATA[{$type}]]></MsgType>
  125. <Content><![CDATA[{$content}]]></Content>
  126. </xml>";
  127. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  128. $encryptMsg = '';
  129. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  130. echo $encryptMsg;
  131. Yii::$app->end();
  132. */
  133. switch ($Event) {
  134. //关注
  135. case 'subscribe':
  136. $getUserInfo = weixinUtil::userInfo($this->fromUsername, $merchant);//从微信接口获取用户信息
  137. $source = UserService::$userSourceId['official']['name'];
  138. Yii::info('关注公众号,获得用户信息:' . json_encode($getUserInfo));
  139. $user = UserService::replaceUser($getUserInfo, $source, $merchantId);
  140. $userId = $user['id'];
  141. $text = $this->replyTextContent("等您好久,终于等到您~\n\n注册会员享折扣哦,<a href='" . Yii::$app->params['frontUrl'] . "/center/right?account={$merchant['id']}'>详情</a>");
  142. if ($merchant['merchantName'] == '花卉宝') {
  143. $text = $this->replyTextContent("等您好久,终于等到您 /::)");
  144. }
  145. //响应扫码的场景事件 shish 2019.9.5
  146. if (strstr($EventKey, 'qrscene_')) {
  147. Yii::info($EventKey);
  148. $sceneId = str_replace('qrscene_', '', $EventKey);
  149. WxSceneService::respondScanEvent($merchant, $user, (string)$sceneId);
  150. }
  151. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  152. $encryptMsg = '';
  153. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  154. echo $encryptMsg;
  155. $admin = xhAdminService::getByOpenId($this->fromUsername);
  156. if (!empty($admin)) {
  157. $adminId = $admin['id'];
  158. xhAdminService::updateById($adminId, ['subscribe' => 1]);
  159. }
  160. break;
  161. //取消关注
  162. case 'unsubscribe':
  163. UserService::unFocus($userId, $merchantId);
  164. break;
  165. //自定义菜单回复
  166. case 'click':
  167. $menuKey = $EventKey;
  168. $menu = xhWxMenuService::getByMenuKey($menuKey);
  169. $wxMenuOption = $menu['menuOption'];
  170. $wxMenuOptionList = configDict::getConfig('wxMenuOption');
  171. switch ($wxMenuOption) {
  172. case $wxMenuOptionList['showText']://链接到-文字
  173. $replyContent = $menu['replyText'];
  174. $text = $this->replyTextContent($replyContent);
  175. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  176. $encryptMsg = '';
  177. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  178. echo $encryptMsg;
  179. break;
  180. default:
  181. }
  182. break;
  183. //门店申请
  184. case 'poi_check_notify':
  185. if ($postObj->Result == 'succ') {
  186. $shop['status'] = 2;
  187. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  188. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  189. } elseif ($postObj->Result == 'fail') {
  190. $shop['status'] = 4;
  191. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  192. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核失败: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  193. } else {
  194. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核异常记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  195. throw new \Exception('微信门店申请返回异常');
  196. }
  197. break;
  198. case 'view':
  199. break;
  200. case 'scan':
  201. //响应扫码的场景事件 shish 2019.9.5
  202. Yii::info('a' . $EventKey);
  203. WxSceneService::respondScanEvent($merchant, $user, (string)$EventKey);
  204. break;
  205. default:
  206. Yii::warning("该EVENT类型未定义,EVENT:" . $Event);
  207. }
  208. } elseif ($this->msgType == 'text') {
  209. /*
  210. //全网发布,3 api客服接口回应
  211. if(strpos($Content,'QUERY_AUTH_CODE:') !== false){
  212. //返回空字符,表示暂不回复
  213. $content = "";
  214. $FuncFlag = 0;
  215. $type = "text";
  216. $createTime = time (); // 响应当前时间
  217. $text = "<xml>
  218. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  219. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  220. <CreateTime>{$createTime}</CreateTime>
  221. <MsgType><![CDATA[{$type}]]></MsgType>
  222. <Content><![CDATA[{$content}]]></Content>
  223. </xml>";
  224. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  225. $encryptMsg = '';
  226. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  227. echo $encryptMsg;
  228. $ticket = str_replace('QUERY_AUTH_CODE:','',$Content);
  229. $authorizer = weixinOpenUtil::getAuthorizer($ticket);
  230. //Yii::warning("authorizer:".json_encode($authorizer));
  231. $info = $authorizer['authorization_info'];
  232. $authorizer_appid = $info['authorizer_appid'];
  233. $authorizer_access_token = $info['authorizer_access_token'];
  234. //Yii::warning("authorizer_access_token:".$authorizer_access_token);
  235. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$authorizer_access_token}";
  236. $con = $ticket."_from_api";
  237. $data = ["touser" => "{$this->fromUsername}","msgtype" => "text","text"=>["content" => $con]];
  238. $curl = new curl\Curl();
  239. $result = $curl->setOption(CURLOPT_POSTFIELDS,json_encode($data))->post($url);
  240. $result = Json::decode($result);
  241. //Yii::warning("fromUsername:".$this->fromUsername.' toUsername:'.$this->toUsername);
  242. //Yii::warning(" ticket: ~ ".$ticket.' | json:'.json_encode($result),__METHOD__);
  243. Yii::$app->end();
  244. }
  245. switch($Content){
  246. //全网发布,2 发送文本消息
  247. case 'TESTCOMPONENT_MSG_TYPE_TEXT':
  248. $content = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
  249. $FuncFlag = 0;
  250. $type = "text";
  251. $createTime = time ();
  252. $text = "<xml>
  253. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  254. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  255. <CreateTime>{$createTime}</CreateTime>
  256. <MsgType><![CDATA[{$type}]]></MsgType>
  257. <Content><![CDATA[{$content}]]></Content>
  258. </xml>";
  259. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  260. $encryptMsg = '';
  261. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);
  262. echo $encryptMsg;
  263. break;
  264. }
  265. */
  266. $adminSendMsg = false;
  267. $openMerchant = xhWxOpenService::getMerchant();
  268. $openMerchantId = $openMerchant['id'];
  269. if ($adminSendMsg == false) {
  270. $lastTimeKey = "customer_{$userId}:merchant_{$merchantId}_new_msg_last_time";//最后一次会话时间key
  271. //将消息内容转发到管理员微信上
  272. $admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
  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. weixinUtil::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. weixinUtil::sendTaskInform($data, $merchant);
  358. }
  359. util::end();
  360. }
  361. //刮刮卡
  362. if ($Content == '我要花') {
  363. $id = GuaGuaService::getNewestId();//取最新的活动id
  364. $text = $this->replyTextContent("会员日抽奖链接:".Yii::$app->params['mobileUrl']."/gua/index?account={$merchantId}&id=" . $id);//没有管理员返回的信息
  365. } else {
  366. $text = $this->replyTextContent("^_^");//没有管理员返回的信息
  367. }
  368. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  369. $encryptMsg = '';
  370. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  371. echo $encryptMsg;
  372. }
  373. } elseif ($this->msgType == 'image') {
  374. $PicUrl = (string)$PicUrl;
  375. if (empty($PicUrl)) {
  376. util::end();
  377. }
  378. $folder = Yii::getAlias('@webroot') . '/../../images';
  379. $pre = '/weixinChat/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  380. if (!file_exists($folder . $pre)) {
  381. mkdir($folder . $pre, 0777, true);
  382. }
  383. $preFileName = substr(md5($userId), -4);
  384. $preName = $preFileName . stringUtil::buildOrderNo();
  385. $extName = '.jpg';
  386. $name = $preName . $extName;
  387. $fullFileName = $folder . $pre . $name;
  388. $fileName = $pre . $name;
  389. $curl = new curl\Curl();
  390. $result = $curl->get($PicUrl);
  391. $fp2 = @fopen($fullFileName, 'a');//文件大小
  392. fwrite($fp2, $result);
  393. fclose($fp2);
  394. //生成300缩略图
  395. $dstImg300 = $folder . $pre . $preName . '_300.' . $extName;
  396. $img2thumbReturn = util::img2thumb($fullFileName, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
  397. $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
  398. $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
  399. $invalid = '/images/invalid.jpg';
  400. $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;" />';
  401. //将图片转发到管理员微信上
  402. $adminId = $merchant['adminId'];
  403. $admin = xhAdminService::getById($adminId);
  404. if (empty($admin)) {
  405. util::stop('没有管理员');
  406. }
  407. $adminOpenId = $admin['openId'];
  408. $adminId = $admin['id'];
  409. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  410. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  411. if (empty($connect) || ($now - $connect) > 100) {
  412. $allTM = xhTMessageService::getList($merchantId);
  413. $shortTempId = 'OPENTM200605630';
  414. if (isset($allTM[$shortTempId])) {
  415. $tempId = $allTM[$shortTempId];
  416. $data = [
  417. "touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  418. "data" => ["first" => ["value" => "{$user['userName']} 发来图片", "color" => "#173177"],
  419. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  420. "keyword2" => ["value" => '图片', "color" => "#173177"],
  421. "remark" => ["value" => '请登陆后台查看', "color" => "#173177"]]];
  422. weixinUtil::sendTaskInform($data, $merchant);
  423. }
  424. }
  425. //记录商家的新消息用户有谁。
  426. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  427. //记录商家的最近联系人
  428. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  429. //设置商家与用户最后一次会话时间。
  430. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  431. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  432. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  433. } elseif ($this->msgType == 'voice') {
  434. $Content = '<span voiceId="' . $MediaId . '">【提示】客户发来一条语音消息,请登陆微信公众号后台查看。</span>';
  435. $adminId = $merchant['adminId'];
  436. $admin = xhAdminService::getById($adminId);
  437. if (empty($admin)) {
  438. Yii::warning("没有管理员,merchantId:" . $merchantId);
  439. util::end();
  440. }
  441. $adminOpenId = $admin['openId'];
  442. $adminId = $admin['id'];
  443. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  444. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  445. if (empty($connect) || ($now - $connect) > 100) {
  446. $allTM = xhTMessageService::getList($merchantId);
  447. $shortTempId = 'OPENTM200605630';
  448. if (isset($allTM[$shortTempId])) {
  449. $tempId = $allTM[$shortTempId];
  450. $data = ["touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  451. "data" => [
  452. "first" => ["value" => "{$user['userName']} 发来语音", "color" => "#173177"],
  453. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  454. "keyword2" => ["value" => '语音', "color" => "#173177"],
  455. "remark" => ["value" => '消息内容:请登陆后台查看', "color" => "#173177"]]];
  456. weixinUtil::sendTaskInform($data, $merchant);
  457. }
  458. }
  459. //记录商家的新消息用户有谁。
  460. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  461. //记录商家的最近联系人
  462. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  463. //设置商家与用户最后一次会话时间。
  464. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  465. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  466. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  467. } elseif ($this->msgType == 'video') {
  468. } elseif ($this->msgType == 'location') {
  469. } elseif ($this->msgType == 'link') {
  470. } else {
  471. }
  472. }
  473. /**
  474. * 回复文字消息
  475. */
  476. private function replyTextContent($content)
  477. {
  478. $createTime = time();//响应当前时间
  479. $con = "<xml>
  480. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  481. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  482. <CreateTime>{$createTime}</CreateTime>
  483. <MsgType><![CDATA[text]]></MsgType>
  484. <Content><![CDATA[{$content}]]></Content>
  485. </xml>";
  486. return $con;
  487. }
  488. /**
  489. * 回复图片消息
  490. */
  491. private function replyPicContent($media_id)
  492. {
  493. $createTime = time();
  494. $con = "<xml>
  495. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  496. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  497. <CreateTime>{$createTime}</CreateTime>
  498. <MsgType><![CDATA[image]]></MsgType>
  499. <Image>
  500. <MediaId><![CDATA[{$media_id}]]></MediaId>
  501. </Image>
  502. </xml>";
  503. return $con;
  504. }
  505. /**
  506. * 回复单图文消息
  507. */
  508. private function replyNewsContent($title, $desc, $picUrl, $url)
  509. {
  510. $createTime = time();//响应当前时间
  511. $con = "<xml>
  512. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  513. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  514. <CreateTime>{$createTime}</CreateTime>
  515. <MsgType><![CDATA[news]]></MsgType>
  516. <ArticleCount>1</ArticleCount><Articles>
  517. <item>
  518. <Title><![CDATA[{$title}]]></Title>
  519. <Description><![CDATA[{$desc}]]></Description>
  520. <PicUrl><![CDATA[{$picUrl}]]></PicUrl>
  521. <Url><![CDATA[{$url}]]></Url>
  522. </item>
  523. </Articles></xml>";
  524. return $con;
  525. }
  526. /**
  527. * 回复视频消息
  528. * @param $title
  529. * @param $media_id
  530. * @param $description
  531. * @return string
  532. */
  533. private function replyVideoContent($title, $media_id, $description)
  534. {
  535. $createTime = time();//响应当前时间
  536. $con = "<xml>
  537. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  538. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  539. <CreateTime>{$createTime}</CreateTime>
  540. <MsgType><![CDATA[video]]></MsgType>
  541. <Video>
  542. <MediaId><![CDATA[{$media_id}]]></MediaId>
  543. <Title><![CDATA[{$title}]]></Title>
  544. <Description><![CDATA[{$description}]]></Description>
  545. </Video>
  546. </xml>";
  547. return $con;
  548. }
  549. }