WxController.php 32 KB

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