WxController.php 38 KB

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