WxController.php 38 KB

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