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