WxController.php 25 KB

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