valid(); }else{ $wechatObj->responseMsg(); } class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取数据 //logger(time()); if (!empty($postStr)){ //$postObj =json_decode($postStr); $gzh=true; $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = trim($postObj->FromUserName); //openid $toUsername = $postObj->ToUserName; $tousernamebak=trim($toUsername); $keyword = trim($postObj->Content); $sessionFrom=$postObj->SessionFrom; //logger('sessionFrom:'.$sessionFrom); // $sessionFrom.="|"; //$userinfo=explode("|",$sessionFrom,-1); $MsgType = $postObj->MsgType;//消息类型 text event //$SessionFrom = $postObj->SessionFrom;//消息类型 text event $time = time(); logger($postStr); //读取设置json 系统设置 $json = file_get_contents('json/'.$toUsername.'.json'); $arr = json_decode($json,true); $uniacid=$arr['uniacid']; $website=$arr['website']; $json = file_get_contents('json/'.$uniacid.'_keywords.json');//读取key列表 $keys = json_decode($json,true); $json = file_get_contents('json/'.$uniacid.'_keys.json');//读取数字key列表 $numkeys = json_decode($json,true); define("APPID", $arr['APPID']); define("APPSECRET", $arr['APPSECRET']); $myopenid=trim($arr['openids']);//管理员id // if(isset($arr['uniacid'])){$uniacid=0; }else{}; //获取access_token 先获取token备份.查询 token是否存在 // $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET; // logger( $token_access_url); // $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 // $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 // $Atoken = $result['access_token']; // $Atoken=getToken(APPID,APPSECRET,$toUsername);//修正token时间问题 //下发信息 $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Atoken; $urlbak=$url; if ($MsgType == "image") {//接收图片 $PicUrl = $postObj->PicUrl; $MediaId = $postObj->MediaId; $MsgId = $postObj->MsgId; if ($fromUsername!= $myopenid){ //当是自己用户发来消息时. $data1=' { "touser":"'.$myopenid.'", "msgtype":"image", "image": { "media_id":"'.$MediaId.'" }}'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 } else{//管理员下发消息. $nowid=dujson('json/'.$toUsername.'_now.json'); $nowid=json_decode($nowid, true); //判断是给谁的图片 .获取到token 并 if (trim($nowid['tousername'])==$toUsername) { $data1=' { "touser":"'.$nowid['openid'].'", "msgtype":"image", "image": { "media_id":"'.$MediaId.'" }}'; $bbb = http_post_data($url, $data1); }else{ $file = file_get_contents("json/{$nowid['tousername']}_token.json",true); $result = json_decode($file,true); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $add="temp/".time().".png";//保存图片时的id $img = GrabImage($PicUrl,$add); logger('////--'.$img); // $type = 'image'; if ($img<>''){//当是图片时 转换成微信图片 $udata= json_decode(uploadFile($add,'image',$result['access_token']),true) ; $MediaId = $udata['media_id']; logger('Mid:'.$MediaId); } //发来图片 没转换成功时 if ($MediaId==''){ $data1='{ "touser":"'.trim($nowid['openid']).'", "msgtype":"text", "text": { "content":"[客服发来图片]\n 点击查看 " } }'; $bbb = http_post_data($url, $data1); }else{ $data1=' { "touser":"'.$nowid['openid'].'", "msgtype":"image", "image": { "media_id":"'.$MediaId.'" }}'; $bbb = http_post_data($url, $data1); } logger($data1.$bbb); } } exit; } if ($MsgType == "link") {//接收图文链接 $PicUrl = $postObj->PicUrl; $MsgId = $postObj->MsgId; $Title = $postObj->Title; $Description = $postObj->Description; $Url = $postObj->Url; $baogao=' { "title": "'.$Title.'", "description": "'.$Description.'", "url": "'.$Url.'", "thumb_url": "" }'; logger($baogao); if ($fromUsername!= $myopenid){ //当是自己用户发来消息时. $data1='{ "touser":"'.$myopenid.'", "msgtype":"link", "link": '.$baogao.' }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 } else{//管理员下发消息. $nowid=dujson('json/'.$toUsername.'_now.json'); $nowid=json_decode($nowid, true); //判断是给谁的图片 .获取到token 并 if (trim($nowid['tousername'])==$toUsername) { $data1='{ "touser":"'.$nowid['openid'].'", "msgtype":"link", "link": '.$baogao.' }'; $bbb = http_post_data($url, $data1); }else{ $file = file_get_contents("json/{$nowid['tousername']}_token.json",true); $result = json_decode($file,true); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $data1='{ "touser":"'.$nowid['openid'].'", "msgtype":"link", "link": '.$baogao.' }'; $bbb = http_post_data($url, $data1); logger($data1.$bbb); } } exit; } if ($MsgType == "video") {//接收图片 $PicUrl = $postObj->PicUrl; $MediaId = $postObj->MediaId; $thumb_media_id = $postObj->ThumbMediaId; if ($fromUsername!= $myopenid){ // $data1=' { "touser":"'.$myopenid.'", "msgtype":"video", "video": { "media_id":"'.$MediaId.'", "thumb_media_id":"VJFReD3DymOpc5slq3FvgQwzNtXQ9hONlafGaxg4P_F5x-1qvj1bgArhYQnrLrRV", "title":"未命名'.$title.'", "description":"视频说明:'.$MediaId.'" }}'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 logger($data1); logger($aaa); } else{ $nowid=dujson('json/'.$toUsername.'_now.json'); $nowopenid=json_decode($nowid, true); $content=''.$paidui['nickname'].':\n'; // $fromUsername= $myopenid; $data1=' { "touser":"'.$nowopenid['openid'] .'", "msgtype":"video", "video": { "media_id":"'.$MediaId.'", "thumb_media_id":"'.$MediaId.'", "title":"未命名'.$title.', "description":"视频说明:'.$MediaId.'" }}'; $bbb = http_post_data($url, $data1); $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[图片ID]\n '.$MediaId.'\n 图片链接:'.$PicUrl.' " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 } exit; } if ($MsgType == "voice") {//接收声音 $PicUrl = $postObj->PicUrl; $MediaId = $postObj->MediaId; $MsgId = $postObj->MsgId; $Recognition = $postObj->Recognition; if ($fromUsername!= $myopenid){ //接收用户发来的语音 $data1=' { "touser":"'.$myopenid.'", "msgtype":"voice", "voice": { "media_id":"'.$MediaId.'" }}'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 if($Recognition<>''){ $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[语音文本]\n '.$Recognition.' " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 } } else{ $nowid=dujson('json/'.$toUsername.'_now.json'); $nowid=json_decode($nowid, true); if (trim($nowid['tousername'])==$toUsername) { //$nowopenid=json_decode($nowid, true)['openid']; $data1=' { "touser":"'.$nowid['openid'] .'", "msgtype":"voice", "voice": { "media_id":"'.$MediaId.'" }}'; $bbb = http_post_data($url, $data1); }else{ $file = file_get_contents("json/{$nowid['tousername']}_token.json",true); $result = json_decode($file,true); $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $nowopenid=$nowid['openid']; $data1='{ "touser":"'.trim($nowopenid).'", "msgtype":"text", "text": { "content":"[语音文本]\n '.$Recognition.' " } }'; $bbb = http_post_data($url1, $data1); if (json_decode($bbb, true)['errcode']==0){ $sd='已送达';}else{$sd='未送达';} $data1='{ "touser":"'.trim($fromUsername).'", "msgtype":"text", "text": { "content":"['.$sd.']\n '.$Recognition.' " } }'; $bbb = http_post_data($url, $data1); } //////////////////////// } exit; } if ($MsgType == "file") {//接收文件 暂时不能支持 . $FromUserName = $postObj->FromUserName; $Title = $postObj->Title; $FileMd5 = $postObj->FileMd5; if ($fromUsername!= $myopenid){ // $data1=' { "touser":"'.$fromUsername.'", "msgtype":"file", // "file": { "title": "'.$Title.'", "FileMd5":"'.$FileMd5.'" }}'; $data1='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":"[系统提示]\n由于微信系统限制,我们还不能接收您发来的文件,可以加我们的客服QQ进行传递.回复QQ立即接通QQ链接. " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 logger($aaa); } else{ $nowid=dujson('json/'.$toUsername.'_now.json'); $nowopenid=json_decode($nowid, true); $content=''.$paidui['nickname'].':\n'; // $fromUsername= $myopenid; $data1=' { "touser":"'.$nowopenid['openid'].'", "msgtype":"image", "image": { "media_id":"'.$MediaId.'" }}'; $bbb = http_post_data($url, $data1); $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[图片ID]\n '.$MediaId.'\n 图片链接:'.$PicUrl.' " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 } exit; } if ($MsgType == "miniprogrampage") {//接收转发小程序... $FromUserName = $postObj->FromUserName; $Title = $postObj->Title; $AppId = $postObj->AppId; $PagePath = $postObj->PagePath; $ThumbMediaId = $postObj->ThumbMediaId; if ($fromUsername!= $myopenid){ //发送给管理员 $data1=' { "touser":"'.$myopenid.'", "msgtype":"miniprogrampage", "miniprogrampage": { "title": "'.$Title.'", "pagepath": "'.$pagepath.'", "thumb_media_id": "'.$ThumbMediaId.'" }}'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 // logger($aaa); } else{ $nowid=dujson('json/'.$toUsername.'_now.json'); $nowopenid=json_decode($nowid, true); // $fromUsername= $myopenid; // $data1=' { "touser":"'.$nowopenid['openid'].'", "msgtype":"image", // "image": { "media_id":"'.$MediaId.'" }}'; $data1=' { "touser":"'.$nowopenid['openid'].'", "msgtype":"miniprogrampage", "miniprogrampage": { "title": "'.$Title.'", "pagepath": "'.$pagepath.'", "thumb_media_id": "'.$ThumbMediaId.'" }}'; $bbb = http_post_data($url, $data1); } exit; } $Event = $postObj->Event; if ($Event == "CLICK") { $EventKey = $postObj->EventKey; $MsgType='text'; $keyword=trim($EventKey);//修复公众号问题. logger('event:'.$Event.$MsgType.'key:'.$keyword); } if ($Event == "VIEW") { exit; } if ($MsgType == "event") { $event = $postObj->Event; //如果传输了seession 就读取然后存储 . /// if (length($SessionFrom)>3) {$nickname=explode("|",$SessionFrom,-1)[0] ;} // $nickname=explode("|",$sessionFrom,-1)[0] ; // logger('nickname0:'.$nickname); //处理第一次进入的回复内容 用户信息查询. 先查询数据库: 并注册用户. if ($fromUsername== $myopenid){ //管理员上线通知 排队人数 留言条数 排队的人. $paiduinumber=count(file('json/'.$toUsername.'_now.json')); $liuyannumber=count(file('json/'.$toUsername.'_lishi.json')); $nowid=dujson('json/'.$toUsername.'_now.json'); $nowopenid=json_decode($nowid, true); $tongzhi='排队人数:'. $paiduinumber.'\n'.'留言条数:\n'. $liuyannumber.' \n当前聊天:\n'.$nowopenid['nickname']; $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[管理员上线工作提醒]\n '.$tongzhi.' " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 exit; } //下发图片. // $MediaId='EZMIeOmWpWieTSEPkUNQ-RfhAoGXBgjHrAXnVbfp9HRt6-Kz3Wx7_jdOSGWZW1uK'; // $data1=' { "touser":"'.$fromUsername.'", "msgtype":"image", // "image": { "media_id":"'.$MediaId.'" }}'; // $bbb = http_post_data($url, $data1); // exit; $user= getwxinfo($Atoken,$fromUsername); if($event=='unsubscribe'){ $eve='取消关注'; exit; }; $userinfo= getuser($uniacid,$fromUsername,$user['nickname'],$website); logger('nickname1:'.$uniacid.$fromUsername.$userinfo['nickname']); $send=$keys[$arr['默认']]; $data['title']= str_replace($userinfo['id'],'[id]',$data); if ($send['link']['title']!=''){ $send['link']['title']=str_replace('id',$userinfo['id'],$send['link']['title']); $send['link']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['link']['title']); } if ($send['miniprogrampage']['title']!=''){ $send['miniprogrampage']['title']=str_replace('id',$userinfo['id'],$send['miniprogrampage']['title']); $send['miniprogrampage']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['miniprogrampage']['title']); } if ($send['text']['content']!=''){ $send['text']['content']=str_replace('[id]',$userinfo['id'],$send['text']['content']); $send['text']['content']=str_replace('[name]',trim($userinfo['nickname']),$send['text']['content']); } $send['touser']=$fromUsername; $data=json_encode($send,JSON_UNESCAPED_UNICODE); //替换会员id和名字: // $data= str_replace($userinfo['id'],'[id]',$data); // echo str_replace("world","Shanghai","Hello world!"); // json_encode( $arr['关注'],JSON_UNESCAPED_UNICODE); $aaa = http_post_data($url, $data); //下发首次进入的回复内容. $zt=json_decode($aaa, true)['errcode']; logger("关注下发:".$data.'-状态:'. $zt); // $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", //"text": { "content":"[进入提醒测试]\n '.$zt.' " } }'; // $aaa = http_post_data($url, $data1); //减少骚扰 不通知 $caidan=trim($arr['Gjsonid']);//进入通知: if ($caidan<>''){ $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题 // logger("通知下发:".$caidan_arr['APPID'].'-状态:'.$caidan_arr['openids']); $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken; $data1='{ "touser":"'.$arr['Gopenids'].'", "msgtype":"text", "text": { "content":"[小程序进入提醒]\n '.$userinfo['nickname'].' " } }'; $aaa = http_post_data($url1, $data1); // //通知到公共号 logger($data1.$aaa); } $eve='用户点击了按钮'; if($event=='subscribe'){ $eve='新增关注'; }; if($event=='unsubscribe'){ $eve='取消关注'; }; $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"['.$eve.'通知]\n 编号: '.$userinfo['id'].' 昵称: '.$userinfo['nickname'].$eve.'" } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 exit; } if ($MsgType == "text") {// 如果不是第一次进入 // logger("keyword".$arr[$keyword]); //如果进入的是数字 判断是否有对应的文字 . if(is_numeric($keyword)){ $send=$keys[$numkeys[$keyword]]; } else { $send=$keys[$keyword]; //$keys['关于我们']; } if ( $send<>'' ) { //判断是否是知识库设置字段 // $user= getwxinfo($Atoken,$fromUsername); // logger('获取微信用户信息:'.$user); // $userinfo= getuser($uniacid,$fromUsername,$nickname); $userinfo=getwxinfo($Atoken,$fromUsername); if ($send['link']['title']!=''){ $send['link']['title']=str_replace('[id]',$userinfo['id'],$send['link']['title']); $send['link']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['link']['title']); } if ($send['miniprogrampage']['title']!=''){ $send['miniprogrampage']['title']=str_replace('[id]',$userinfo['id'],$send['miniprogrampage']['title']); $send['miniprogrampage']['title']=str_replace('[name]', trim($userinfo['nickname']),$send['miniprogrampage']['title']); } if ($send['text']['content']!=''){ $send['text']['content']=str_replace('[id]',$userinfo['id'],$send['text']['content']); $send['text']['content']=str_replace('[name]',trim($userinfo['nickname']),$send['text']['content']); $send['text']['content']=changeurl($send['text']['content']); } $send['touser']=$fromUsername; $data=json_encode($send,JSON_UNESCAPED_UNICODE); $aaa = http_post_data($url, $data); logger($data); getuser($uniacid,$fromUsername,$userinfo['nickname'],$website); //保存 $zt=json_decode($aaa, true)['errcode']; if ($zt!=0){//下发未成功 $data='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" 系统忙 错误代码: ' . $zt . ' " } }'; $aaa = http_post_data($url, $data); } logger("关注下发:".$data.'-状态:'. $zt); exit; }else {//文字推送 if ($keyword=='openid'){ //获取openid $data='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" 你的openid: ' . $fromUsername . ' " } }'; $aaa = http_post_data($url, $data); exit; } if (substr($keyword,0,6)=='取号'){ //手动设置昵称.. $quhao= edituser($uniacid,$fromUsername,trim(substr($keyword,6)),$website); $allnumber=count(file('json/'.$toUsername.'_now.json')); $data='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" '.substr($keyword,6).$quhao.' 前面有' .$allnumber . '人排队. " } }'; $aaa = http_post_data($url, $data); $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[取号通知]\n'.substr($keyword,6).'排队取号,目前共'.$allnumber+1 . ' 人. \n " } }'; $bbb = http_post_data($url, $data1); exit; } if ($arr["其他"]<>""){ //人工客服时 读一次数据库 . if ($fromUsername!= $myopenid){ //不是管理员时 //先判断用户是否在排队? $caidan=trim($arr['Gjsonid']);//进入通知: if ($arr["其他"]=='公众号客服'){ $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题 $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken; $myopenid=trim($arr['Gopenids']); $toUsername= $caidan; //写入新的公众号文件里面. } $paidui= ifpaidui('json/'.$toUsername.'_now.json',$fromUsername); logger($fromUsername.':'.$paidui['shunxu']); if ($paidui['shunxu']==0)//是新用户 查编号 写入队列. { $userinfowx=getwxinfo($Atoken,$fromUsername); $userinfo= getusernew($uniacid,$fromUsername,$userinfowx['nickname'],$website);//如果是第一个 直接读取缓存 $userinfo['tousername']=$tousernamebak; $userinfo['uniacid']=$uniacid; //判断是否是公共号绑定回复---- $new= savejson('json/'.$toUsername.'_now.json', json_encode($userinfo));//写入一个. 改. $allnumber=count(file('json/'.$toUsername.'_now.json')); if ($new==0){$new1=$allnumber;} else{$new1=$new;} //新用户 总排队 // $fromUsername= $myopenid; if($allnumber==1) {$hui='可直接回复'; $tishi='\n人工客服已经接入.'; //对方正在输入...哈哈 $data8='{ "touser":"'.$fromUsername.'", "command":"Typing"}'; $url8='https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token='.$Atoken; $bbb = http_post_data($url8, $data8); logger($bbb); //结束输入判断. } else{ $hui='可用命令 下一个 接通.或\n @'.$userinfo['id'].':私信Ta'; if ($arr["其他"]=='人工+机器人'){ $tishi='\n直接回复接入智能聊天机器人.';}; }; $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"[排队通知]目前共'.$allnumber . ' 人. \n'.$userinfowx['nickname'].' 备注:['.$userinfo['beizhu'].'] :'.$keyword.'\n '.$hui.'" } }'; $bbb = http_post_data($url, $data1); //第一次打招呼通知管理员. //读取Key 自动导航 $arr= array_keys($numkeys); $i=0; foreach ($arr as $arr) { $daohang.=$arr.':'.changeurl($numkeys[$arr]) .'\n'; $i++; if ($i>9){break;}; } //echo $caidan; $jqr=' 先看看这些能不能帮到您. 直接回复序号即可.\n'.$daohang; $data='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":"排队中,您是第'.$new1.' 个. '.$jqr.$tishi.' " } }'; //当没有约定好的回复时,这么回复。 $bbb = http_post_data($urlbak, $data); //第一次打招 exit; } elseif($paidui['shunxu']==1){ //是第一个 . $content='['.$paidui['id'].']'.$paidui['nickname'].'_'.$uniacid.':\n'; // $fromUsername= $myopenid; $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"'. $content. $keyword . ' " } }'; $bbb = http_post_data($url, $data1); if (json_decode($bbb, true)['errcode']==40001) { //发送失败 删掉token 再次获取. exec("rm -f ".'json/'.$toUsername.'_token.json'); // $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"重发:'. $content. $keyword . ' " } }'; $bbb = http_post_data($url, $data1); exit; } if (json_decode($bbb, true)['errcode']<>0){ $data2='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" 客服离开... 消息已存入信箱.'.json_decode($bbb, true)['errcode'].'" } }'; //当没有约定好的回复时,这么回复。 $bbbb = http_post_data($urlbak, $data2); savejson('json/'.$toUsername.'_lishi.json', '@'.$paidui['id'].'_'.$content.''.$keyword ); $caidan=trim($arr['Gjsonid']);//消息通知到公共号: if ($caidan<>''){ $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题 $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken; $data1='{ "touser":"'.$arr['Gopenids'].'", "msgtype":"text", "text": { "content":"[客服离线消息]错误代码:'.json_decode($bbb, true)['errcode'].'\n '. $content. $keyword .' " } }'; $aaa = http_post_data($url1, $data1); // //通知到公共号 logger($data1.$aaa); if (json_decode($aaa, true)['errcode']==40001) { //发送失败 删掉token 再次获取. exec("rm -f ".'json/'.$caidan.'_token.json'); $Btoken=getToken($arr['Gappid'],$arr['GAPPSECRET'],$caidan);//修正token时间问题 $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$Btoken; $data1='{ "touser":"'.$arr['Gopenids'].'", "msgtype":"text", "text": { "content":"[客服离线消息]错误代码:'.json_decode($bbb, true)['errcode'].'\n '. $content. $keyword .' " } }'; $aaa = http_post_data($url1, $data1); // //通知到公共号 } } } }else {//不是第一个 判断客服模式 if ($arr["其他"]=='人工+机器人') { $jqr='先和智能客服聊会. \n智能客服:'.jiqiren($keyword); } else { $jqr='轮到您时我们会信息通知.请耐心等待. \n '; } // $jqr='先和智能客服聊会. \n智能客服:'.jiqiren($keyword); $data='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":"排队中,您是第'.$paidui['shunxu'].' 个. '.$jqr.' " } }'; //当没有约定好的回复时,这么回复。 $aaa = http_post_data($urlbak, $data); // logger('下发:'.$data.$aaa); //通知到公共号 exit; } }else{//处理管理员发来的消息 //测试下发图片 if ($keyword=='生成缓存'){//调用生成缓存接口. // $huncun= json_decode(alluser($uniacid,$website),true); $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":" [缓存报告:]'.$huncun['openids'].' 数量:'.$huncun['count'].' "" } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 exit; } //处理群发所有人消息 if (substr($keyword,0,10)=='@所有人'){ //判断有没有缓存. $huncun= json_decode(alluser($uniacid,$website),true); //复制一份 "json/".$uniacid."_user.json" // exec("cp -f {$icon} ".$_base_path.'/WeMall/res/drawable-xhdpi-v4/ic_launcher.png'); $gjz=substr($keyword,10,strlen(trim($keyword))-10); if (substr ($keyword, -1)=='#'){ $gjz=str_replace('#','|',$gjz); } logger('是不是:'.$gjz) ; $baogao=' { "title": "代发列表已经准备好!点此群发", "description": "本次准备发送: '.$huncun['count'].' 请1分钟内点击,过期失效.", "url": "'.$website.'addons/qidong_app/qunfa.php?uniacid='.$uniacid.'&keyword='.$gjz.'&tousername='.$toUsername.'&t='.time().'", "thumb_url": "'.$website.'/addons/qidong_app/icon.jpg" }'; logger($baogao); $data1='{ "touser":"'.$myopenid.'", "msgtype":"link", "link": '.$baogao.' }'; $aaa = http_post_data($url, $data1); // exit; }///@所有人结束 //增加@某人的功能 if (substr($keyword,0,1)=='@'){ //取openid hiuser $stri=0; $stri= stripos($keyword,':'); if ($stri==0){$stri= stripos($keyword,' ') ;} if ($stri==0){$stri= stripos($keyword,':') ;} $nid=substr($keyword,1,$stri-1); //@12:=>12 $say=trim(substr($keyword,$stri+1));//发送的内容: //判断say最后字符是# 则是关键词消息 991# $liuuser= hiuser($uniacid,$nid,$website); $result = substr ($say, -1); if ($result=='#'){ $gjz=substr($say,0,strlen($say)-1); if(is_numeric($gjz)){ $send=$keys[$numkeys[$gjz]]; } else { $send=$keys[$gjz]; //$keys['关于我们']; } $send['touser']=$liuuser['openid']; $nickname=$liuuser['nickname']; if($nickname==''){$nickname='会员'.$liuuser['id'];} $send['link']['title']=str_replace('[id]',$liuuser['id'],$send['link']['title']); $send['link']['title']=str_replace('[name]', trim($nickname),$send['link']['title']); $data=json_encode($send,JSON_UNESCAPED_UNICODE); $bbb = http_post_data($url, $data); logger('单发:'.$data); }else{ $data2='{ "touser":"'.$liuuser['openid'].'", "msgtype":"text", "text": { "content":"[管理员@你]:\n'.$say.'" } }'; //当没有约定好的回复时,这么回复。 $bbb = http_post_data($url, $data2); } if (json_decode($bbb, true)['errcode']==0) { $zt='送达'; }else{ $zt='失败,可能已经离线'.json_decode($bbb, true)['errcode']; }; $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"会员'.$nid.'[消息'.$zt.']\n " } }'; $aaa = http_post_data($url, $data1); //减少骚扰 不通知 //发送消息 exit; }//@某人结束 switch ($keyword) { case '下一个': $delid=deljson('json/'.$toUsername.'_now.json');//删掉一个 // logger($delid); $jieshuyu= str_replace('[name]',$delid['nickname'],$arr['结束语']); $data0='{ "touser":"'.trim($delid['openid']).'", "msgtype":"text", "text": { "content":" '.$jieshuyu.' " } }'; //$delid=json_decode($delid, true); logger('1:'.$uniacid.'---'.$delid['uniacid']); if (trim($delid['uniacid'])==$uniacid) // If (substr(trim($delid['tousername']),0,1)=='') { //当是自己公众号的客户时: $a= edituser($uniacid,$delid['openid'],'',$website); logger('更新时间:'.$uniacid.$delid['openid'].$a); $aaa = http_post_data($url, $data0); logger('结束语1:'.$data0); }else{ $file = file_get_contents("json/{$delid['tousername']}_token.json",true); $a= edituser($delid['uniacid'],$delid['openid'],'',$website); logger('更新时间1:'.$uniacid.$delid['openid'].$a); $result = json_decode($file,true); $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $aaa = http_post_data($url1, $data0);//下发结束语 . logger('结束语2:'.$data0); } //////////////读取下一个////////////////////////////////////////////// $nowid=dujson('json/'.$toUsername.'_now.json'); $nowid=json_decode($nowid, true); $data2='{ "touser":"'.trim($nowid['openid']).'", "msgtype":"text", "text": { "content":"'.$nowid['nickname'].', 你好,久等了,有什么可以帮你的吗? " } }'; // 通知到管理员 If (substr(trim($nowid['openid']),0,1)=='o'){ //$userinfo= getuser($uniacid,$nowid,$nickname); $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"新用户'.$nowid['nickname'].'接入,准备接待.\n排队人数:'.count(file('json/'.$toUsername.'_now.json')).' " } }'; $bbb = http_post_data($url, $data1); // exit; }else{ $data1='{ "touser":"'.$myopenid.'", "msgtype":"text", "text": { "content":"已经接待完毕,没有用户排队了. " } }'; $bbb = http_post_data($url, $data1); // exit; } if (trim($nowid['tousername'])==null) { //当是自己公众号的客户时: $aaa = http_post_data($url, $data2); logger('欢迎语1 自己公共号:'.$data2); } else{ $file = file_get_contents("json/{$nowid['tousername']}_token.json",true); $result = json_decode($file,true); $url1 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $aaa = http_post_data($url1, $data2); logger('欢迎语1 其他小程序:'.$data2); } exit;//解决两次通知问题?2.28 // file_put_contents('json/'.$toUsername.'_all.json'.$delid.PHP_EOL, FILE_APPEND); break; case '排队'://排队列表 $paiduis=paiduilist('json/'.$toUsername.'_now.json'); $data1='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":"排队人数:'.count(file('json/'.$toUsername.'_now.json')).'\n 排队列表'.$paiduis.'\n 小提示 发送@ID:内容 可直接给会员私信. " } }'; break; case '看留言': $json = file_get_contents('json/'.$toUsername.'_lishi.json'); $data1='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":"本次获取的内容,已清空留言板:\n'.$json.' " } }'; exec("rm -f ".'json/'.$toUsername.'_lishi.json'); break; case '清零'://清除文件 继续.. exec("rm -f ".'json/'.$toUsername.'_now.json'); exec("rm -f ".'json/'.$toUsername.'_token.json'); exec("rm -f ".'log.xml'); if (!file_exists('json/'.$toUsername.'_now.json')){ $data1='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" 排队人数清零成功! " } }'; } else{ $data1='{ "touser":"'.$fromUsername.'", "msgtype":"text", "text": { "content":" 清零失败,请检查目录权限. " } }'; } break; case '公众号': ///推送公众号给用户 $nowid=dujson('json/'.$toUsername.'_now.json'); $data1=' { "touser": "'.$nowid.'", "msgtype": "link", "link": '.json_encode( $arr['关注'],JSON_UNESCAPED_UNICODE).'}'; //没成功.... break; default://管理员默认回复第一个 . $nowid=dujson('json/'.$toUsername.'_now.json'); $nowid=json_decode($nowid, true); //如果读到的jsonid 和 这里的不同 则是来自其他平台的 . //logger('读取到了一个文件:'.$nowid['tousername']); if (trim($nowid['tousername'])==null) { //$nowopenid=json_decode($nowid, true)['openid']; $data1='{ "touser":"'.trim($nowid['openid']).'", "msgtype":"text", "text": { "content":" '. $keyword . ' " } }'; }else{ $file = file_get_contents("json/{$nowid['tousername']}_token.json",true); $result = json_decode($file,true); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$result['access_token']; $nowopenid=$nowid['openid']; $data1='{ "touser":"'.trim($nowopenid).'", "msgtype":"text", "text": { "content":" '. $keyword . ' " } }'; } } $bbb = http_post_data($url, $data1); logger($data1.$bbb) ; } } } } $aaa = http_post_data($url, $data); //给管理员推送: logger($data.$aaa) ; }else{ echo ""; exit; } } } function http_post_data($url, $data_string) { set_time_limit ( 0 ); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。 curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $data = curl_exec($curl); curl_close($curl); return $data; } function traceHttp() { //logger("\n\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"].(strstr($_SERVER["REMOTE_ADDR"],'101.226')? " FROM WeiXin": "Unknown IP")); // logger("QUERY_STRING:".$_SERVER["QUERY_STRING"]); } function logger($log_content) { if(isset($_SERVER['HTTP_APPNAME'])){ //SAE sae_set_display_errors(false); sae_debug($log_content); sae_set_display_errors(true); }else{ //LOCAL $max_size = 500000; $log_filename = "log.xml"; if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);} file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND); } } //查询进入人的相关信息的 function getinfo($open_id,$title,$description,$url){ $link=mysql_connect("localhost","we7000","w7pass000"); if(!$link) echo "没有连接成功!"; mysql_select_db("we7", $link); //选择数据库 //查询userid ,昵称,图片 $q = "SELECT * FROM hjmall_user where (wechat_open_id ='".$open_id."' and store_id=20) "; //SQL查询语句 mysql_query("SET NAMES utf8"); $rs = mysql_query($q); //获取数据集 if(!$rs){die("Valid result!");} $row = mysql_fetch_array($rs); $result=' { "title": "hi!'.$row[10].','.$title.'", "description": "'.$description.'", "url": "'.$url.'", "thumb_url":"'. $row[11].'" }'; mysql_free_result($rs); //关闭数据集 return $result; } //查询进入人的相关信息的 function getinfo_s($open_id){ $link=mysql_connect("localhost","we70000","w7pass000"); if(!$link) echo "没有连接成功!"; mysql_select_db("we7", $link); //选择数据库 //查询userid ,昵称,图片 $q = "SELECT * FROM hjmall_user where (wechat_open_id ='".$open_id."' and store_id=20) "; //SQL查询语句 mysql_query("SET NAMES utf8"); $rs = mysql_query($q); //获取数据集 if(!$rs){die("Valid result!");} $row = mysql_fetch_array($rs); $result= $row[10] ; mysql_free_result($rs); //关闭数据集 return $result; } function alluser($ucid,$website){ $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=Getallopenid&m=qidong_app"; $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP $data=$result['data'] ; return json_encode($data) ; } function jiqiren($keyword) { $token_access_url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=".urlencode($keyword); // logger( $token_access_url); $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 $content = $result['content']; $content=str_replace("{br}","\n",$content); return $content; } function getwxinfo($token,$openid){ $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN"; // logger($url); $access_token_Arr = https_request($url); return $access_token_Arr; } function getToken($appid,$appsecret,$jsonid){ $file = file_get_contents("json/{$jsonid}_token.json",true); $result = json_decode($file,true); if (time() > $result['expires']){ $data = array(); $data['access_token'] = getNewToken($appid,$appsecret); $data['expires']=time()+7200; $jsonStr = json_encode($data); $fp = fopen("json/{$jsonid}_token.json", "w"); fwrite($fp, $jsonStr); fclose($fp); return $data['access_token']; }else{ return $result['access_token']; } } function getNewToken($appid,$appsecret){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}"; $access_token_Arr = https_request($url); return $access_token_Arr['access_token']; } function https_request ($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $out = curl_exec($ch); curl_close($ch); return json_decode($out,true); } function deljson($path){//读出第一行 删除 $f= fopen($path, "r"); $line = fgets($f); ob_start(); fpassthru($f); fclose($f); file_put_contents($path, ob_get_clean() ); $nowopenid=json_decode($line, true); return $nowopenid; } function dujson($path){//读出第一行 $f= fopen($path, "r"); $line = fgets($f); return trim($line); } function ifpaidui($path,$openid){//查看用户是否在队列 $lines = file($path); $i=0; $cf=0; foreach ($lines as $line) { $line = rtrim($line); $i++; $nowopenid=json_decode($line, true); if ($openid==$nowopenid['openid']){ $cf=$i; $findedata = array( 'shunxu' => $cf, 'nickname' => $nowopenid['nickname'], 'openid'=> $nowopenid['openid'], 'id' => $nowopenid['id'] ); break;//找到后中止. } // more statements... }//如果没找到. if ($cf==0) { $data = array( 'shunxu' => $cf, 'nickname' => '无', 'openid'=> '', 'avartar' => '' ); return $data; } else{ return $findedata; } } function paiduilist($path){//查看用户是否在队列 $lines = file($path); $i=0; $cf=0; foreach ($lines as $line) { $line = rtrim($line); $i++; $nowopenid=json_decode($line, true); $paidui=$paidui.'\n ID:'.$nowopenid['id'].' 昵称:'.$nowopenid['nickname']; // more statements... }//如果没找到. return $paidui; } function savejson($path,$data){ //保存1行 //去除重复 $lines = file($path); $i=0; $cf=0; foreach ($lines as $line) { $line = rtrim($line); $i++; // print("$line\n"); if ($data==$line){ $cf=$i; break; } // more statements... } if ($cf==0) { // echo "newone:\n"; file_put_contents($path, $data.PHP_EOL, FILE_APPEND); return $cf; } else{ return $cf; } } function edituser($ucid,$openid,$nickname,$website) //改名取号 { $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=edituser&m=qidong_app&openid=".$openid."&nickname=".$nickname; $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP $data=$result['data']; if ($data==1){$data='取号成功!';} else{$data='取号失败!';} return $data ; } function getusernew($ucid,$openid,$nickname,$website) { $file = file_get_contents("json/{$ucid}_token.json",true); $result = json_decode($file,true); if ($openid != $result['openid']){ $data = array(); $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getuser&m=qidong_app&openid=".$openid."&nickname=".$nickname; // logger( $token_access_url); $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP $nickname= $result['data']['wxapp'][0]['nickname']; if (trim($nickname==null)) { $nickname='会员'.$result['data']['wxapp'][0]['id']; $isid=1; } $data = array( 'nickname' => $nickname, 'id' => $result['data']['wxapp'][0]['id'], 'openid'=> $result['data']['wxapp'][0]['openid'], 'avartar' => $result['data']['wxapp'][0]['avartar'] ); $jsonStr = json_encode($data); $fp = fopen("json/{$ucid}_token.json", "w"); fwrite($fp, $jsonStr); fclose($fp); return $data; }else{ return $result; } } function hiuser($ucid,$id,$website){ $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getopenid&m=qidong_app&id=".$id; $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP $data=$result['data'][0] ; return $data ; } function getuser($ucid,$openid,$nickname,$website) { ///先判断缓存文件是否存在 if (file_exists("json/".$ucid."_user.json")){ $json = file_get_contents("json/".$ucid."_user.json"); $userinfos = json_decode($json,true); $userid=$userinfos[$openid]['id']; } if ($userid==null){ //获取微信昵称 ..?? $token_access_url = "{$website}/app/index.php?i=".$ucid."&c=entry&a=wxapp&do=getuser&m=qidong_app&openid=".$openid."&nickname=".$nickname; // logger( $token_access_url); $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容 $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP $nickname= $result['data']['wxapp'][0]['nickname']; if (trim($nickname)==null) { $nickname='会员'.$result['data']['wxapp'][0]['id']; $isid=1; } $userid=$result['data']['wxapp'][0]['id']; }else { if (trim($userinfos[$openid]['nickname'])==null) { $nickname='会员'.$userinfos[$openid]['id']; $isid=1; }else{ $nickname=$userinfos[$openid]['nickname']; $userid=''.$userinfos[$openid]['id']; } } //缓存 先去判断文件是否存在 . $data = array( 'nickname' => $nickname, 'id' => $userid, 'isid'=> $isid, 'avartar' => '' ); return $data ; } function changeurl($a){ $bi= strpos($a,'[['); if ($bi==0){ return $a; }else{ $ei= strpos($a,']]'); $qb=substr($a,0,$bi); $eb=substr($a,$ei+2); $b=substr($a,$bi+2,$ei-$bi-2); $ci=strpos($b,'|'); $add=substr($b,0,$ci); $herf=substr($b,$ci+1,strlen($b)-$ci); } return $qb."".$add."".$eb; } function GrabImage($url, $filename = "") { if ($url == ""):return false; endif; //如果$url地址为空,直接退出 if ($filename == "") { //如果没有指定新的文件名 $ext = strrchr($url, "."); //得到$url的图片格式 if ($ext != ".gif" && $ext != ".jpg"):return false; endif; //如果图片格式不为.gif或者.jpg,直接退出 $filename = date("dMYHis") . $ext; //用天月面时分秒来命名新的文件名 } ob_start();//打开输出 readfile($url);//输出图片文件 $img = ob_get_contents();//得到浏览器输出 ob_end_clean();//清除输出并关闭 $size = strlen($img);//得到图片大小 $fp2 = @fopen($filename, "a"); fwrite($fp2, $img);//向当前目录写入图片文件,并重新命名 fclose($fp2); return $filename;//返回新的文件名 } function uploadFile($file, $type = 'image', $acctoken = '') { // $post_data ['type'] = $type; // 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) $post_data ['media'] = '@'.$file; //$post_data ['media'] =$file; $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={$acctoken}&type=image"; $output=http_post_media($url, $post_data); return $output; } function http_post_media($url,$strPOST) { $oCurl = curl_init (); curl_setopt ( $oCurl, CURLOPT_SAFE_UPLOAD, false); if (stripos ( $url, "https://" ) !== FALSE) { curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false ); } curl_setopt ( $oCurl, CURLOPT_URL, $url ); curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $oCurl, CURLOPT_POST, true ); curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST ); $sContent = curl_exec ( $oCurl ); $aStatus = curl_getinfo ( $oCurl ); curl_close ( $oCurl ); if (intval ( $aStatus ["http_code"] ) == 200) { return $sContent; } else { return false; } } ?>