WxController.php 25 KB

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