WxController.php 38 KB

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