WxController.php 26 KB

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