WxController.php 35 KB

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