WxController.php 38 KB

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