WxController.php 34 KB

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