WxController.php 35 KB

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