WxController.php 25 KB

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