WxController.php 39 KB

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