WxController.php 40 KB

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