WxController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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['openName'] . ",解密未成功,错误代码:" . $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. $source = UserClass::$userSourceId['official']['name'];
  178. $user = UserService::replaceUser($getUserInfo, $source, $merchantId);
  179. $userId = $user['id'];
  180. UserService::focus($user, $merchant);
  181. //响应扫码的场景事件 shish 2019.9.5
  182. if (strstr($EventKey, 'qrscene_')) {
  183. Yii::info($EventKey);
  184. $sceneId = str_replace('qrscene_', '', $EventKey);
  185. WxSceneService::respondScanEvent($merchant, $user, (string)$sceneId);
  186. }
  187. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  188. $encryptMsg = '';
  189. $text = $this->replyTextContent("等您好久,终于等到您 /::)");
  190. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  191. echo $encryptMsg;
  192. break;
  193. //取消关注
  194. case 'unsubscribe':
  195. UserService::unFocus($userId, $merchantId);
  196. break;
  197. //自定义菜单回复
  198. case 'click':
  199. $menuKey = $EventKey;
  200. $menu = xhWxMenuService::getByMenuKey($menuKey);
  201. $wxMenuOption = $menu['menuOption'];
  202. $wxMenuOptionList = configDict::getConfig('wxMenuOption');
  203. switch ($wxMenuOption) {
  204. case $wxMenuOptionList['showText']://链接到-文字
  205. $replyContent = $menu['replyText'];
  206. $text = $this->replyTextContent($replyContent);
  207. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  208. $encryptMsg = '';
  209. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  210. echo $encryptMsg;
  211. break;
  212. default:
  213. }
  214. break;
  215. //门店申请
  216. case 'poi_check_notify':
  217. if ($postObj->Result == 'succ') {
  218. $shop['status'] = 2;
  219. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  220. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  221. } elseif ($postObj->Result == 'fail') {
  222. $shop['status'] = 4;
  223. xhShopService::updateByPoiId($postObj->PoiId, $shop);
  224. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核失败: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  225. } else {
  226. Yii::warning('poiId: ' . $postObj->PoiId . '<=>微信门店审核异常记录: ' . $postObj->msg . ', 时间:' . date('Y-m-d H:i:s', time()));
  227. throw new \Exception('微信门店申请返回异常');
  228. }
  229. break;
  230. case 'view':
  231. break;
  232. case 'scan':
  233. //响应扫码的场景事件 shish 2019.9.5
  234. Yii::info('a' . $EventKey);
  235. WxSceneService::respondScanEvent($merchant, $user, (string)$EventKey);
  236. break;
  237. default:
  238. Yii::warning("该EVENT类型未定义,EVENT:" . $Event);
  239. }
  240. } elseif ($this->msgType == 'text') {
  241. /*
  242. //全网发布,3 api客服接口回应
  243. if(strpos($Content,'QUERY_AUTH_CODE:') !== false){
  244. //返回空字符,表示暂不回复
  245. $content = "";
  246. $FuncFlag = 0;
  247. $type = "text";
  248. $createTime = time (); // 响应当前时间
  249. $text = "<xml>
  250. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  251. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  252. <CreateTime>{$createTime}</CreateTime>
  253. <MsgType><![CDATA[{$type}]]></MsgType>
  254. <Content><![CDATA[{$content}]]></Content>
  255. </xml>";
  256. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  257. $encryptMsg = '';
  258. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  259. echo $encryptMsg;
  260. $ticket = str_replace('QUERY_AUTH_CODE:','',$Content);
  261. $authorizer = wxUtil::getAuthorizer($ticket);
  262. //Yii::warning("authorizer:".json_encode($authorizer));
  263. $info = $authorizer['authorization_info'];
  264. $authorizer_appid = $info['authorizer_appid'];
  265. $authorizer_access_token = $info['authorizer_access_token'];
  266. //Yii::warning("authorizer_access_token:".$authorizer_access_token);
  267. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$authorizer_access_token}";
  268. $con = $ticket."_from_api";
  269. $data = ["touser" => "{$this->fromUsername}","msgtype" => "text","text"=>["content" => $con]];
  270. $curl = new curl\Curl();
  271. $result = $curl->setOption(CURLOPT_POSTFIELDS,json_encode($data))->post($url);
  272. $result = Json::decode($result);
  273. //Yii::warning("fromUsername:".$this->fromUsername.' toUsername:'.$this->toUsername);
  274. //Yii::warning(" ticket: ~ ".$ticket.' | json:'.json_encode($result),__METHOD__);
  275. Yii::$app->end();
  276. }
  277. switch($Content){
  278. //全网发布,2 发送文本消息
  279. case 'TESTCOMPONENT_MSG_TYPE_TEXT':
  280. $content = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
  281. $FuncFlag = 0;
  282. $type = "text";
  283. $createTime = time ();
  284. $text = "<xml>
  285. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  286. <FromUserName><![CDATA[gh_3c884a361561]]></FromUserName>
  287. <CreateTime>{$createTime}</CreateTime>
  288. <MsgType><![CDATA[{$type}]]></MsgType>
  289. <Content><![CDATA[{$content}]]></Content>
  290. </xml>";
  291. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  292. $encryptMsg = '';
  293. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);
  294. echo $encryptMsg;
  295. break;
  296. }
  297. */
  298. $adminSendMsg = false;
  299. $openMerchant = xhWxOpenService::getMerchant();
  300. $openMerchantId = $openMerchant['id'];
  301. if ($adminSendMsg == false) {
  302. $lastTimeKey = "customer_{$userId}:merchant_{$merchantId}_new_msg_last_time";//最后一次会话时间key
  303. //将消息内容转发到管理员微信上
  304. //$admin = xhAdminToMerchantService::getAdminByMerchantId($merchantId);
  305. $admin = [];
  306. if (!empty($admin)) {
  307. $adminOpenId = $admin['openId'];
  308. $adminId = $admin['id'];
  309. //获取最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  310. $connect = Yii::$app->redis->executeCommand('GET', [$lastTimeKey]);
  311. if (empty($connect) || ($now - $connect) >= 100) {
  312. $allTM = xhTMessageService::getList($openMerchantId);
  313. $shortTempId = 'OPENTM200605630';
  314. if (isset($allTM[$shortTempId])) {
  315. $tempId = $allTM[$shortTempId];
  316. $data = [
  317. "touser" => $adminOpenId,
  318. "template_id" => $tempId,
  319. "url" => Yii::$app->params['adminUrl'] . "/chat/index?customId=" . $userId,
  320. "data" => ["first" => ["value" => "{$user['userName']} 向您的公众号发来新消息", "color" => "#173177"],
  321. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  322. "keyword2" => ["value" => '文字', "color" => "#173177"],
  323. "remark" => ["value" => '点击查看详情', "color" => "#173177"]
  324. ]
  325. ];
  326. wxUtil::sendTaskInform($data, $openMerchant);
  327. }
  328. //设置商家与用户最后一次会话时间。
  329. Yii::$app->redis->executeCommand('SET', [$lastTimeKey, $now]);
  330. Yii::$app->redis->executeCommand('EXPIRE', [$lastTimeKey, 100]);//过期
  331. }
  332. //swoole:商家是否在线
  333. $customId = $userId;//客户uid
  334. xhUserService::getById($customId);//把客户用户数据存入缓存,预防清缓存,取不到客户数据
  335. //在线,通过socket给商家发消息
  336. define('WEBPATH', __DIR__);
  337. define('ROOT_PATH', __DIR__);
  338. //Swoole框架自动载入器初始化
  339. // \Swoole\Loader::vendorInit();
  340. // $serverIp = util::serverIP();
  341. // $client = new \Swoole\Client\WebSocket($serverIp, 9503, '/');
  342. // if (!$client->connect()) {
  343. // echo "connect to server failed.\n";
  344. // exit;
  345. // }
  346. //from: 客户的clientId(无); to:商家的clientId
  347. $sendData = [
  348. 'cmd' => 'sendMsgC2M',
  349. 'from' => -1,//可能未在线
  350. 'to' => 0,
  351. 'uid' => $customId,//客户id
  352. 'chatUid' => $merchantId,//商家id
  353. 'chatLogKey' => "merchant_history_{$merchantId}_{$customId}",//消息记录缓存key
  354. 'channal' => 1,
  355. 'data' => $Content,
  356. 'type' => 'text'
  357. ];
  358. // $client->send(json_encode($sendData));
  359. //$message = $client->recv();
  360. //表情替换
  361. /*$imgUrl = $this->imgUrl;
  362. $emotionCode = qqFaceUtil::getEmojiCode($imgUrl);
  363. foreach($emotionCode as $key => $val){
  364. $zz = $val[0];
  365. $img = $val[1];
  366. $name = $val[2];
  367. $Content = str_replace($zz,$img,$Content);
  368. }
  369. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now.'{~CHAT~}themself{~CHAT~}'.$Content]);*/
  370. //util::end();
  371. }
  372. //给客户微信返回(打开聊天界面的模板消息通知)
  373. $userTest = false;
  374. if (!empty($userTest)) {
  375. $userOpenId = $user['openId'];
  376. $allTM = xhTMessageService::getList($merchantId);
  377. $shortTempId = 'OPENTM200605630';
  378. if (isset($allTM[$shortTempId])) {
  379. $tempId = $allTM[$shortTempId];
  380. $data = [
  381. "touser" => $userOpenId,
  382. "template_id" => $tempId,
  383. "url" => Yii::$app->params['frontUrl'] . "/chat/index?account=" . $account,
  384. "data" => ["first" => ["value" => "亲,有什么需要可以帮到您,点此联系客服。", "color" => "#173177"],
  385. "keyword1" => ["value" => '前往聊天页', "color" => "#173177"],
  386. "keyword2" => ["value" => '文字', "color" => "#173177"],
  387. "remark" => ["value" => '点击与客服聊天', "color" => "#173177"]
  388. ]
  389. ];
  390. wxUtil::sendTaskInform($data, $merchant);
  391. }
  392. util::end();
  393. }
  394. //$text = $this->replyTextContent("^_^");
  395. $text = $this->replyTextContent(Yii::$app->params['mallDomain'] . '/#/?account=' . $merchantId);
  396. $pc = new \WXBizMsgCrypt($openToken, $encodingAesKey, $openAppId);
  397. $encryptMsg = '';
  398. $pc->encryptMsg($text, $timestamp, $nonce, $encryptMsg);//加密
  399. echo $encryptMsg;
  400. }
  401. } elseif ($this->msgType == 'image') {
  402. $PicUrl = (string)$PicUrl;
  403. if (empty($PicUrl)) {
  404. util::end();
  405. }
  406. $folder = Yii::getAlias('@webroot') . '/../../images';
  407. $pre = '/weixinChat/' . date('Y') . '/' . date('m') . '/' . date("d") . '/';
  408. if (!file_exists($folder . $pre)) {
  409. mkdir($folder . $pre, 0777, true);
  410. }
  411. $preFileName = substr(md5($userId), -4);
  412. $preName = $preFileName . stringUtil::buildOrderNo();
  413. $extName = '.jpg';
  414. $name = $preName . $extName;
  415. $fullFileName = $folder . $pre . $name;
  416. $fileName = $pre . $name;
  417. $curl = new curl\Curl();
  418. $result = $curl->get($PicUrl);
  419. $fp2 = @fopen($fullFileName, 'a');//文件大小
  420. fwrite($fp2, $result);
  421. fclose($fp2);
  422. //生成300缩略图
  423. $dstImg300 = $folder . $pre . $preName . '_300.' . $extName;
  424. $img2thumbReturn = util::img2thumb($fullFileName, $dstImg300, $width = 300, $height = 0, $cut = 0, $proportion = 0);
  425. $srcImgWidth = isset($img2thumbReturn['width']) ? $img2thumbReturn['width'] : 0;
  426. $srcImgHeight = isset($img2thumbReturn['height']) ? $img2thumbReturn['height'] : 0;
  427. $invalid = '/images/invalid.jpg';
  428. $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;" />';
  429. //将图片转发到管理员微信上
  430. $adminId = $merchant['adminId'];
  431. $admin = xhAdminService::getById($adminId);
  432. if (empty($admin)) {
  433. util::stop('没有管理员');
  434. }
  435. $adminOpenId = $admin['openId'];
  436. $adminId = $admin['id'];
  437. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  438. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  439. if (empty($connect) || ($now - $connect) > 100) {
  440. $allTM = xhTMessageService::getList($merchantId);
  441. $shortTempId = 'OPENTM200605630';
  442. if (isset($allTM[$shortTempId])) {
  443. $tempId = $allTM[$shortTempId];
  444. $data = [
  445. "touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  446. "data" => ["first" => ["value" => "{$user['userName']} 发来图片", "color" => "#173177"],
  447. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  448. "keyword2" => ["value" => '图片', "color" => "#173177"],
  449. "remark" => ["value" => '请登陆后台查看', "color" => "#173177"]]];
  450. wxUtil::sendTaskInform($data, $merchant);
  451. }
  452. }
  453. //记录商家的新消息用户有谁。
  454. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  455. //记录商家的最近联系人
  456. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  457. //设置商家与用户最后一次会话时间。
  458. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  459. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  460. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  461. } elseif ($this->msgType == 'voice') {
  462. $Content = '<span voiceId="' . $MediaId . '">【提示】客户发来一条语音消息,请登陆微信公众号后台查看。</span>';
  463. $adminId = $merchant['adminId'];
  464. $admin = xhAdminService::getById($adminId);
  465. if (empty($admin)) {
  466. Yii::warning("没有管理员,merchantId:" . $merchantId);
  467. util::end();
  468. }
  469. $adminOpenId = $admin['openId'];
  470. $adminId = $admin['id'];
  471. //获取商家与用户最后一次会话时间。如果是首次会话或中断对话持续100秒,则通过发公众号通知有新消息
  472. $connect = Yii::$app->redis->executeCommand('GET', ["merchant_{$merchantId}_new_msg_last_time"]);
  473. if (empty($connect) || ($now - $connect) > 100) {
  474. $allTM = xhTMessageService::getList($merchantId);
  475. $shortTempId = 'OPENTM200605630';
  476. if (isset($allTM[$shortTempId])) {
  477. $tempId = $allTM[$shortTempId];
  478. $data = ["touser" => $adminOpenId, "template_id" => $tempId, "url" => "",
  479. "data" => [
  480. "first" => ["value" => "{$user['userName']} 发来语音", "color" => "#173177"],
  481. "keyword1" => ["value" => '新消息', "color" => "#173177"],
  482. "keyword2" => ["value" => '语音', "color" => "#173177"],
  483. "remark" => ["value" => '消息内容:请登陆后台查看', "color" => "#173177"]]];
  484. wxUtil::sendTaskInform($data, $merchant);
  485. }
  486. }
  487. //记录商家的新消息用户有谁。
  488. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_new_msg", $now, "{$userId}"]);
  489. //记录商家的最近联系人
  490. Yii::$app->redis->executeCommand('ZADD', ["merchant_{$merchantId}_history_chat_user", $now, "{$userId}"]);
  491. //设置商家与用户最后一次会话时间。
  492. Yii::$app->redis->executeCommand('SETEX', ["merchant_{$merchantId}_new_msg_last_time", 100, $now]);
  493. //商家需要接收的消息。key里 第二个参数 ourself表示自己的消息 themself表示对方的消息 {~CHAT~} 表示分隔符
  494. Yii::$app->redis->executeCommand('LPUSH', ["merchant_get_{$merchantId}_{$userId}", $now . '{~CHAT~}themself{~CHAT~}' . $Content]);
  495. } elseif ($this->msgType == 'video') {
  496. } elseif ($this->msgType == 'location') {
  497. } elseif ($this->msgType == 'link') {
  498. } else {
  499. }
  500. }
  501. }
  502. /**
  503. * 回复文字消息
  504. */
  505. private function replyTextContent($content)
  506. {
  507. $createTime = time();//响应当前时间
  508. $con = "<xml>
  509. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  510. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  511. <CreateTime>{$createTime}</CreateTime>
  512. <MsgType><![CDATA[text]]></MsgType>
  513. <Content><![CDATA[{$content}]]></Content>
  514. </xml>";
  515. return $con;
  516. }
  517. /**
  518. * 回复图片消息
  519. */
  520. private function replyPicContent($media_id)
  521. {
  522. $createTime = time();
  523. $con = "<xml>
  524. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  525. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  526. <CreateTime>{$createTime}</CreateTime>
  527. <MsgType><![CDATA[image]]></MsgType>
  528. <Image>
  529. <MediaId><![CDATA[{$media_id}]]></MediaId>
  530. </Image>
  531. </xml>";
  532. return $con;
  533. }
  534. /**
  535. * 回复单图文消息
  536. */
  537. private function replyNewsContent($title, $desc, $picUrl, $url)
  538. {
  539. $createTime = time();//响应当前时间
  540. $con = "<xml>
  541. <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
  542. <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
  543. <CreateTime>{$createTime}</CreateTime>
  544. <MsgType><![CDATA[news]]></MsgType>
  545. <ArticleCount>1</ArticleCount><Articles>
  546. <item>
  547. <Title><![CDATA[{$title}]]></Title>
  548. <Description><![CDATA[{$desc}]]></Description>
  549. <PicUrl><![CDATA[{$picUrl}]]></PicUrl>
  550. <Url><![CDATA[{$url}]]></Url>
  551. </item>
  552. </Articles></xml>";
  553. return $con;
  554. }
  555. /**
  556. * 回复视频消息
  557. * @param $title
  558. * @param $media_id
  559. * @param $description
  560. * @return string
  561. */
  562. private function replyVideoContent($title, $media_id, $description)
  563. {
  564. $createTime = time();//响应当前时间
  565. $con = "<xml>
  566. <ToUserName><![CDATA[{$this->toUsername}]]></ToUserName>
  567. <FromUserName><![CDATA[{$this->fromUsername}]]></FromUserName>
  568. <CreateTime>{$createTime}</CreateTime>
  569. <MsgType><![CDATA[video]]></MsgType>
  570. <Video>
  571. <MediaId><![CDATA[{$media_id}]]></MediaId>
  572. <Title><![CDATA[{$title}]]></Title>
  573. <Description><![CDATA[{$description}]]></Description>
  574. </Video>
  575. </xml>";
  576. return $con;
  577. }
  578. }