WxController.php 38 KB

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