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