WxController.php 35 KB

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