WxController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. namespace www\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. $admin = [];
  277. if (!empty($admin)) {
  278. $adminOpenId = $admin['openId'];
  279. $adminId = $admin['id'];
  280. //获取最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  281. $connect = Yii::$app->redis->executeCommand('GET', [$lastTimeKey]);
  282. if (empty($connect) || ($now - $connect) >= 100) {
  283. $allTM = xhTMessageService::getList($openMerchantId);
  284. $shortTempId = 'OPENTM200605630';
  285. if (isset($allTM[$shortTempId])) {
  286. $tempId = $allTM[$shortTempId];
  287. $data = [
  288. "touser" => $adminOpenId,
  289. "template_id" => $tempId,
  290. "url" => Yii::$app->params['adminUrl'] . "/chat/index?customId=" . $userId,
  291. "data" => ["first" => ["value" => "{$user['userName']} 向您的公众号发来新消息", "color" => "#173177"],
  292. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  293. "keyword2" => ["value" => '文字', "color" => "#173177"],
  294. "remark" => ["value" => '点击查看详情', "color" => "#173177"]
  295. ]
  296. ];
  297. wxUtil::sendTaskInform($data, $openMerchant);
  298. }
  299. //设置商家与用户最后一次会话时间。
  300. Yii::$app->redis->executeCommand('SET', [$lastTimeKey, $now]);
  301. Yii::$app->redis->executeCommand('EXPIRE', [$lastTimeKey, 100]);//过期
  302. }
  303. //swoole:商家是否在线
  304. $customId = $userId;//客户uid
  305. xhUserService::getById($customId);//把客户用户数据存入缓存,预防清缓存,取不到客户数据
  306. //在线,通过socket给商家发消息
  307. define('WEBPATH', __DIR__);
  308. define('ROOT_PATH', __DIR__);
  309. //Swoole框架自动载入器初始化
  310. // \Swoole\Loader::vendorInit();
  311. // $serverIp = util::serverIP();
  312. // $client = new \Swoole\Client\WebSocket($serverIp, 9503, '/');
  313. // if (!$client->connect()) {
  314. // echo "connect to server failed.\n";
  315. // exit;
  316. // }
  317. //from: 客户的clientId(无); to:商家的clientId
  318. $sendData = [
  319. 'cmd' => 'sendMsgC2M',
  320. 'from' => -1,//可能未在线
  321. 'to' => 0,
  322. 'uid' => $customId,//客户id
  323. 'chatUid' => $merchantId,//商家id
  324. 'chatLogKey' => "merchant_history_{$merchantId}_{$customId}",//消息记录缓存key
  325. 'channal' => 1,
  326. 'data' => $Content,
  327. 'type' => 'text'
  328. ];
  329. // $client->send(json_encode($sendData));
  330. //$message = $client->recv();
  331. //表情替换
  332. /*$imgUrl = $this->imgUrl;
  333. $emotionCode = qqFaceUtil::getEmojiCode($imgUrl);
  334. foreach($emotionCode as $key => $val){
  335. $zz = $val[0];
  336. $img = $val[1];
  337. $name = $val[2];
  338. $Content = str_replace($zz,$img,$Content);
  339. }
  340. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now.'{~CHAT~}themself{~CHAT~}'.$Content]);*/
  341. //util::end();
  342. }
  343. //给客户微信返回(打开聊天界面的模板消息通知)
  344. $userTest = false;
  345. if (!empty($userTest)) {
  346. $userOpenId = $user['openId'];
  347. $allTM = xhTMessageService::getList($merchantId);
  348. $shortTempId = 'OPENTM200605630';
  349. if (isset($allTM[$shortTempId])) {
  350. $tempId = $allTM[$shortTempId];
  351. $data = [
  352. "touser" => $userOpenId,
  353. "template_id" => $tempId,
  354. "url" => Yii::$app->params['frontUrl'] . "/chat/index?account=" . $account,
  355. "data" => ["first" => ["value" => "亲,有什么需要可以帮到您,点此联系客服。", "color" => "#173177"],
  356. "keyword1" => ["value" => '前往聊天页', "color" => "#173177"],
  357. "keyword2" => ["value" => '文字', "color" => "#173177"],
  358. "remark" => ["value" => '点击与客服聊天', "color" => "#173177"]
  359. ]
  360. ];
  361. wxUtil::sendTaskInform($data, $merchant);
  362. }
  363. util::end();
  364. }
  365. $text = $this->replyTextContent("^_^");//没有管理员返回的信息
  366. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  367. $encryptMsg = '';
  368. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  369. echo $encryptMsg;
  370. }
  371. } elseif ($this->msgType == 'image') {
  372. $PicUrl = (string)$PicUrl;
  373. if (empty($PicUrl)) {
  374. util::end();
  375. }
  376. $folder = Yii::getAlias('@webroot') . '/../../images';
  377. $pre = '/weixinChat/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  378. if (!file_exists($folder . $pre)) {
  379. mkdir($folder . $pre, 0777, true);
  380. }
  381. $preFileName = substr(md5($userId), -4);
  382. $preName = $preFileName . stringUtil::buildOrderNo();
  383. $extName = '.jpg';
  384. $name = $preName . $extName;
  385. $fullFileName = $folder . $pre . $name;
  386. $fileName = $pre . $name;
  387. $curl = new curl\Curl();
  388. $result = $curl->get($PicUrl);
  389. $fp2 = @fopen($fullFileName, 'a');//文件大小
  390. fwrite($fp2, $result);
  391. fclose($fp2);
  392. //生成300缩略图
  393. $dstImg300 = $folder . $pre . $preName . '_300.' . $extName;
  394. $img2thumbReturn = util::img2thumb($fullFileName, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
  395. $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
  396. $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
  397. $invalid = '/images/invalid.jpg';
  398. $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;" />';
  399. //将图片转发到管理员微信上
  400. $adminId = $merchant['adminId'];
  401. $admin = xhAdminService::getById($adminId);
  402. if (empty($admin)) {
  403. util::stop('没有管理员');
  404. }
  405. $adminOpenId = $admin['openId'];
  406. $adminId = $admin['id'];
  407. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  408. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  409. if (empty($connect) || ($now - $connect) > 100) {
  410. $allTM = xhTMessageService::getList($merchantId);
  411. $shortTempId = 'OPENTM200605630';
  412. if (isset($allTM[$shortTempId])) {
  413. $tempId = $allTM[$shortTempId];
  414. $data = [
  415. "touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  416. "data" => ["first" => ["value" => "{$user['userName']} 发来图片", "color" => "#173177"],
  417. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  418. "keyword2" => ["value" => '图片', "color" => "#173177"],
  419. "remark" => ["value" => '请登陆后台查看', "color" => "#173177"]]];
  420. wxUtil::sendTaskInform($data, $merchant);
  421. }
  422. }
  423. //记录商家的新消息用户有谁。
  424. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  425. //记录商家的最近联系人
  426. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  427. //设置商家与用户最后一次会话时间。
  428. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  429. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  430. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  431. } elseif ($this->msgType == 'voice') {
  432. $Content = '<span voiceId="' . $MediaId . '">【提示】客户发来一条语音消息,请登陆微信公众号后台查看。</span>';
  433. $adminId = $merchant['adminId'];
  434. $admin = xhAdminService::getById($adminId);
  435. if (empty($admin)) {
  436. Yii::warning("没有管理员,merchantId:" . $merchantId);
  437. util::end();
  438. }
  439. $adminOpenId = $admin['openId'];
  440. $adminId = $admin['id'];
  441. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  442. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  443. if (empty($connect) || ($now - $connect) > 100) {
  444. $allTM = xhTMessageService::getList($merchantId);
  445. $shortTempId = 'OPENTM200605630';
  446. if (isset($allTM[$shortTempId])) {
  447. $tempId = $allTM[$shortTempId];
  448. $data = ["touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  449. "data" => [
  450. "first" => ["value" => "{$user['userName']} 发来语音", "color" => "#173177"],
  451. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  452. "keyword2" => ["value" => '语音', "color" => "#173177"],
  453. "remark" => ["value" => '消息内容:请登陆后台查看', "color" => "#173177"]]];
  454. wxUtil::sendTaskInform($data, $merchant);
  455. }
  456. }
  457. //记录商家的新消息用户有谁。
  458. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  459. //记录商家的最近联系人
  460. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  461. //设置商家与用户最后一次会话时间。
  462. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  463. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  464. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  465. } elseif ($this->msgType == 'video') {
  466. } elseif ($this->msgType == 'location') {
  467. } elseif ($this->msgType == 'link') {
  468. } else {
  469. }
  470. }
  471. /**
  472. * 回复文字消息
  473. */
  474. private function replyTextContent($content)
  475. {
  476. $createTime = time();//响应当前时间
  477. $con = "<xml>
  478. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  479. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  480. <CreateTime>{$createTime}</CreateTime>
  481. <MsgType><![CDATA[text]]></MsgType>
  482. <Content><![CDATA[{$content}]]></Content>
  483. </xml>";
  484. return $con;
  485. }
  486. /**
  487. * 回复图片消息
  488. */
  489. private function replyPicContent($media_id)
  490. {
  491. $createTime = time();
  492. $con = "<xml>
  493. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  494. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  495. <CreateTime>{$createTime}</CreateTime>
  496. <MsgType><![CDATA[image]]></MsgType>
  497. <Image>
  498. <MediaId><![CDATA[{$media_id}]]></MediaId>
  499. </Image>
  500. </xml>";
  501. return $con;
  502. }
  503. /**
  504. * 回复单图文消息
  505. */
  506. private function replyNewsContent($title, $desc, $picUrl, $url)
  507. {
  508. $createTime = time();//响应当前时间
  509. $con = "<xml>
  510. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  511. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  512. <CreateTime>{$createTime}</CreateTime>
  513. <MsgType><![CDATA[news]]></MsgType>
  514. <ArticleCount>1</ArticleCount><Articles>
  515. <item>
  516. <Title><![CDATA[{$title}]]></Title>
  517. <Description><![CDATA[{$desc}]]></Description>
  518. <PicUrl><![CDATA[{$picUrl}]]></PicUrl>
  519. <Url><![CDATA[{$url}]]></Url>
  520. </item>
  521. </Articles></xml>";
  522. return $con;
  523. }
  524. /**
  525. * 回复视频消息
  526. * @param $title
  527. * @param $media_id
  528. * @param $description
  529. * @return string
  530. */
  531. private function replyVideoContent($title, $media_id, $description)
  532. {
  533. $createTime = time();//响应当前时间
  534. $con = "<xml>
  535. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  536. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  537. <CreateTime>{$createTime}</CreateTime>
  538. <MsgType><![CDATA[video]]></MsgType>
  539. <Video>
  540. <MediaId><![CDATA[{$media_id}]]></MediaId>
  541. <Title><![CDATA[{$title}]]></Title>
  542. <Description><![CDATA[{$description}]]></Description>
  543. </Video>
  544. </xml>";
  545. return $con;
  546. }
  547. }