WxController.php 38 KB

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