WxController.php 34 KB

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