kefu_d.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. <?php
  2. //echo checkSignature;
  3. /* 本代码已经申请著作权保护
  4. 盗版必究
  5. 法律顾问:北京东环律所事务所
  6. ?用插件的方式./...
  7. CopyRight 2017 www.17cheng.cn All Rights Reserved
  8. */
  9. header('Content-type:text/json');
  10. $stime=microtime(true);
  11. ini_set("display_errors", "off");
  12. define("TOKEN", "xcxkefu");
  13. $wechatObj = new wechatCallbackapiTest();
  14. if (isset($_GET['echostr'])) { //判断是不是首次验证
  15. $wechatObj->valid();
  16. }else{
  17. $wechatObj->responseMsg();
  18. }
  19. class wechatCallbackapiTest
  20. {
  21. public function valid()
  22. {
  23. $echoStr = $_GET["echostr"];
  24. if($this->checkSignature()){
  25. echo $echoStr;
  26. exit;
  27. }
  28. }
  29. private function checkSignature()
  30. {
  31. $signature = $_GET["signature"];
  32. $timestamp = $_GET["timestamp"];
  33. $nonce = $_GET["nonce"];
  34. $token = TOKEN;
  35. $tmpArr = array($token, $timestamp, $nonce);
  36. sort($tmpArr);
  37. $tmpStr = implode( $tmpArr );
  38. $tmpStr = sha1( $tmpStr );
  39. if( $tmpStr == $signature ){
  40. return true;
  41. }else{
  42. return false;
  43. }
  44. }
  45. public function responseMsg()
  46. {
  47. $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取数据
  48. // logger(time().$postStr);
  49. $xcx=true;//true 是小程序
  50. if (!empty($postStr)){
  51. //$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  52. if($xcx){
  53. $postObj =json_decode($postStr);}
  54. else{
  55. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  56. }
  57. $fromUsername = trim($postObj->FromUserName); //openid
  58. $toUsername = trim($postObj->ToUserName);
  59. $tousernamebak = $toUsername;
  60. $keyword = trim($postObj->Content);
  61. $sessionFrom = trim($postObj->SessionFrom);
  62. $MsgType = $postObj->MsgType;//消息类型 text event
  63. $Event = $postObj->Event;
  64. if ($Event == "CLICK") {
  65. $EventKey = $postObj->EventKey;
  66. $MsgType='text';
  67. $keyword=trim($EventKey);//修复公众号问题.
  68. logger('event:'.$Event.$MsgType.'key:'.$keyword);
  69. }
  70. $json = file_get_contents('json/'.$toUsername.'.json');
  71. $arr = json_decode($json,true);
  72. $uniacid = $arr['uniacid'];
  73. //echo $uniacid;
  74. $website = $arr['website'];
  75. define("APPID", $arr['APPID']);
  76. define("APPSECRET", $arr['APPSECRET']);
  77. $fromuserid = $fromUsername;//
  78. $myopenid = trim($arr['openids']);//管理员id
  79. $Atoken = getToken(APPID,APPSECRET,$toUsername);
  80. $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Atoken;
  81. if ($keyword=='openid'){
  82. sendmsg($fromuserid,$MsgType,$fromuserid,'',$url);//给用户发消息.
  83. exit;
  84. }
  85. //echo $Atoken ;
  86. $json = file_get_contents("json/".$uniacid."_kefu.json");
  87. $kefuarr = json_decode($json,true); //客服列表
  88. ////////////////////////////////////////////////////////动作提示//////////////////////////////
  89. if ($MsgType == "event") {
  90. $event = $postObj->Event;
  91. if(array_key_exists($fromuserid,$kefuarr)){
  92. logger($MsgType.'是客服.');
  93. $paiduinumber=count(file('json/'.$uniacid.'_paidui.json'));
  94. $liuyannumber=count(file('json/'.$toUsername.'_lishi.json'));
  95. $kehuopenid= $kefuarr[$fromuserid];
  96. if (substr($kehuopenid,0,1)=='o'){
  97. $users=getuser($uniacid,$kehuopenid,$nickname,$website);
  98. $zhuangtai='当前聊天:['.$users['id'].']'.$users['nickname'];
  99. }else{
  100. $zhuangtai='休息中';
  101. if ($kehuopenid=='空闲') { $zhuangtai='当前空闲,有客户会立即进入聊天.';}
  102. if ($kehuopenid=='隐身') { $zhuangtai='当前隐身,客户可主动指定聊天.';}
  103. }
  104. $tongzhi='排队人数:'. $paiduinumber.'\n'.'留言条数:\n'. $liuyannumber.' \n'.$zhuangtai;
  105. $data1='{ "touser":"'.$fromuserid.'", "msgtype":"text",
  106. "text": { "content":"[客服上线工作提醒]\n '.$tongzhi.' " } }';
  107. $aaa = http_post_data($url, $data1); //减少骚扰 不通知
  108. exit;
  109. }
  110. //在线客服代码
  111. //继续上一次的对话
  112. $Kefuopenid=array_search($fromuserid,$kefuarr,true);
  113. if($Kefuopenid<>''){
  114. sendmsg($fromuserid,'text','客服还在,直接回复继续上次的对话,或者回复再见 结束对话','',$url);//给用户发消息.
  115. exit;
  116. }
  117. if($xcx){
  118. $tablename=trim($arr['tablename']);//管理员id
  119. if ($tablename<>''){
  120. $culname=$arr['culname'];
  121. $findname=$arr['findname'];
  122. $nickname= Finduser($uniacid,$tablename,$culname,$fromUsername,$findname,$website);
  123. if(!$nickname)
  124. {
  125. $nickname ='';
  126. }
  127. //logger('findname:'. $nickname);
  128. }
  129. $userinfo = getuser($uniacid,$fromUsername,$nickname,$website);
  130. } else{
  131. $user = getwxinfo($Atoken,$fromUsername);//微信公众号代码
  132. $userinfo = getuser($uniacid,$fromUsername,$user['nickname'],$website);//微信公众号代码
  133. }
  134. //
  135. // 下一次增加在线客服提示 这里不提示先 .等下一版本.
  136. if ($arr['Gappid']<>''){ //网页授权
  137. // if((substr($userinfo['nickname'],0,6)=='会员')){
  138. $sqstr1=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid'];
  139. $sqstr="\n<a href='".$sqstr1."'>点链接快速接通客服</a>";
  140. // }
  141. }
  142. //logger('是客户:.'.$fromUsername);
  143. // if($event=='unsubscribe'){ $eve='取消关注'; exit; };//公众号专用
  144. //logger($fromuserid.'-'.$arr['默认'].$uniacid.$url);
  145. $zxkefu="\n在线客服:回复名字接通\n".zxkefu($uniacid,$kefuarr,$sqstr1);
  146. if($userinfo['lastliao']<>null){$zxkefu.="\n上次接待客服是:".$userinfo['lastliao'];}
  147. $zxkefu.=$sqstr;//[屏蔽一下 下一版发布.]
  148. zhishiku($fromuserid,trim($arr['默认']),$uniacid,$url,$zxkefu,$userinfo) ;
  149. $caidan=trim($arr['Gjsonid']);//进入通知:
  150. if ($caidan<>''){
  151. $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题
  152. // logger("通知下发:".$caidan_arr['APPID'].'-状态:'.$caidan_arr['openids']);
  153. $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken;
  154. $data1='{ "touser":"'.$arr['Gopenids'].'", "msgtype":"text",
  155. "text": { "content":"[小程序'.$uniacid.'进入提醒]\n '.$userinfo['nickname'].' " } }';
  156. $aaa = http_post_data($url1, $data1); // //通知到公共号
  157. // logger($data1.$aaa);
  158. }
  159. exit;
  160. }
  161. ////////////////////////////////////////////////结束动作///////////////////////////////
  162. //print_r($kefuarr);
  163. //$arr= array_keys($arr1);//openid
  164. //处理客服消息模块开始
  165. if(array_key_exists($fromuserid,$kefuarr)){//客服消息处理
  166. if (substr($keyword,0,10)=='@所有人'){//@所有人
  167. atsuoyouren($uniacid,$website,$keyword,$fromuserid,$url,$toUsername);
  168. exit;
  169. }
  170. //处理@----某人命令
  171. if(substr($keyword,0,1)=='@'){//@某人
  172. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  173. $kefuname = $kefulist[$fromuserid];
  174. atmouren($keyword,$uniacid,$website,$fromuserid,$url,$kefuname);
  175. exit;
  176. }
  177. if($keyword=='p'){$keyword='下一个'; }
  178. if($keyword=='m'){$keyword='排队'; }
  179. if($keyword=='0'){$keyword='清零'; }
  180. //客服来的消息处理
  181. $kehuopenid= $kefuarr[$fromuserid];//
  182. // echo '找到客户:'.$kehuopenid;
  183. //判断是不是有客户
  184. if (substr($kehuopenid,0,1)=='o'){
  185. //有客户 ,直接发消息过去: 判断消息是不是@
  186. if (glymingling($uniacid,$fromuserid,$kehuopenid,$keyword,$arr['结束语'],$kefuarr,$url,$toUsername)){//是管理员命令
  187. // echo '命令!';
  188. }else{
  189. //查找客服信息.
  190. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  191. $kefuname = $kefulist[$fromuserid];
  192. // echo '给:'.$kefuarr[$fromuserid].'发内容'.$keyword;
  193. $bbb=sendmsg($kehuopenid,$MsgType,$kefuname.':'.$keyword,$postObj,$url);//给用户发消息.
  194. //增加判断.消息失败提示.
  195. if (json_decode($bbb, true)['errcode']<>0){
  196. $data2='{ "touser":"'.$fromUsername.'", "msgtype":"text",
  197. "text": { "content":" 客服离开... 消息已存入信箱.'.json_decode($bbb, true)['errcode'].'" } }'; //当没有约定好的回复时,这么回复。
  198. sendmsg($fromUsername,'text','消息失败,客户可能已经离开了.','',$url);//给用户发消息.
  199. // savejson('json/'.$toUsername.'_lishi.json', '@'.$paidui['id'].'_'.$content.''.$keyword );
  200. }
  201. //sendmsg($openid,$msgtype,$keyword,$postObj,$url)
  202. }
  203. }else{
  204. //没客户接待时,可能发的命令:下一个.
  205. if (glymingling($uniacid,$fromuserid,$kehuopenid,$keyword,$arr['结束语'],$kefuarr,$url,$toUsername,$website)){
  206. //echo '是命令!';zaij
  207. }else{
  208. // echo '给:'.$kefuarr[$fromuserid].'发内容'.$keyword;
  209. // 空闲时 可以玩玩素材库 .
  210. if (!zhishiku($fromuserid,$keyword,$uniacid,$url,'',$userinfo)){
  211. sendmsg($fromuserid,'text','暂无接待客户,可发送命令下一个接通.','',$url,$toUsername,$website);//给用户发消息.
  212. }
  213. }
  214. //客服状态. kong mang 判断是不是要上班?或者其他命令 比如 下一个 等.
  215. }
  216. }else{
  217. // echo "not found kefu--";//不是客服 则看谁空闲? 规则 先找老客服 .
  218. //反查是否在队列
  219. //先看客户是不是...选了指定的客服. 客服小李 正在咨询的时候 是不能调出的.除非.
  220. $Kefuopenid=array_search($fromuserid,$kefuarr,true);
  221. if($Kefuopenid<>'')
  222. {
  223. // echo "这是用户,正在咨询的客服是:";
  224. // 用户发 再见 主动离线 . 更新客服列表 . 告诉客服 告诉客户
  225. if (substr($keyword,0,6)=='再见'){
  226. // sendmsg($fromuserid,'text',$arr['结束语'],'',$url);//说再见.
  227. jieshuyu($arr['结束语'],$uniacid,$fromuserid,$website,$url);
  228. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  229. $kefulist = json_decode($json,true);
  230. $kefuname = $kefulist[$Kefuopenid];
  231. edituser($uniacid,$fromuserid,'',$website,$avartar,$zhuangtai,$kefuname);
  232. $json = file_get_contents("json/".$uniacid."_paidui.json");
  233. $paiduinum = count(json_decode($json,true));
  234. sendmsg($Kefuopenid,'text','当前客户已经离开,发下一个接通.当前有'.$paiduinum.'人排队.','',$url);//说再见.
  235. $kefuarr[$Kefuopenid]='空闲';
  236. //建立对接 同时通知双方. 发两次消息.
  237. unlink('json/'.$uniacid.'_kefu.json');
  238. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  239. }else{
  240. $users=getuser($uniacid,$fromuserid,$nickname,$website);
  241. $bbb=sendmsg($Kefuopenid,$MsgType,'['.$users['id'].']'.$users['nickname'].':'.$keyword,$postObj,$url);
  242. if (json_decode($bbb, true)['errcode']<>0){
  243. sendmsg($fromUsername,'text','客服忙..已经存入留言板...\n 回复 再见 结束会话.','',$url);//给用户发消息.
  244. // savejson('json/'.$toUsername.'_lishi.json', '@'.$users['id'].'_'.$users['nickname'].''.$keyword );
  245. file_put_contents('json/'.$toUsername.'_lishi.json', '@'.$users['id'].'_'.$users['nickname'].''.$keyword .PHP_EOL, FILE_APPEND);
  246. }
  247. }
  248. }else{//没在咨询,检查是否有空闲客服
  249. if ( strpos($arr['kefustr'],$keyword)>0){//客户发张三
  250. $kongkefu='';
  251. $zhiding=1;
  252. }else{
  253. $kongkefu=array_search('空闲',$kefuarr,true);
  254. }
  255. if($kongkefu<>''){
  256. //echo '当前有空的客服:';
  257. //echo $kongkefu;
  258. $kefuarr[$kongkefu]=$fromuserid;
  259. //建立对接 同时通知双方. 发两次消息.
  260. unlink('json/'.$uniacid.'_kefu.json');
  261. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  262. //增加获取用户信息功能. 没排队 直接进入 需要查客户信息.
  263. $users=getuser($uniacid,$fromuserid,$nickname,$website);
  264. sendmsg($kongkefu,'text',$users['id'].$users['nickname'].':'.$keyword,'',$url);//通知客服
  265. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  266. $kefuname = $kefulist[$kongkefu];
  267. sendmsg($fromuserid,'text',$kefuname.':你好,有什么可以帮到你的?','',$url);//通知客服
  268. $tongzhiadmin=$kefuname.' 接入了新客户.['.$users['id'].']'.$users['nickname'];
  269. }else
  270. { //echo '当前客服都忙:/或者客户指定了客服.';
  271. //检查关键词回复 如果有则回复关键词
  272. if($MsgType=='text'){
  273. if (!zhishiku($fromuserid,$keyword,$uniacid,$url,'',$userinfo)){
  274. //当客服发送 指定客服的指令时 .如发 客服1
  275. if ($zhiding==1){//客户主动选择客服.
  276. $zd=zhaokefumingling($fromuserid,$uniacid,$keyword,$url,$kefuarr,$website);
  277. if($zd){ $tongzhiadmin=$keyword.' 被客户点名. ';}
  278. }else{
  279. $paidui=paidui($uniacid,$fromuserid,$website);//排队语自己组织.
  280. sendmsg($fromuserid,'text',$paidui,'',$url);//下发排队情况给用户.
  281. if($paidui<>'排队中,请耐心等待.'){
  282. $tongzhiadmin='有用户来:'.$keyword.'排队:'.$paidui;
  283. }
  284. }
  285. }
  286. }else{//用户发送其他信息怎么办? 通知他排队.
  287. $paidui=paidui($uniacid,$fromuserid,$website);//排队语自己组织.
  288. sendmsg($fromuserid,'text',$paidui,'',$url);//下发排队情况给用户.
  289. sendmsg($myopenid,$MsgType,'其他类型文件',$postObj,$url);//其他文件 直接通知管理员..
  290. }
  291. // 是否在排队? 用数组键值查询, 没有.插入排队表 .有 返回排队顺序?
  292. }
  293. } //下发给总管理员通知;
  294. if ($tongzhiadmin<>''){
  295. $data1='{ "touser":"'.$myopenid.'", "msgtype":"text",
  296. "text": { "content":"[管理员提醒:]\n'.$tongzhiadmin.'" } }';
  297. $aaa = http_post_data($url, $data1); //减少骚扰 不通知
  298. }
  299. }
  300. //处理客服消息模块结束.
  301. }else{///////////////////////////////////////////////////////////////
  302. echo "";
  303. exit;
  304. }
  305. }
  306. }
  307. function zhishiku($fromuserid,$keyword,$uniacid,$url,$addstr,$userinfo){
  308. //知识库处理模块
  309. //echo '<br>知识库模块<br>'.$keyword.$uniacid;
  310. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  311. $keys = json_decode($json,true);
  312. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  313. $numkeys = json_decode($json,true);
  314. if(is_numeric($keyword)){
  315. $send=$keys[$numkeys[$keyword]];
  316. }else {
  317. $send=$keys[$keyword]; //$keys['关于我们'];
  318. }
  319. if ( $send<>'' ) { //判断是否是知识库设置字段
  320. if ($send['link']['title']!=''){
  321. $send['link']['title']=str_replace('id',$userinfo['id'],$send['link']['title']);
  322. $send['link']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['link']['title']);
  323. }
  324. if ($send['miniprogrampage']['title']!=''){
  325. $send['miniprogrampage']['title']=str_replace('id',$userinfo['id'],$send['miniprogrampage']['title']);
  326. $send['miniprogrampage']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['miniprogrampage']['title']);
  327. }
  328. if ($send['text']['content']!=''){
  329. $send['text']['content']=str_replace('[id]',$userinfo['id'],$send['text']['content']);
  330. $send['text']['content']=str_replace('[name]',trim($userinfo['nickname']),$send['text']['content']);
  331. $send['text']['content']=changeurl($send['text']['content']);
  332. $send['text']['content'].=$addstr;
  333. }
  334. $send['touser']=$fromuserid;
  335. $data=json_encode($send,JSON_UNESCAPED_UNICODE);
  336. $aaa = http_post_data($url, $data);
  337. $zt=json_decode($aaa, true)['errcode'];
  338. if ($zt!=0){//下发未成功
  339. $data='{ "touser":"'.$fromuserid.'", "msgtype":"text",
  340. "text": { "content":" 系统忙 错误代码: ' . $zt . ' " } }';
  341. $aaa = http_post_data($url, $data);
  342. }
  343. return true;
  344. }else{
  345. return false;//不是知识.
  346. }
  347. }
  348. function sendmsg($openid,$msgtype,$keyword,$postObj,$url){
  349. //消息处理模块.
  350. switch ($msgtype)
  351. {
  352. case 'text':
  353. $data1='{ "touser":"'.$openid.'", "msgtype":"text",
  354. "text": { "content":" '.$keyword.' " } }';
  355. break;
  356. case 'image':
  357. $MediaId = $postObj->MediaId;
  358. $data1=' { "touser":"'.$openid.'", "msgtype":"image",
  359. "image": { "media_id":"'.$MediaId.'" }}';
  360. break;
  361. case 'voice':
  362. $MediaId = $postObj->MediaId;
  363. $Recognition = $postObj->Recognition;
  364. $data1=' { "touser":"'.$openid.'", "msgtype":"voice",
  365. "voice": { "media_id":"'.$MediaId.'" }}';
  366. break;
  367. case 'miniprogrampage':
  368. $data1='';
  369. break;
  370. default:
  371. $data1='';
  372. }
  373. $aaa = http_post_data($url, $data1);
  374. //echo '发送消息:'.$data1.$aaa;
  375. // logger('@@@@@@@@'.$data1.$aaa);
  376. return $aaa;
  377. }
  378. function http_post_data($url, $data_string) {
  379. $ch = curl_init();
  380. curl_setopt($ch, CURLOPT_POST, 1);
  381. curl_setopt($ch, CURLOPT_URL, $url);
  382. curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  383. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  384. 'Content-Type: application/json; charset=utf-8',
  385. 'Content-Length: ' . strlen($data_string))
  386. );
  387. ob_start();
  388. curl_exec($ch);
  389. $return_content = ob_get_contents();
  390. //echo $return_content."<br>";
  391. ob_end_clean();
  392. $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  393. // return array($return_code, $return_content);
  394. return $return_content;
  395. }
  396. function zhaokefumingling($fromuserid,$uniacid,$keyword,$url,$kefuarr,$website){
  397. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  398. //$kefuname=substr($keyword,7);
  399. $Kefuopenid=array_search($keyword,$kefulist,true);//找到客服id
  400. if (substr($kefuarr[$Kefuopenid],0,1)=='o')//看客服状态 客服状态over
  401. {
  402. sendmsg($fromuserid,'text','客服忙,请稍后.','',$url);//下发排队情况给用户.
  403. return false;
  404. }else{//客服接入//
  405. if($Kefuopenid==''){
  406. sendmsg($fromuserid,'text','客服休息了.请稍后再试.','',$url);//下发排队情况给用户.
  407. return false;
  408. }else{//客服在,对接开始. 如果是排队发的 则删除排队.如果是没排队发的.则不排队.
  409. $kefuarr[$Kefuopenid]=$fromuserid;
  410. //建立对接 同时通知双方. 发两次消息.
  411. unlink('json/'.$uniacid.'_kefu.json');
  412. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  413. //增加获取用户信息功能. 没排队 直接进入 需要查客户信息.
  414. $json = file_get_contents("json/".$uniacid."_paidui.json");
  415. $paiduiarr = json_decode($json,true);
  416. if(array_key_exists($fromuserid,$paiduiarr)){//如果在排队则..
  417. $uid=$paiduiarr[$fromuserid]['id'];
  418. $nickname=$paiduiarr[$fromuserid]['nickname'];
  419. unset($paiduiarr[$fromuserid]);//删除它
  420. $res=file_put_contents("json/".$uniacid."_paidui.json", json_encode($paiduiarr));
  421. }else{//没排队 .就是上来就发的. 新用户就注册 老用户就获取.
  422. $users=getuser($uniacid,$fromuserid,$nickname,$website);
  423. $uid=$users['id'];
  424. $nickname=$users['nickname'];
  425. }
  426. sendmsg($Kefuopenid,'text','['.$uid.']'.$nickname.':'.$keyword.' 你好','',$url);//通知客服
  427. // $kefuname = $kefulist[$Kefuopenid];
  428. sendmsg($fromuserid,'text',$keyword.':你好,有什么可以帮到你的?','',$url);//通知客服
  429. return true;
  430. }
  431. }
  432. }
  433. function atsuoyouren($uniacid,$website,$keyword,$myopenid,$url,$toUsername){
  434. //@所有人
  435. $huncun= json_decode(alluser($uniacid,$website),true);
  436. $gjz=substr($keyword,10,strlen(trim($keyword))-10);
  437. if (substr ($keyword, -1)=='#'){
  438. $gjz=str_replace('#','|',$gjz);
  439. }
  440. $baogao=' {
  441. "title": "代发列表已经准备好!点此群发",
  442. "description": "本次准备发送: '.$huncun['count'].' 请1分钟内点击,过期失效.",
  443. "url": "'.$website.'addons/qidong_app/qunfa.php?uniacid='.$uniacid.'&keyword='.$gjz.'&tousername='.$toUsername.'&t='.time().'",
  444. "thumb_url": "'.$website.'/addons/qidong_app/icon.jpg"
  445. }';
  446. $data1='{ "touser":"'.$myopenid.'", "msgtype":"link", "link": '.$baogao.' }';
  447. $aaa = http_post_data($url, $data1); //
  448. }
  449. function zxkefu($uniacid,$kefuarr,$sqstr1){//读取在线客服列表//下次升级点击接通??
  450. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  451. $kefulist = json_decode($json,true);
  452. $kefuopenid= array_keys($kefulist);//kfuopenid
  453. $kefuall='';
  454. $i=0;
  455. foreach ($kefuopenid as $kefuopenid){ //群发--
  456. //$kfopenid=$arr;
  457. if(substr($kefuarr[$kefuopenid],0,1)=="o"){
  458. $zt='忙碌';
  459. }else{
  460. $zt=$kefuarr[$kefuopenid];
  461. }
  462. if ($zt<>'隐身'){
  463. $i++;
  464. //$sqstr=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid']."&kfname=".$kfname;
  465. //$sqstr="\n<a href='".$sqstr."'>点此快速接通客服</a>";
  466. //$sqstr1=$website."addons/qidong_app/intenet.php?zfopenid=".$fromUsername."&toUsername=".$toUsername."&appid=".$arr['Gappid']."&kfname=".$kfname;
  467. if(($sqstr1=='') or ($zt=='忙碌')){
  468. $kefuall=$kefuall." ".$kefulist[$kefuopenid]."[".$zt."]";
  469. }else{
  470. $sqstr="\n<a href='".$sqstr1."&kfname=".$kefulist[$kefuopenid]."&kfopenid=".$kefuopenid."'>".$kefulist[$kefuopenid]."</a>";
  471. $kefuall=$kefuall." ".$sqstr."[".$zt."]";
  472. }
  473. if(($i % 2)==0){ $kefuall.="\n";}
  474. // $kefuall=$kefuall.' <a href="#">'.$kefulist[$kefuopenid].'</a>['.$zt.']';
  475. }
  476. }
  477. //logger($kefuall);
  478. return $kefuall;
  479. }
  480. function atmouren($keyword,$uniacid,$website,$fromuserid,$url,$kefuname){
  481. $stri=0;
  482. $stri= stripos($keyword,':');
  483. if ($stri==0){$stri= stripos($keyword,' ') ;}
  484. if ($stri==0){$stri= stripos($keyword,':') ;}
  485. $nid=substr($keyword,1,$stri-1); //@12:=>12
  486. $say=trim(substr($keyword,$stri+1));//发送的内容:
  487. if($say==''){$say=$kefuname.'@你 ,客服上线了,邀请你进入会话.';}
  488. //判断say最后字符是# 则是关键词消息 991#
  489. $liuuser= hiuser($uniacid,$nid,$website);
  490. $result = substr ($say, -1); //当是# 关键字图文时 .
  491. if ($result=='#'){
  492. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  493. $keys = json_decode($json,true);
  494. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  495. $numkeys = json_decode($json,true);
  496. $gjz=substr($say,0,strlen($say)-1);
  497. if(is_numeric($gjz)){
  498. $send=$keys[$numkeys[$gjz]];
  499. } else {
  500. $send=$keys[$gjz]; //$keys['关于我们'];
  501. }
  502. $send['touser']=$liuuser['openid'];
  503. $nickname=$liuuser['nickname'];
  504. if($nickname==''){$nickname='会员'.$liuuser['id'];}
  505. $send['link']['title']=str_replace('[id]',$liuuser['id'],$send['link']['title']);
  506. $send['link']['title']=str_replace('[name]', trim($nickname),$send['link']['title']);
  507. $data=json_encode($send,JSON_UNESCAPED_UNICODE);
  508. $bbb = http_post_data($url, $data);
  509. logger('单发:'.$gjz.'-'.$data);
  510. }else{
  511. sendmsg($liuuser['openid'],'text','['.$kefuname.'@你]:'.$say,'',$url);
  512. }
  513. if (json_decode($bbb, true)['errcode']==0)
  514. { $zt='送达';
  515. //对方正在输入...哈哈
  516. $data8='{ "touser":"'.trim($liuuser['openid']).'", "command":"Typing"}';
  517. $url8='https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token='.$Atoken;
  518. $bbb = http_post_data($url8, $data8);
  519. //logger($bbb);
  520. //结束输入判断.
  521. }else{
  522. $zt='失败,可能已经离线'.json_decode($bbb, true)['errcode']; };
  523. sendmsg($fromuserid,'text','[@'.$nid.'报告]:'.$zt,'',$url);
  524. //发送消息
  525. }
  526. function glymingling($uniacid,$openid,$kehuopenid,$keyword,$jsy,$kefuarr,$url,$toUsername,$website){
  527. //处理管理员命令 @某人命令?
  528. //echo '检查命令!';$
  529. if (strpos(',清零,下一个,隐身,看留言,上班,排队,@所有人,',$keyword)>0){
  530. //此处增加管理员命令列表处理.
  531. if($keyword=='看留言'){
  532. $json = file_get_contents('json/'.$toUsername.'_lishi.json');
  533. sendmsg($openid,'text','本次获取的内容,已清空留言板:\n'.$json,'',$url);
  534. unlink('json/'.$toUsername.'_lishi.json');
  535. break;
  536. }
  537. if($keyword=='排队'){
  538. $json = file_get_contents("json/".$uniacid."_paidui.json");
  539. $karr = json_decode($json,true);
  540. $pdrs=count($karr);
  541. sendmsg($openid,'text','排队人数:'.$pdrs,'',$url);//发排队人数.后面再做详情.??
  542. }
  543. if($keyword=='隐身'){
  544. $kefuarr[$openid]='隐身';
  545. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  546. sendmsg($openid,'text','设置隐身成功. 可被点名进入聊天.不能自动进入聊天.','',$url);
  547. }
  548. if($keyword=='清零'){
  549. unlink('json/'.$toUsername.'_paidui.json');
  550. unlink('json/'.$toUsername.'_token.json');
  551. unlink('log.xml');
  552. if (!file_exists('json/'.$toUsername.'_paidui.json')){
  553. $t="清零成功!";
  554. }else{
  555. $t="清零失败,请检查目录权限是否设置为777!";
  556. }
  557. sendmsg($openid,'text',$t,'',$url);
  558. }
  559. if($keyword=='上班'){
  560. $kefuarr[$openid]='空闲';
  561. $res=file_put_contents("json/".$uniacid."_kefu.json", json_encode($kefuarr));
  562. sendmsg($openid,'text','设置上班成功. 可自动接入来访客户.','',$url);
  563. }
  564. if($keyword=='下一个'){
  565. //跟现在的说再见 ?再见语?
  566. $json = file_get_contents("json/".$uniacid."_kefulist.json");//客服详情页
  567. $kefulist = json_decode($json,true);
  568. $kefuname = $kefulist[$openid];
  569. if (substr($kehuopenid,0,1)=='o'){
  570. //回复图文消息.
  571. jieshuyu($jsy,$uniacid,$kehuopenid,$website,$url);
  572. // sendmsg($kehuopenid,'text',$jsy,'',$url);//说再见.
  573. // $a=edituser($uniacid,$delid['openid'],'',$website);
  574. //$lastliao='';//最后聊天客服.
  575. edituser($uniacid,$kehuopenid,'',$website,$avartar,$zhuangtai,$kefuname);
  576. }
  577. //找到下一个客户?
  578. $json = file_get_contents("json/".$uniacid."_paidui.json");
  579. $paiduiarr = json_decode($json,true);
  580. $nextkh=array_shift($paiduiarr);//取出并从排队中删除第一个.
  581. if (substr($nextkh['openid'],0,1)=='o'){
  582. //print_r($nextkh);
  583. //echo '<hr>';
  584. //print_r('nextkhoid:'.$nextkh['openid']);
  585. sendmsg($nextkh['openid'],'text',$kefuname.':你好,久等了.','',$url);//新用户你好.
  586. $userjson=json_encode($paiduiarr);
  587. $res=file_put_contents("json/".$uniacid."_paidui.json",$userjson);//更新排队数据.
  588. $kefuarr[$openid]=$nextkh['openid'];//保存新的用户进来.;
  589. sendmsg($openid,'text','['.$nextkh['id'].']'.$nextkh['nickname'].'已经进入聊天.','',$url);//
  590. $res=file_put_contents("json/".$uniacid."_kefu.json",json_encode($kefuarr));//更新客服数据.
  591. $kefulist = json_decode(file_get_contents("json/".$uniacid."_kefulist.json"),true);
  592. $kefuname = $kefulist[$fromuserid];
  593. //sendmsg($nextkh['openid'],'text',$kefuname.':你好久等了.','',$url);//
  594. }else{//已无排队用户.修正客服表 保存.告诉客服.
  595. $kefuarr[$openid]='空闲';
  596. $res=file_put_contents("json/".$uniacid."_kefu.json",json_encode($kefuarr));//更新客服数据.
  597. sendmsg($openid,'text','已无排队用户.你的状态目前是空闲.\n常用命令: 上班 隐身 排队.','',$url);//新用户你好.
  598. }
  599. }
  600. return true;
  601. }else
  602. {
  603. return false;
  604. }
  605. }
  606. function paidui($uniacid,$openid,$website){
  607. $json = file_get_contents("json/".$uniacid."_paidui.json");
  608. $kefuarr = json_decode($json,true);
  609. if(array_key_exists($openid,$kefuarr)){
  610. return '排队中,请耐心等待.';//排队中...
  611. }else{
  612. $user=getuser($uniacid,$openid,$nickname,$website);//获取用户信息
  613. $userinfo=array('id'=>$user['id'],
  614. 'nickname'=>$user['nickname'],
  615. 'beizhu'=>$user['beizhu'],
  616. 'openid'=>$openid);
  617. $kefuarr[$openid]=$userinfo;
  618. $userjson=json_encode($kefuarr);
  619. $res=file_put_contents("json/".$uniacid."_paidui.json",$userjson);
  620. $qianmian=count($kefuarr)-1;
  621. return '已接入客服中心,前面有'.$qianmian.'人';//排队数量
  622. }
  623. }
  624. function getuser($ucid,$openid,$nickname,$website)
  625. {
  626. ///先判断缓存文件是否存在
  627. $json = file_get_contents("json/".$ucid."_user.json");
  628. $userinfos = json_decode($json,true);
  629. // $userid=$userinfos[$openid]['id'];
  630. // echo '找到缓存表:'.$userid;
  631. if (!array_key_exists($openid,$userinfos)){
  632. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getuser&m=qidong_app&openid=".$openid."&nickname=".$nickname;
  633. // echo $token_access_url;
  634. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  635. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  636. $nickname= $result['data']['wxapp'][0]['nickname'];
  637. $beizhu= $result['data']['wxapp'][0]['zhuangtai'];
  638. $lastliao= $result['data']['wxapp'][0]['lastliao'];
  639. if (trim($nickname)==null) {
  640. $nickname='会员'.$result['data']['wxapp'][0]['id'];
  641. $isid=1;
  642. }
  643. $userid=$result['data']['wxapp'][0]['id'];
  644. $data = array(
  645. 'nickname' => $nickname,
  646. 'id' => $userid,
  647. 'beizhu' => $beizhu,
  648. 'lastliao'=> $lastliao
  649. );
  650. return $data ;
  651. }else
  652. {
  653. // echo '找到缓存 直接返回;';
  654. return $userinfos[$openid];
  655. }
  656. //缓存 先去判断文件是否存在 .
  657. }
  658. //去查询 用户表 或者 客服表 找到详细信息.
  659. // 输出 : 身份[客服 或 用户 ] 状态 [ 咨询中 | 排队中 ]
  660. //规则 聊天中 不能使用1 2 3 不去查询 . 都发给管理员 .
  661. function changeurl($a){
  662. $bi= strpos($a,'[[');
  663. if ($bi==0){
  664. return $a;
  665. }else{
  666. $ei= strpos($a,']]');
  667. $qb=substr($a,0,$bi);
  668. $eb=substr($a,$ei+2);
  669. $b=substr($a,$bi+2,$ei-$bi-2);
  670. $ci=strpos($b,'|');
  671. $add=substr($b,0,$ci);
  672. $herf=substr($b,$ci+1,strlen($b)-$ci);
  673. }
  674. return $qb."<a href='".$herf."'>".$add."</a>".$eb;
  675. }
  676. function getToken($appid,$appsecret,$jsonid){
  677. $file = file_get_contents("json/{$jsonid}_token.json",true);
  678. $result = json_decode($file,true);
  679. if (time() > $result['expires']){
  680. $data = array();
  681. $data['access_token'] = getNewToken($appid,$appsecret);
  682. $data['expires']=time()+7200;
  683. $jsonStr = json_encode($data);
  684. $fp = fopen("json/{$jsonid}_token.json", "w");
  685. fwrite($fp, $jsonStr);
  686. fclose($fp);
  687. return $data['access_token'];
  688. }else{
  689. return $result['access_token'];
  690. }
  691. }
  692. function getNewToken($appid,$appsecret){
  693. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
  694. $access_token_Arr = https_request($url);
  695. return $access_token_Arr['access_token'];
  696. }
  697. function https_request ($url){
  698. $ch = curl_init();
  699. curl_setopt($ch, CURLOPT_URL, $url);
  700. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  701. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  702. $out = curl_exec($ch);
  703. curl_close($ch);
  704. return json_decode($out,true);
  705. }
  706. function logger($log_content)
  707. {
  708. if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
  709. sae_set_display_errors(false);
  710. sae_debug($log_content);
  711. sae_set_display_errors(true);
  712. }else{ //LOCAL
  713. $max_size = 500000;
  714. $log_filename = "log1.xml";
  715. if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
  716. file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
  717. }
  718. }
  719. function getwxinfo($token,$openid){
  720. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
  721. // logger($url);
  722. $access_token_Arr = https_request($url);
  723. return $access_token_Arr;
  724. }
  725. function hiuser($ucid,$id,$website){
  726. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getopenid&m=qidong_app&id=".$id;
  727. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  728. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  729. $data=$result['data'][0] ;
  730. return $data ;
  731. }
  732. function alluser($ucid,$website){
  733. $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=Getallopenid&m=qidong_app";
  734. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  735. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  736. $data=$result['data'] ;
  737. return json_encode($data) ;
  738. }
  739. function edituser($ucid,$openid,$nickname,$website,$avartar,$zhuangtai,$lastliao) //改名取号
  740. {
  741. $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
  742. // echo $token_access_url;
  743. // exit;
  744. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  745. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  746. $data=$result['data'];
  747. if ($data==1){$data='改名成功!';}
  748. else{$data='改名失败!';}
  749. return $data ;
  750. }
  751. function jieshuyu($bye,$uniacid,$openid,$website,$url){
  752. if(is_numeric($bye)){
  753. $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表
  754. $keys = json_decode($json,true);
  755. $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表
  756. $numkeys = json_decode($json,true);
  757. $delid=getuser($uniacid,$openid,'',$website);
  758. $send=$keys[$numkeys[$bye]];
  759. if ($send['link']['title']!=''){
  760. $send['link']['title']=str_replace('id',$delid['id'],$send['link']['title']);
  761. $send['link']['title']=str_replace('[name]', trim($delid['nickname']),$send['link']['title']);
  762. }
  763. if ($send['miniprogrampage']['title']!=''){
  764. $send['miniprogrampage']['title']=str_replace('id',$delid['id'],$send['miniprogrampage']['title']);
  765. $send['miniprogrampage']['title']=str_replace('[name]', trim($delid['nickname']),$send['miniprogrampage']['title']);
  766. }
  767. if ($send['text']['content']!=''){
  768. $send['text']['content']=str_replace('[id]',$delid['id'],$send['text']['content']);
  769. $send['text']['content']=str_replace('[name]',trim($delid['nickname']),$send['text']['content']);
  770. // logger('要替换的文本:'.$send['text']['content']);
  771. $send['text']['content']=changeurl($send['text']['content']);
  772. }
  773. $send['touser']=trim($openid);
  774. $data0=json_encode($send,JSON_UNESCAPED_UNICODE);
  775. }
  776. else {
  777. $sends=$bye; //$keys['关于我们'];
  778. $jieshuyu= str_replace('[name]',$delid['nickname'],$sends);
  779. $jieshuyu=str_replace("{br}","\n",$jieshuyu);
  780. $jieshuyu=changeurl($jieshuyu);
  781. $data0='{ "touser":"'.trim($openid).'", "msgtype":"text",
  782. "text": { "content":" '.$jieshuyu.' " } }';
  783. }
  784. $aaa = http_post_data($url, $data0);
  785. logger($data0);
  786. }
  787. function Finduser($ucid,$tablename,$culname,$openid,$findname,$website){
  788. //&tablename=dc_user&culname=openid&findname=name&openid=ogMce0dAqzqm3LSCIBzoHb4XYgFU
  789. $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}";
  790. // logger( $token_access_url);
  791. $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
  792. logger('--------------'.$res);
  793. $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP
  794. $data=$result['data']['nickname'] ;
  795. return $data ;
  796. }
  797. ?>