WxController.php 38 KB

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