open.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. <?php
  2. /*
  3. 易企程客服. http://www.17cheng.cn
  4. CopyRight 2018 All Rights Reserved
  5. */
  6. //traceHttp();
  7. $datas = file_get_contents('json/config.json');
  8. $datas = json_decode($datas,true);
  9. define("TOKEN", "eqcxcx");
  10. define("AppID", $datas['AppID']);//Appsecret
  11. define("Appsecret", $datas['Appsecret']);
  12. define("bakuniacid", $datas['bakuniacid']);
  13. define("shangyong", $datas['shangyong']);
  14. define("EncodingAESKey", "53o42sbbzslie4tjbll3ta5zlwe11rrk53o42sbbzsl");
  15. require_once('php/wxBizMsgCrypt.php');
  16. $wechatObj = new wechatCallbackapiTest();
  17. if (!isset($_GET['echostr'])) {
  18. if(shangyong=="0"){
  19. $wechatObj->responseMsg();// 这里区分下是测试还是商用 .
  20. }else{
  21. $wechatObj->responseMsgsq();// 这里区分下是测试还是商用 .
  22. }
  23. }else{
  24. $wechatObj->valid();
  25. }
  26. class wechatCallbackapiTest
  27. {
  28. //验证签名
  29. public function valid()
  30. {
  31. $echoStr = $_GET["echostr"];
  32. $signature = $_GET["signature"];
  33. $timestamp = $_GET["timestamp"];
  34. $nonce = $_GET["nonce"];
  35. $tmpArr = array(TOKEN, $timestamp, $nonce);
  36. sort($tmpArr);
  37. $tmpStr = implode($tmpArr);
  38. $tmpStr = sha1($tmpStr);
  39. if($tmpStr == $signature){
  40. echo $echoStr;
  41. exit;
  42. }
  43. }
  44. //响应消息 审核
  45. public function responseMsgsq()
  46. {
  47. $timestamp = $_GET['timestamp'];
  48. $nonce = $_GET["nonce"];
  49. $msg_signature = $_GET['msg_signature'];
  50. $encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw";
  51. $this->logger('APPID:'.$_GET['APPID']);
  52. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  53. if (!empty($postStr)){
  54. //解密
  55. if ($encrypt_type == 'aes'){
  56. $pc = new WXBizMsgCrypt(TOKEN, EncodingAESKey, AppID);
  57. $this->logger(" D \r\n".$postStr);
  58. $decryptMsg = ""; //解密后的明文
  59. $errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg);
  60. $postStr = $decryptMsg;
  61. }
  62. $this->logger(" R \r\n".$postStr);
  63. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  64. $RX_TYPE = trim($postObj->MsgType);
  65. $ComponentVerifyTicket = trim($postObj->ComponentVerifyTicket);
  66. $this->logger(" T: \r\n".$ComponentVerifyTicket);
  67. if($ComponentVerifyTicket<>''){//保存即可.
  68. $res=file_put_contents("json/VerifyTicket.json", $ComponentVerifyTicket);
  69. $data_string='{
  70. "component_appid":"'.AppID.'" ,
  71. "component_appsecret": "'.Appsecret.'",
  72. "component_verify_ticket": "'.$ComponentVerifyTicket.'"
  73. }';
  74. // $bbb = http_post_data("https://api.weixin.qq.com/cgi-bin/component/api_component_token", $data_string);
  75. $this->logger(" B \r\n".$bbb);
  76. //echo "success";
  77. // exit;
  78. //echo "sucsess";
  79. }
  80. //消息类型分离
  81. switch ($RX_TYPE)
  82. {
  83. case "location":
  84. $result = $this->receiveEvent($RX_TYPE,$postObj);
  85. break;
  86. case "event":
  87. $result = $this->receiveEvent($RX_TYPE,$postObj);
  88. break;
  89. case "text":
  90. $result = $this->receiveText($postObj);
  91. break;
  92. default:
  93. $result = $this->receiveEvent($RX_TYPE,$postObj);
  94. break;
  95. }
  96. $this->logger(" Re: \r\n".$RX_TYPE.$result);
  97. //加密
  98. if ($encrypt_type == 'aes'){
  99. $encryptMsg = ''; //加密后的密文
  100. $errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg);
  101. $result = $encryptMsg;
  102. $this->logger(" E \r\n".$result);
  103. }
  104. echo $result;
  105. }else {
  106. echo "";
  107. exit;
  108. }
  109. }
  110. //正式响应消息
  111. public function responseMsg()
  112. {
  113. $timestamp = $_GET['timestamp'];
  114. $nonce = $_GET["nonce"];
  115. $msg_signature = $_GET['msg_signature'];
  116. $encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw";
  117. $this->logger('APPID:'.$_GET['APPID']);
  118. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  119. if (!empty($postStr)){
  120. if ($encrypt_type == 'aes'){ //解密
  121. $pc = new WXBizMsgCrypt(TOKEN, EncodingAESKey, AppID);
  122. $this->logger(" D \r\n".$postStr); //发来的加密文件
  123. $decryptMsg = "";
  124. $errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg);
  125. $postStr = $decryptMsg;
  126. }
  127. $this->logger(" R \r\n".$postStr);
  128. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  129. $RX_TYPE = trim($postObj->MsgType);
  130. $ComponentVerifyTicket = file_get_contents('json/VerifyTicket.json');//yaoshi
  131. $Mtoken= $this-> getMToken(AppID,Appsecret,$ComponentVerifyTicket,'11111');//拿到自己的密钥
  132. $this->logger(" M \r\n".$ComponentVerifyTicket);
  133. $this->logger(" M \r\n".$Mtoken);
  134. $ToUserName=$postObj->ToUserName; // 获取当前公众号的name
  135. $info = json_decode(file_get_contents("jsonX/info_".$ToUserName.".json"),true);//读取设置文件.
  136. $mini=$info['authorizer_info']['MiniProgramInfo'];
  137. if (is_array($mini)) { $xcx= true; }else{ $xcx= false; }
  138. $name=$info['authorizer_info']['nick_name'];//公众号名称
  139. $signature=$info['authorizer_info']['signature'];//公众号名称 signature
  140. $Cappid=$info['authorization_info']['authorizer_appid'];
  141. $refresh_token=$info['authorization_info']['authorizer_refresh_token'];
  142. $Atoken=$this->getCToken(AppID,$Cappid,$refresh_token,$Mtoken);
  143. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Atoken;
  144. // $aaa=sendmsg($FromUserName,$RX_TYPE,"测试:".$Content,$postObj,$url);
  145. //////////////////////////////////以上是获取token部分//////////////////////////////////////////////////////
  146. //$Content=trim($postObj->Content);
  147. $fromUsername = trim($postObj->FromUserName); //openid
  148. $toUsername = trim($postObj->ToUserName);
  149. $tousernamebak = $toUsername;
  150. $keyword = trim($postObj->Content);
  151. $sessionFrom = trim($postObj->SessionFrom);
  152. $MsgType = trim($postObj->MsgType);//消息类型 text event
  153. $Event = trim($postObj->Event);
  154. $json = file_get_contents('json/'.$toUsername.'.json');
  155. $arr = json_decode($json,true);
  156. $uniacid = $arr['uniacid'];//bakuniacid
  157. $bakuniacid = bakuniacid;//bakuniacid
  158. $website = $arr['website'];
  159. $fromuserid = $fromUsername;//
  160. $myopenid = trim($arr['openids']);//管理员id
  161. if ($keyword=='openid'){
  162. if ($xcx){
  163. sendmsg($fromuserid,$MsgType,$fromuserid,'',$url);//给用户发消息.
  164. exit;}
  165. else{
  166. $encrypt_type = 'aes11';
  167. $keyword=$fromuserid;
  168. $result = $this->transmitText($postObj, $keyword.$aaa);
  169. $encryptMsg = ''; //加密后的密文
  170. $errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg);
  171. $result = $encryptMsg;
  172. echo $result;
  173. exit;
  174. }
  175. }
  176. $json = file_get_contents("json/".$uniacid."_kefu.json");
  177. $kefuarr = json_decode($json,true); //客服列表
  178. ////////////////////////////////////////////////////////动作提示//////////////////////////////
  179. if ($MsgType == "event") {
  180. $event = $postObj->Event;
  181. $this->logger(" R \r\n 进入动作处理:".$MsgType);
  182. if(array_key_exists($fromuserid,$kefuarr)){ //判断是不是客服.
  183. $paiduinumber=count(file('json/'.$uniacid.'_paidui.json'));
  184. $liuyannumber=count(file('json/'.$toUsername.'_lishi.json'));
  185. $kehuopenid= $kefuarr[$fromuserid];
  186. //当前聊天的是?
  187. if (substr($kehuopenid,0,1)=='o'){
  188. if(!is_numeric($uniacid)){$uniacid=$bakuniacid;};
  189. $users=getuser($uniacid,$kehuopenid,$nickname,$website);
  190. $zhuangtai='当前聊天:['.$users['id'].']'.$users['nickname'];
  191. }else{
  192. $zhuangtai='休息中';
  193. if ($kehuopenid=='空闲') { $zhuangtai='当前空闲,有客户会立即进入聊天.';}
  194. if ($kehuopenid=='隐身') { $zhuangtai='当前隐身,客户可主动指定聊天.';}
  195. }
  196. $tongzhi='排队人数:'. $paiduinumber.'\n'.'留言条数:\n'. $liuyannumber.' \n'.$zhuangtai;
  197. $data1='{ "touser":"'.$fromuserid.'", "msgtype":"text",
  198. "text": { "content":"[客服上线工作提醒]\n '.$tongzhi.' " } }';
  199. $aaa = http_post_data($url, $data1); //减少骚扰 不通知
  200. exit;
  201. }
  202. //在线客服代码
  203. $this->logger(" R \r\n 是客户:".$MsgType);
  204. //继续上一次的对话
  205. $Kefuopenid=array_search($fromuserid,$kefuarr,true);
  206. if($Kefuopenid<>''){
  207. sendmsg($fromuserid,'text','客服还在,直接回复继续上次的对话,或者回复再见 结束对话','',$url);//给用户发消息.
  208. exit;
  209. }
  210. if($xcx){
  211. $this->logger(" R \r\n 是小程序:".$MsgType);
  212. $tablename=trim($arr['tablename']);//管理员id
  213. if ($tablename<>''){
  214. $culname=$arr['culname'];
  215. $findname=$arr['findname'];
  216. $nickname= Finduser($uniacid,$tablename,$culname,$fromUsername,$findname,$website);
  217. if(!$nickname)
  218. {
  219. $nickname ='';
  220. }
  221. //logger('findname:'. $nickname);
  222. }
  223. $unid=$uniacid;
  224. if(!is_numeric($uniacid)){$unid=$bakuniacid;};
  225. $userinfo = getuser($unid,$fromUsername,$nickname,$website);
  226. $this->logger(" R \r\n 客户信息:".json_encode($userinfo));
  227. } else{
  228. $user = getwxinfo($Atoken,$fromUsername);//微信公众号代码
  229. $unid=$uniacid;
  230. if(!is_numeric($uniacid)){$unid=$bakuniacid;};
  231. $userinfo = getuser($unid,$fromUsername,$user['nickname'],$website);//微信公众号代码
  232. }
  233. if ($arr['Gappid']<>''){ //网页授权
  234. // if((substr($userinfo['nickname'],0,6)=='会员')){
  235. $sqstr1=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid'];
  236. $sqstr="\n<a href='".$sqstr1."'>点链接快速接通客服</a>";
  237. // }
  238. }
  239. if (trim(trim($arr['默认']))<>''){
  240. $this->logger(" R \r\n 默认有:".$arr['默认']);
  241. zhishiku($fromuserid,trim($arr['默认']),$uniacid,$url,$zxkefu,$userinfo) ;
  242. }else{
  243. $this->logger(" R \r\n 默认无:".$name.trim($arr['默认']));
  244. sendmsg($fromuserid,'text','你好!欢迎访问'.$name.'.'.$signature,'',$url);//给用户发消息.
  245. }
  246. $zxkefu="\n在线客服:回复名字接通\n".zxkefu($uniacid,$kefuarr,$sqstr1);
  247. if($userinfo['lastliao']<>null){$zxkefu.="\n上次接待客服是:".$userinfo['lastliao'];}
  248. $zxkefu.=$sqstr;
  249. $caidan=trim($arr['Gjsonid']);//进入通知:
  250. if ($caidan<>''){//暂时屏蔽这里.3.15
  251. // $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题
  252. // $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken;
  253. // $data1='{ "touser":"'.$arr['Gopenids'].'", "msgtype":"text",
  254. // "text": { "content":"[小程序'.$uniacid.'进入提醒]\n '.$userinfo['nickname'].' " } }';
  255. // $aaa = http_post_data($url1, $data1); // //通知到公共号
  256. }
  257. $this->logger(" R \r\n 完成.:" );
  258. exit;
  259. }
  260. ////////////////////////////////////////////////结束动作///////////////////////////////
  261. //print_r($kefuarr);
  262. //$arr= array_keys($arr1);//openid
  263. //处理客服消息模块开始
  264. if(array_key_exists($fromuserid,$kefuarr)){//客服消息处理
  265. if (substr($keyword,0,10)=='@所有人'){//@所有人
  266. atsuoyouren($uniacid,$website,$keyword,$fromuserid,$url,$toUsername);
  267. exit;
  268. }
  269. //处理@----某人命令
  270. if(substr($keyword,0,1)=='@'){//@某人
  271. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  272. $kefuname = $kefulist[$fromuserid];
  273. atmouren($keyword,$uniacid,$website,$fromuserid,$url,$kefuname);
  274. exit;
  275. }
  276. if($keyword=='p'){$keyword='下一个'; }
  277. if($keyword=='m'){$keyword='排队'; }
  278. if($keyword=='0'){$keyword='清零'; }
  279. //客服来的消息处理
  280. $kehuopenid= $kefuarr[$fromuserid];//
  281. // echo '找到客户:'.$kehuopenid;
  282. //判断是不是有客户
  283. if (substr($kehuopenid,0,1)=='o'){
  284. //有客户 ,直接发消息过去: 判断消息是不是@
  285. if (glymingling($uniacid,$fromuserid,$kehuopenid,$keyword,$arr['结束语'],$kefuarr,$url,$toUsername)){//是管理员命令
  286. // echo '命令!';
  287. }else{
  288. //查找客服信息.
  289. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  290. $kefuname = $kefulist[$fromuserid];
  291. // echo '给:'.$kefuarr[$fromuserid].'发内容'.$keyword;
  292. $bbb=sendmsg($kehuopenid,$MsgType,$kefuname.':'.$keyword,$postObj,$url);//给用户发消息.
  293. //增加判断.消息失败提示.
  294. if (json_decode($bbb, true)['errcode']<>0){
  295. // $data2='{ "touser":"'.$fromUsername.'", "msgtype":"text",
  296. // "text": { "content":" 客服离开... 消息已存入信箱.'.json_decode($bbb, true)['errcode'].'" } }'; //当没有约定好的回复时,这么回复。
  297. sendmsg($fromUsername,'text','客户可能已经离开了.','',$url);//给用户发消息.
  298. // savejson('json/'.$toUsername.'_lishi.json', '@'.$paidui['id'].'_'.$content.''.$keyword );
  299. }
  300. //sendmsg($openid,$msgtype,$keyword,$postObj,$url)
  301. }
  302. }else{
  303. //没客户接待时,可能发的命令:下一个.
  304. if (glymingling($uniacid,$fromuserid,$kehuopenid,$keyword,$arr['结束语'],$kefuarr,$url,$toUsername,$website)){
  305. //echo '是命令!';zaij
  306. }else{
  307. // echo '给:'.$kefuarr[$fromuserid].'发内容'.$keyword;
  308. // 空闲时 可以玩玩素材库 .
  309. if (!zhishiku($fromuserid,$keyword,$uniacid,$url,'',$userinfo)){
  310. sendmsg($fromuserid,'text','暂无接待客户,可发送命令下一个接通.','',$url,$toUsername,$website);//给用户发消息.
  311. }
  312. }
  313. //客服状态. kong mang 判断是不是要上班?或者其他命令 比如 下一个 等.
  314. }
  315. }else{
  316. // echo "not found kefu--";//不是客服 则看谁空闲? 规则 先找老客服 .
  317. //反查是否在队列
  318. //先看客户是不是...选了指定的客服. 客服小李 正在咨询的时候 是不能调出的.除非.
  319. $Kefuopenid=array_search($fromuserid,$kefuarr,true);
  320. if($Kefuopenid<>'')
  321. {
  322. // echo "这是用户,正在咨询的客服是:";
  323. // 用户发 再见 主动离线 . 更新客服列表 . 告诉客服 告诉客户
  324. if (substr($keyword,0,6)=='再见'){
  325. // sendmsg($fromuserid,'text',$arr['结束语'],'',$url);//说再见.
  326. jieshuyu($arr['结束语'],$uniacid,$fromuserid,$website,$url);
  327. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  328. $kefulist = json_decode($json,true);
  329. $kefuname = $kefulist[$Kefuopenid];
  330. edituser($uniacid,$fromuserid,'',$website,$avartar,$zhuangtai,$kefuname);
  331. $json = file_get_contents("json/".$uniacid."_paidui.json");
  332. $paiduinum = count(json_decode($json,true));
  333. sendmsg($Kefuopenid,'text','当前客户已经离开,发下一个接通.当前有'.$paiduinum.'人排队.','',$url);//说再见.
  334. $kefuarr[$Kefuopenid]='空闲';
  335. //建立对接 同时通知双方. 发两次消息.
  336. exec("rm -f ".'json/'.$uniacid.'_kefu.json');
  337. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  338. }else{
  339. if(!is_numeric($uniacid)){$uniacid=$bakuniacid;}
  340. $users=getuser($uniacid,$fromuserid,$nickname,$website);
  341. $bbb=sendmsg($Kefuopenid,$MsgType,'['.$users['id'].']'.$users['nickname'].':'.$keyword,$postObj,$url);
  342. if (json_decode($bbb, true)['errcode']<>0){
  343. sendmsg($fromUsername,'text','客服忙..已经存入留言板...\n 回复 再见 结束会话.','',$url);//给用户发消息.
  344. // savejson('json/'.$toUsername.'_lishi.json', '@'.$users['id'].'_'.$users['nickname'].''.$keyword );
  345. file_put_contents('json/'.$toUsername.'_lishi.json', '@'.$users['id'].'_'.$users['nickname'].''.$keyword .PHP_EOL, FILE_APPEND);
  346. }
  347. }
  348. }else{//没在咨询,检查是否有空闲客服
  349. if ( strpos($arr['kefustr'],$keyword)>0){//客户发张三
  350. $kongkefu='';
  351. $zhiding=1;
  352. }else{
  353. $kongkefu=array_search('空闲',$kefuarr,true);
  354. }
  355. if($kongkefu<>''){
  356. //echo '当前有空的客服:';
  357. //echo $kongkefu;
  358. $kefuarr[$kongkefu]=$fromuserid;
  359. //建立对接 同时通知双方. 发两次消息.
  360. exec("rm -f ".'json/'.$uniacid.'_kefu.json');
  361. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  362. //增加获取用户信息功能. 没排队 直接进入 需要查客户信息.
  363. $unid=$uniacid;
  364. if(!is_numeric($uniacid)){$unid=$bakuniacid;};
  365. $users=getuser($unid,$fromuserid,$nickname,$website);
  366. sendmsg($kongkefu,'text',$users['id'].$users['nickname'].':'.$keyword,'',$url);//通知客服
  367. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  368. $kefuname = $kefulist[$kongkefu];
  369. sendmsg($fromuserid,'text',$kefuname.':你好,有什么可以帮到你的?','',$url);//通知客服
  370. $tongzhiadmin=$kefuname.' 接入了新客户.['.$users['id'].']'.$users['nickname'];
  371. }else
  372. { //echo '当前客服都忙:/或者客户指定了客服.';
  373. //检查关键词回复 如果有则回复关键词
  374. if($MsgType=='text'){
  375. if (!zhishiku($fromuserid,$keyword,$uniacid,$url,'',$userinfo)){
  376. //当客服发送 指定客服的指令时 .如发 客服1
  377. if ($zhiding==1){//客户主动选择客服.
  378. $zd=zhaokefumingling($fromuserid,$uniacid,$keyword,$url,$kefuarr,$website);
  379. if($zd){ $tongzhiadmin=$keyword.' 被客户点名. ';}
  380. }else{
  381. $paidui=paidui($uniacid,$fromuserid,$website);//排队语自己组织.
  382. sendmsg($fromuserid,'text',$paidui,'',$url);//下发排队情况给用户.
  383. if($paidui<>'排队中,请耐心等待.'){
  384. $tongzhiadmin='有用户来:'.$keyword.'\n排队中:'.$paidui;
  385. }
  386. }
  387. }
  388. }else{//用户发送其他信息怎么办? 通知他排队.
  389. $paidui=paidui($uniacid,$fromuserid,$website);//排队语自己组织.
  390. sendmsg($fromuserid,'text',$paidui,'',$url);//下发排队情况给用户.
  391. sendmsg($myopenid,$MsgType,'其他类型文件',$postObj,$url);//其他文件 直接通知管理员..
  392. }
  393. // 是否在排队? 用数组键值查询, 没有.插入排队表 .有 返回排队顺序?
  394. }
  395. } //下发给总管理员通知;
  396. if ($tongzhiadmin<>''){
  397. $data1='{ "touser":"'.$myopenid.'", "msgtype":"text",
  398. "text": { "content":"[管理员提醒:]\n'.$tongzhiadmin.'" } }';
  399. $aaa = http_post_data($url, $data1); //减少骚扰 不通知
  400. }
  401. }
  402. //处理客服消息模块结束.
  403. ///////////////////////////////////////////////结束分配/////////////////////////////////
  404. //如果是公众号,可以自动回复:
  405. if ($encrypt_type == 'aes11'){
  406. $result = $this->transmitText($postObj, $keyword.$aaa);
  407. $encryptMsg = ''; //加密后的密文
  408. $errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg);
  409. $result = $encryptMsg;
  410. $this->logger(" E \r\n".$result);
  411. }
  412. echo $result;
  413. }else {
  414. echo "";
  415. exit;
  416. }
  417. }
  418. //接收事件消息
  419. private function receiveEvent($RX_TYPE,$object)
  420. {
  421. $content = "";
  422. // switch ($object->Event)
  423. // {
  424. // case "subscribe":
  425. // $content = "欢迎关注,系统正在升级. ";
  426. // break;
  427. // }
  428. $content= $RX_TYPE."from_callback";
  429. $result = $this->transmitText($object, $content);
  430. return $result;
  431. }
  432. //接收文本消息
  433. private function receiveText($object)
  434. {
  435. // $keyword = trim($object->Content);
  436. $needle ='QUERY_AUTH_CODE:';
  437. $tmparray = explode($needle,$object['Content']);
  438. if(count($tmparray)>1){
  439. // trace($response,"解密后: " );
  440. //3、模拟粉丝发送文本消息给专用测试公众号,第三方平台方需在5秒内返回空串
  441. //表明暂时不回复,然后再立即使用客服消息接口发送消息回复粉丝
  442. $contentx = str_replace ($needle,'',$object['Content']);//将$query_auth_code$的值赋值给API所需的参数authorization_code
  443. $this->authorization_code = $contentx;//authorization_code
  444. // trace($contentx,'authorization_code');
  445. //使用授权码换取公众号或小程序的接口调用凭据和授权信息
  446. $postdata = array(
  447. "component_appid"=>$this->appid,
  448. "authorization_code"=>$this->authorization_code,
  449. );
  450. $ComponentVerifyTicket = file_get_contents('json/VerifyTicket.json');
  451. $token= getToken(AppID,Appsecret,$ComponentVerifyTicket,'11111');
  452. $url="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=$token";
  453. $authorization=http_post_data($url,$data);
  454. $auth=json_decode($authorization,true);
  455. //authorizer_access_token
  456. $authorizer_access_token=$auth['authorization_info']['authorizer_access_token'];
  457. $content_re = $contentx."_from_api";
  458. echo '';
  459. $data = array(
  460. "touser"=>$object['FromUserName'],
  461. "msgtype"=>"text",
  462. "text" => array(
  463. "content" =>$content_re
  464. )
  465. );
  466. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
  467. $ret = http_post_data($url, $data);
  468. }else{
  469. $content="TESTCOMPONENT_MSG_TYPE_TEXT_callback";
  470. $result = $this->transmitText($object, $content);
  471. return $result;}
  472. }
  473. //回复文本消息
  474. private function transmitText($object, $content)
  475. {
  476. $xmlTpl = "<xml>
  477. <ToUserName><![CDATA[%s]]></ToUserName>
  478. <FromUserName><![CDATA[%s]]></FromUserName>
  479. <CreateTime>%s</CreateTime>
  480. <MsgType><![CDATA[text]]></MsgType>
  481. <Content><![CDATA[%s]]></Content>
  482. </xml>";
  483. $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
  484. return $result;
  485. }
  486. //回复图文消息
  487. private function transmitNews($object, $newsArray)
  488. {
  489. if(!is_array($newsArray)){
  490. return;
  491. }
  492. $itemTpl = " <item>
  493. <Title><![CDATA[%s]]></Title>
  494. <Description><![CDATA[%s]]></Description>
  495. <PicUrl><![CDATA[%s]]></PicUrl>
  496. <Url><![CDATA[%s]]></Url>
  497. </item>
  498. ";
  499. $item_str = "";
  500. foreach ($newsArray as $item){
  501. $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
  502. }
  503. $xmlTpl = "<xml>
  504. <ToUserName><![CDATA[%s]]></ToUserName>
  505. <FromUserName><![CDATA[%s]]></FromUserName>
  506. <CreateTime>%s</CreateTime>
  507. <MsgType><![CDATA[news]]></MsgType>
  508. <ArticleCount>%s</ArticleCount>
  509. <Articles>
  510. $item_str </Articles>
  511. </xml>";
  512. $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
  513. return $result;
  514. }
  515. //回复音乐消息
  516. private function transmitMusic($object, $musicArray)
  517. {
  518. $itemTpl = "<Music>
  519. <Title><![CDATA[%s]]></Title>
  520. <Description><![CDATA[%s]]></Description>
  521. <MusicUrl><![CDATA[%s]]></MusicUrl>
  522. <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
  523. </Music>";
  524. $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
  525. $xmlTpl = "<xml>
  526. <ToUserName><![CDATA[%s]]></ToUserName>
  527. <FromUserName><![CDATA[%s]]></FromUserName>
  528. <CreateTime>%s</CreateTime>
  529. <MsgType><![CDATA[music]]></MsgType>
  530. $item_str
  531. </xml>";
  532. $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
  533. return $result;
  534. }
  535. //日志记录
  536. public function logger($log_content)
  537. {
  538. if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
  539. sae_set_display_errors(false);
  540. sae_debug($log_content);
  541. sae_set_display_errors(true);
  542. }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
  543. $max_size = 500000;
  544. $log_filename = "log_wx_open.xml";
  545. if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
  546. file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
  547. }
  548. }
  549. public function getNewCToken($Mappid,$Cappid,$refresh_token,$Mtoken){
  550. $data_string='{
  551. "component_appid":"'.$Mappid.'",
  552. "authorizer_appid":"'.$Cappid.'",
  553. "authorizer_refresh_token":"'.$refresh_token.'",
  554. }';
  555. $access_token_Arr = http_post_data("https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=$Mtoken", $data_string);
  556. //$access_token_Arr=json_decode($access_token_Arr,true);
  557. return $access_token_Arr;
  558. }
  559. public function getCToken($Mappid,$Cappid,$refresh_token,$Mtoken){
  560. $file = file_get_contents("jsonX/{$Cappid}_token.json",true);
  561. $result = json_decode($file,true);
  562. if (time() > $result['expires']){
  563. // $data = array();
  564. $jsonStr = $this->getNewCToken($Mappid,$Cappid,$refresh_token,$Mtoken);
  565. // $jsonStr = json_encode($data);
  566. $fp = fopen("jsonX/{$Cappid}_token.json", "w");
  567. fwrite($fp, $jsonStr);
  568. fclose($fp);
  569. $data=json_decode($jsonStr,true);
  570. return $data['authorizer_access_token'];
  571. }else{
  572. return $result['authorizer_access_token'];
  573. }
  574. }
  575. public function https_request ($url){
  576. $ch = curl_init();
  577. curl_setopt($ch, CURLOPT_URL, $url);
  578. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  579. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  580. $out = curl_exec($ch);
  581. curl_close($ch);
  582. return json_decode($out,true);
  583. }
  584. public function traceHttp()
  585. {
  586. logger("\n\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"].(strstr($_SERVER["REMOTE_ADDR"],'101.226')? " FROM WeiXin": "Unknown IP"));
  587. logger("QUERY_STRING:".$_SERVER["QUERY_STRING"]);
  588. }
  589. public function getMToken($appid,$appsecret,$ComponentVerifyTicket,$jsonid){
  590. $file = file_get_contents("jsonX/{$appid}_token.json",true);
  591. $result = json_decode($file,true);
  592. if (time() > $result['expires']){
  593. $data = array();
  594. $data['component_access_token'] =$this->getNewToken($appid,$appsecret,$ComponentVerifyTicket);
  595. $data['expires']=time()+6200;
  596. $jsonStr = json_encode($data);
  597. $fp = fopen("jsonX/{$appid}_token.json", "w");
  598. fwrite($fp, $jsonStr);
  599. fclose($fp);
  600. return $data['component_access_token'];
  601. }else{
  602. return $result['component_access_token'];
  603. }
  604. }
  605. public function getNewToken($appid,$appsecret,$ComponentVerifyTicket){
  606. $data_string='{
  607. "component_appid":"'.$appid.'" ,
  608. "component_appsecret": "'.$appsecret.'",
  609. "component_verify_ticket": "'.$ComponentVerifyTicket.'"
  610. }';
  611. $access_token_Arr = http_post_data("https://api.weixin.qq.com/cgi-bin/component/api_component_token", $data_string);
  612. //echo "<br>---";
  613. $access_token_Arr=json_decode($access_token_Arr,true);
  614. return $access_token_Arr['component_access_token'];
  615. }
  616. }
  617. function sendmsg($openid,$msgtype,$keyword,$postObj,$url){
  618. //消息处理模块.
  619. switch ($msgtype)
  620. {
  621. case 'text':
  622. $data1='{ "touser":"'.$openid.'", "msgtype":"text",
  623. "text": { "content":" '.$keyword.' " } }';
  624. break;
  625. case 'image':
  626. $MediaId = $postObj->MediaId;
  627. $data1=' { "touser":"'.$openid.'", "msgtype":"image",
  628. "image": { "media_id":"'.$MediaId.'" }}';
  629. break;
  630. case 'voice':
  631. $MediaId = $postObj->MediaId;
  632. $Recognition = $postObj->Recognition;
  633. $data1=' { "touser":"'.$openid.'", "msgtype":"voice",
  634. "voice": { "media_id":"'.$MediaId.'" }}';
  635. break;
  636. case 'miniprogrampage':
  637. $data1='';
  638. break;
  639. default:
  640. $data1='';
  641. }
  642. $aaa = http_post_data($url, $data1);
  643. //echo '发送消息:'.$data1.$aaa;
  644. // logger('@@@@@@@@'.$data1.$aaa);
  645. return $aaa;
  646. }
  647. function http_post_data($url, $data_string) {
  648. $ch = curl_init();
  649. curl_setopt($ch, CURLOPT_POST, 1);
  650. curl_setopt($ch, CURLOPT_URL, $url);
  651. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  652. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  653. 'Content-Type: application/json; charset=utf-8',
  654. 'Content-Length: ' . strlen($data_string))
  655. );
  656. ob_start();
  657. curl_exec($ch);
  658. $return_content = ob_get_contents();
  659. //echo $return_content."<br>";
  660. ob_end_clean();
  661. $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  662. // return array($return_code, $return_content);
  663. return $return_content;
  664. }
  665. function getuser($ucid,$openid,$nickname,$website)
  666. {
  667. ///先判断缓存文件是否存在
  668. $json = file_get_contents("json/".$ucid."_user.json");
  669. $userinfos = json_decode($json,true);
  670. // $userid=$userinfos[$openid]['id'];
  671. // echo '找到缓存表:'.$userid;
  672. if (!array_key_exists($openid,$userinfos)){
  673. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getuser&m=qidong_app&openid=".$openid."&nickname=".$nickname;
  674. loggers($token_access_url) ;
  675. // echo $token_access_url;
  676. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  677. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  678. $nickname= $result['data']['wxapp'][0]['nickname'];
  679. $beizhu= $result['data']['wxapp'][0]['zhuangtai'];
  680. $lastliao= $result['data']['wxapp'][0]['lastliao'];
  681. if (trim($nickname)==null) {
  682. $nickname='会员'.$result['data']['wxapp'][0]['id'];
  683. $isid=1;
  684. }
  685. $userid=$result['data']['wxapp'][0]['id'];
  686. $data = array(
  687. 'nickname' => $nickname,
  688. 'id' => $userid,
  689. 'beizhu' => $beizhu,
  690. 'lastliao'=> $lastliao
  691. );
  692. return $data ;
  693. }else
  694. {
  695. // echo '找到缓存 直接返回;';
  696. return $userinfos[$openid];
  697. }
  698. }
  699. function zxkefu($uniacid,$kefuarr,$sqstr1){//读取在线客服列表//下次升级点击接通??
  700. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  701. $kefulist = json_decode($json,true);
  702. $kefuopenid= array_keys($kefulist);//kfuopenid
  703. $kefuall='';
  704. $i=0;
  705. foreach ($kefuopenid as $kefuopenid){ //群发--
  706. //$kfopenid=$arr;
  707. if(substr($kefuarr[$kefuopenid],0,1)=="o"){
  708. $zt='忙碌';
  709. }else{
  710. $zt=$kefuarr[$kefuopenid];
  711. }
  712. if ($zt<>'隐身'){
  713. $i++;
  714. //$sqstr=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid']."&kfname=".$kfname;
  715. //$sqstr="\n<a href='".$sqstr."'>点此快速接通客服</a>";
  716. //$sqstr1=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid']."&kfname=".$kfname;
  717. if(($sqstr1=='') or ($zt=='忙碌')){
  718. $kefuall=$kefuall." ".$kefulist[$kefuopenid]."[".$zt."]";
  719. }else{
  720. $sqstr="\n<a href='".$sqstr1."&kfname=".$kefulist[$kefuopenid]."&kfopenid=".$kefuopenid."'>".$kefulist[$kefuopenid]."</a>";
  721. $kefuall=$kefuall." ".$sqstr."[".$zt."]";
  722. }
  723. if(($i % 2)==0){ $kefuall.="\n";}
  724. // $kefuall=$kefuall.' <a href="#">'.$kefulist[$kefuopenid].'</a>['.$zt.']';
  725. }
  726. }
  727. //logger($kefuall);
  728. return $kefuall;
  729. }
  730. function zhishiku($fromuserid,$keyword,$uniacid,$url,$addstr,$userinfo){
  731. //知识库处理模块
  732. //echo '<br>知识库模块<br>'.$keyword.$uniacid;
  733. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  734. $keys = json_decode($json,true);
  735. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  736. $numkeys = json_decode($json,true);
  737. if(is_numeric($keyword)){
  738. $send=$keys[$numkeys[$keyword]];
  739. }else {
  740. $send=$keys[$keyword]; //$keys['关于我们'];
  741. }
  742. if ( $send<>'' ) { //判断是否是知识库设置字段
  743. if ($send['link']['title']!=''){
  744. $send['link']['title']=str_replace('id',$userinfo['id'],$send['link']['title']);
  745. $send['link']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['link']['title']);
  746. }
  747. if ($send['miniprogrampage']['title']!=''){
  748. $send['miniprogrampage']['title']=str_replace('id',$userinfo['id'],$send['miniprogrampage']['title']);
  749. $send['miniprogrampage']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['miniprogrampage']['title']);
  750. }
  751. if ($send['text']['content']!=''){
  752. $send['text']['content']=str_replace('[id]',$userinfo['id'],$send['text']['content']);
  753. $send['text']['content']=str_replace('[name]',trim($userinfo['nickname']),$send['text']['content']);
  754. $send['text']['content']=changeurl($send['text']['content']);
  755. $send['text']['content'].=$addstr;
  756. }
  757. $send['touser']=$fromuserid;
  758. $data=json_encode($send,JSON_UNESCAPED_UNICODE);
  759. $aaa = http_post_data($url, $data);
  760. $zt=json_decode($aaa, true)['errcode'];
  761. if ($zt!=0){//下发未成功
  762. $data='{ "touser":"'.$fromuserid.'", "msgtype":"text",
  763. "text": { "content":" 系统忙 错误代码: ' . $zt . ' " } }';
  764. $aaa = http_post_data($url, $data);
  765. }
  766. return true;
  767. }else{
  768. return false;//不是知识.
  769. }
  770. }
  771. function zhaokefumingling($fromuserid,$uniacid,$keyword,$url,$kefuarr,$website){
  772. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  773. //$kefuname=substr($keyword,7);
  774. $Kefuopenid=array_search($keyword,$kefulist,true);//找到客服id
  775. if (substr($kefuarr[$Kefuopenid],0,1)=='o')//看客服状态 客服状态over
  776. {
  777. sendmsg($fromuserid,'text','客服忙,请稍后.','',$url);//下发排队情况给用户.
  778. return false;
  779. }else{//客服接入//
  780. if($Kefuopenid==''){
  781. sendmsg($fromuserid,'text','客服休息了.请稍后再试.','',$url);//下发排队情况给用户.
  782. return false;
  783. }else{//客服在,对接开始. 如果是排队发的 则删除排队.如果是没排队发的.则不排队.
  784. $kefuarr[$Kefuopenid]=$fromuserid;
  785. //建立对接 同时通知双方. 发两次消息.
  786. exec("rm -f ".'json/'.$uniacid.'_kefu.json');
  787. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  788. //增加获取用户信息功能. 没排队 直接进入 需要查客户信息.
  789. $json = file_get_contents("json/".$uniacid."_paidui.json");
  790. $paiduiarr = json_decode($json,true);
  791. if(array_key_exists($fromuserid,$paiduiarr)){//如果在排队则..
  792. $uid=$paiduiarr[$fromuserid]['id'];
  793. $nickname=$paiduiarr[$fromuserid]['nickname'];
  794. unset($paiduiarr[$fromuserid]);//删除它
  795. $res=file_put_contents("json/".$uniacid."_paidui.json", json_encode($paiduiarr));
  796. }else{//没排队 .就是上来就发的. 新用户就注册 老用户就获取.
  797. $users=getuser($uniacid,$fromuserid,$nickname,$website);
  798. $uid=$users['id'];
  799. $nickname=$users['nickname'];
  800. }
  801. sendmsg($Kefuopenid,'text','['.$uid.']'.$nickname.':'.$keyword.' 你好','',$url);//通知客服
  802. // $kefuname = $kefulist[$Kefuopenid];
  803. sendmsg($fromuserid,'text',$keyword.':你好,有什么可以帮到你的?','',$url);//通知客服
  804. return true;
  805. }
  806. }
  807. }
  808. function atsuoyouren($uniacid,$website,$keyword,$myopenid,$url,$toUsername){
  809. //@所有人
  810. $huncun= json_decode(alluser($uniacid,$website),true);
  811. $gjz=substr($keyword,10,strlen(trim($keyword))-10);
  812. if (substr ($keyword, -1)=='#'){
  813. $gjz=str_replace('#','|',$gjz);
  814. }
  815. $baogao=' {
  816. "title": "代发列表已经准备好!点此群发",
  817. "description": "本次准备发送: '.$huncun['count'].' 请1分钟内点击,过期失效.",
  818. "url": "'.$website.'addons/qidong_app/qunfa.php?uniacid='.$uniacid.'&keyword='.$gjz.'&tousername='.$toUsername.'&t='.time().'",
  819. "thumb_url": "'.$website.'/addons/qidong_app/icon.jpg"
  820. }';
  821. $data1='{ "touser":"'.$myopenid.'", "msgtype":"link", "link": '.$baogao.' }';
  822. $aaa = http_post_data($url, $data1); //
  823. }
  824. function atmouren($keyword,$uniacid,$website,$fromuserid,$url,$kefuname){
  825. $stri=0;
  826. $stri= stripos($keyword,':');
  827. if ($stri==0){$stri= stripos($keyword,' ') ;}
  828. if ($stri==0){$stri= stripos($keyword,':') ;}
  829. $nid=substr($keyword,1,$stri-1); //@12:=>12
  830. $say=trim(substr($keyword,$stri+1));//发送的内容:
  831. if($say==''){$say=$kefuname.'@你 ,客服上线了,邀请你进入会话.';}
  832. //判断say最后字符是# 则是关键词消息 991#
  833. $liuuser= hiuser($uniacid,$nid,$website);
  834. $result = substr ($say, -1); //当是# 关键字图文时 .
  835. if ($result=='#'){
  836. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  837. $keys = json_decode($json,true);
  838. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  839. $numkeys = json_decode($json,true);
  840. $gjz=substr($say,0,strlen($say)-1);
  841. if(is_numeric($gjz)){
  842. $send=$keys[$numkeys[$gjz]];
  843. } else {
  844. $send=$keys[$gjz]; //$keys['关于我们'];
  845. }
  846. $send['touser']=$liuuser['openid'];
  847. $nickname=$liuuser['nickname'];
  848. if($nickname==''){$nickname='会员'.$liuuser['id'];}
  849. $send['link']['title']=str_replace('[id]',$liuuser['id'],$send['link']['title']);
  850. $send['link']['title']=str_replace('[name]', trim($nickname),$send['link']['title']);
  851. $data=json_encode($send,JSON_UNESCAPED_UNICODE);
  852. $bbb = http_post_data($url, $data);
  853. // logger('单发:'.$gjz.'-'.$data);
  854. }else{
  855. sendmsg($liuuser['openid'],'text','['.$kefuname.'@你]:'.$say,'',$url);
  856. }
  857. if (json_decode($bbb, true)['errcode']==0)
  858. { $zt='送达';
  859. //对方正在输入...哈哈
  860. $data8='{ "touser":"'.trim($liuuser['openid']).'", "command":"Typing"}';
  861. $url8='https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token='.$Atoken;
  862. $bbb = http_post_data($url8, $data8);
  863. //logger($bbb);
  864. //结束输入判断.
  865. }else{
  866. $zt='失败,可能已经离线'.json_decode($bbb, true)['errcode']; };
  867. sendmsg($fromuserid,'text','[@'.$nid.'报告]:'.$zt,'',$url);
  868. //发送消息
  869. }
  870. function glymingling($uniacid,$openid,$kehuopenid,$keyword,$jsy,$kefuarr,$url,$toUsername,$website){
  871. //处理管理员命令 @某人命令?
  872. //echo '检查命令!';$
  873. if (strpos(',清零,下一个,隐身,看留言,上班,排队,@所有人,',$keyword)>0){
  874. //此处增加管理员命令列表处理.
  875. if($keyword=='看留言'){
  876. $json = file_get_contents('json/'.$toUsername.'_lishi.json');
  877. sendmsg($openid,'text','本次获取的内容,已清空留言板:\n'.$json,'',$url);
  878. exec("rm -f ".'json/'.$toUsername.'_lishi.json');
  879. break;
  880. }
  881. if($keyword=='排队'){
  882. $json = file_get_contents("json/".$uniacid."_paidui.json");
  883. $karr = json_decode($json,true);
  884. $pdrs=count($karr);
  885. sendmsg($openid,'text','排队人数:'.$pdrs,'',$url);//发排队人数.后面再做详情.??
  886. }
  887. if($keyword=='隐身'){
  888. $kefuarr[$openid]='隐身';
  889. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  890. sendmsg($openid,'text','设置隐身成功. 可被点名进入聊天.不能自动进入聊天.','',$url);
  891. }
  892. if($keyword=='清零'){
  893. exec("rm -f ".'json/'.$toUsername.'_paidui.json');
  894. exec("rm -f ".'json/'.$toUsername.'_token.json');
  895. exec("rm -f ".'log.xml');
  896. if (!file_exists('json/'.$toUsername.'_token.json')){
  897. $t="清零成功!";
  898. }else{
  899. $t="清零失败,请检查目录权限是否设置为777!";
  900. }
  901. sendmsg($openid,'text',$t,'',$url);
  902. }
  903. if($keyword=='上班'){
  904. $kefuarr[$openid]='空闲';
  905. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  906. sendmsg($openid,'text','设置上班成功. 可自动接入来访客户.','',$url);
  907. }
  908. if($keyword=='下一个'){
  909. //跟现在的说再见 ?再见语?
  910. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  911. $kefulist = json_decode($json,true);
  912. $kefuname = $kefulist[$openid];
  913. if (substr($kehuopenid,0,1)=='o'){
  914. //回复图文消息.
  915. jieshuyu($jsy,$uniacid,$kehuopenid,$website,$url);
  916. // sendmsg($kehuopenid,'text',$jsy,'',$url);//说再见.
  917. // $a=edituser($uniacid,$delid['openid'],'',$website);
  918. //$lastliao='';//最后聊天客服.
  919. edituser($uniacid,$kehuopenid,'',$website,$avartar,$zhuangtai,$kefuname);
  920. }
  921. //找到下一个客户?
  922. $json = file_get_contents("json/".$uniacid."_paidui.json");
  923. $paiduiarr = json_decode($json,true);
  924. $nextkh=array_shift($paiduiarr);//取出并从排队中删除第一个.
  925. if (substr($nextkh['openid'],0,1)=='o'){
  926. //print_r($nextkh);
  927. //echo '<hr>';
  928. //print_r('nextkhoid:'.$nextkh['openid']);
  929. sendmsg($nextkh['openid'],'text',$kefuname.':你好,久等了.','',$url);//新用户你好.
  930. $userjson=json_encode($paiduiarr);
  931. $res=file_put_contents("json/".$uniacid."_paidui.json",$userjson);//更新排队数据.
  932. $kefuarr[$openid]=$nextkh['openid'];//保存新的用户进来.;
  933. sendmsg($openid,'text','['.$nextkh['id'].']'.$nextkh['nickname'].'已经进入聊天.','',$url);//
  934. $res=file_put_contents("json/".$uniacid."_kefu.json",json_encode($kefuarr));//更新客服数据.
  935. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  936. $kefuname = $kefulist[$fromuserid];
  937. //sendmsg($nextkh['openid'],'text',$kefuname.':你好久等了.','',$url);//
  938. }else{//已无排队用户.修正客服表 保存.告诉客服.
  939. $kefuarr[$openid]='空闲';
  940. $res=file_put_contents("json/".$uniacid."_kefu.json",json_encode($kefuarr));//更新客服数据.
  941. sendmsg($openid,'text','已无排队用户.你的状态目前是空闲.\n常用命令: 上班 隐身 排队.','',$url);//新用户你好.
  942. }
  943. }
  944. return true;
  945. }else
  946. {
  947. return false;
  948. }
  949. }
  950. function paidui($uniacid,$openid,$website){
  951. $json = file_get_contents("json/".$uniacid."_paidui.json");
  952. $kefuarr = json_decode($json,true);
  953. if(array_key_exists($openid,$kefuarr)){
  954. return '排队中,请耐心等待.';//排队中...
  955. }else{
  956. $user=getuser($uniacid,$openid,$nickname,$website);//获取用户信息
  957. $userinfo=array('id'=>$user['id'],
  958. 'nickname'=>$user['nickname'],
  959. 'beizhu'=>$user['beizhu'],
  960. 'openid'=>$openid);
  961. $kefuarr[$openid]=$userinfo;
  962. $userjson=json_encode($kefuarr);
  963. $res=file_put_contents("json/".$uniacid."_paidui.json",$userjson);
  964. $qianmian=count($kefuarr)-1;
  965. return '已接入客服中心,前面有'.$qianmian.'人';//排队数量
  966. }
  967. }
  968. function changeurl($a){
  969. $bi= strpos($a,'[[');
  970. if ($bi==0){
  971. return $a;
  972. }else{
  973. $ei= strpos($a,']]');
  974. $qb=substr($a,0,$bi);
  975. $eb=substr($a,$ei+2);
  976. $b=substr($a,$bi+2,$ei-$bi-2);
  977. $ci=strpos($b,'|');
  978. $add=substr($b,0,$ci);
  979. $herf=substr($b,$ci+1,strlen($b)-$ci);
  980. }
  981. return $qb."<a href='".$herf."'>".$add."</a>".$eb;
  982. }
  983. function getwxinfo($token,$openid){
  984. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
  985. // logger($url);
  986. $access_token_Arr = https_request($url);
  987. return $access_token_Arr;
  988. }
  989. function hiuser($ucid,$id,$website){
  990. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getopenid&m=qidong_app&id=".$id;
  991. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  992. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  993. $data=$result['data'][0] ;
  994. return $data ;
  995. }
  996. function alluser($ucid,$website){
  997. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=Getallopenid&m=qidong_app";
  998. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  999. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  1000. $data=$result['data'] ;
  1001. return json_encode($data) ;
  1002. }
  1003. function edituser($ucid,$openid,$nickname,$website,$avartar,$zhuangtai,$lastliao) //改名取号
  1004. {
  1005. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=edituser&m=qidong_app&openid=".$openid."&nickname=".$nickname."&avartar=".$avartar."&lastliao=".$lastliao; //zhuangtai
  1006. // echo $token_access_url;
  1007. // exit;
  1008. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  1009. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  1010. $data=$result['data'];
  1011. if ($data==1){$data='改名成功!';}
  1012. else{$data='改名失败!';}
  1013. return $data ;
  1014. }
  1015. function jieshuyu($bye,$uniacid,$openid,$website,$url){
  1016. if(is_numeric($bye)){
  1017. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  1018. $keys = json_decode($json,true);
  1019. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  1020. $numkeys = json_decode($json,true);
  1021. $delid=getuser($uniacid,$openid,'',$website);
  1022. $send=$keys[$numkeys[$bye]];
  1023. if ($send['link']['title']!=''){
  1024. $send['link']['title']=str_replace('id',$delid['id'],$send['link']['title']);
  1025. $send['link']['title']=str_replace('[name]', trim($delid['nickname']),$send['link']['title']);
  1026. }
  1027. if ($send['miniprogrampage']['title']!=''){
  1028. $send['miniprogrampage']['title']=str_replace('id',$delid['id'],$send['miniprogrampage']['title']);
  1029. $send['miniprogrampage']['title']=str_replace('[name]', trim($delid['nickname']),$send['miniprogrampage']['title']);
  1030. }
  1031. if ($send['text']['content']!=''){
  1032. $send['text']['content']=str_replace('[id]',$delid['id'],$send['text']['content']);
  1033. $send['text']['content']=str_replace('[name]',trim($delid['nickname']),$send['text']['content']);
  1034. // logger('要替换的文本:'.$send['text']['content']);
  1035. $send['text']['content']=changeurl($send['text']['content']);
  1036. }
  1037. $send['touser']=trim($openid);
  1038. $data0=json_encode($send,JSON_UNESCAPED_UNICODE);
  1039. }
  1040. else {
  1041. $sends=$bye; //$keys['关于我们'];
  1042. $jieshuyu= str_replace('[name]',$delid['nickname'],$sends);
  1043. $jieshuyu=str_replace("{br}","\n",$jieshuyu);
  1044. $jieshuyu=changeurl($jieshuyu);
  1045. $data0='{ "touser":"'.trim($openid).'", "msgtype":"text",
  1046. "text": { "content":" '.$jieshuyu.' " } }';
  1047. }
  1048. $aaa = http_post_data($url, $data0);
  1049. // logger($data0);
  1050. }
  1051. function Finduser($ucid,$tablename,$culname,$openid,$findname,$website){
  1052. //&tablename=dc_user&culname=openid&findname=name&openid=ogMce0dAqzqm3LSCIBzoHb4XYgFU
  1053. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=finduser&m=qidong_app&tablename={$tablename}&culname={$culname}&findname={$findname}&openid={$openid}";
  1054. // logger( $token_access_url);
  1055. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  1056. //logger('--------------'.$res);
  1057. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  1058. $data=$result['data']['nickname'] ;
  1059. return $data ;
  1060. }
  1061. function loggers($log_content)
  1062. {
  1063. if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
  1064. sae_set_display_errors(false);
  1065. sae_debug($log_content);
  1066. sae_set_display_errors(true);
  1067. }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
  1068. $max_size = 500000;
  1069. $log_filename = "log_wx_open.xml";
  1070. if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
  1071. file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
  1072. }
  1073. }
  1074. ?>