WxController.php 38 KB

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