WxController.php 35 KB

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