WxController.php 25 KB

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