WxController.php 35 KB

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