WxController.php 32 KB

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