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