您的位置:首页 > 编程语言 > PHP开发

php+ajax实现web客服系统

2017-09-28 16:14 239 查看
在后台接入界面将访问者信息通过POST方式传递到接口文件

var custom = function(){
    ajax_get_data(site_url_user+'?act=custom','',do_custom,'POST','数据加载中!');
}
var do_custom = function(mydata){
    switch(mydata.code){
        case 200:
            var userdata = mydata.userdata;
            var form = $("<form method='post' id='myform'></form>" ),
            input;
            form.attr('action',mydata.url);
            $.each(userdata,function(key,value){
                input = $("<input type='hidden'>");
                input.attr('name',key);
                input.val(value);
                form.append(input);
            });
            form.appendTo($('#custom'));
            form.submit();
            break;
        default :
            location.href = site_url+'login.html';
            break;
    }
}

访问接口文件 custom_service.api.php

<?php
/**
* Info 客服功能接口
* Created by PhpStorm.
* User: d
* Date: 2017/5/16
* Time: 14:46
*/
include_once("config.inc.php");

//接收提交参数
$mydata['act'] = get_param('act','int');//游戏/代理
$mydata['pb_nickname'] = get_param('nickname');//名称
$mydata['pb_wjuid'] = get_param('wjuid');//玩家/代理ID
$mydata['pb_wjopenid'] = get_param('wjopenid');
$mydata['pb_wjunionid'] = get_param('wjunionid');
if($mydata['act']==2){
    $mydata['pb_areaid'] = get_param('areaid','int');//地区ID
    $value = array('sysid'=>$mydata['pb_wjuid'],'p_nickname'=>$mydata['pb_nickname'],'p_serarea'=>$mydata['pb_areaid'],'p_wxopenid'=>$mydata['pb_wjopenid'],'p_unionid'=>$mydata['pb_wjunionid']);
    $prinfo = exist_check($GLOBALS['conn'],'game_proxy',$value);
    if(!$prinfo){
        $smarty->assign('code',300);//错误码
        $smarty->assign('mess','代理信息有误');//错误信息
        $smarty->display('custom_service.html');
        exit;
    }
}else{
    $mydata['pb_gameid'] = get_param('gameid','int');//游戏id
    $mydata['pb_areaid'] = get_area_id($mydata['pb_gameid']);//地区ID
    $value = array('uid'=>$mydata['pb_wjuid'],'user_nickname'=>$mydata['pb_nickname'],'area_id'=>$mydata['pb_gameid'],'user_openid'=>$mydata['pb_wjopenid'],'user_unionid'=>$mydata['pb_wjunionid']);
    $wjinfo = exist_check($GLOBALS['conn'],'game_member',$value);
    if(!$wjinfo){
        $smarty->assign('code',300);//错误码
        $smarty->assign('mess','玩家信息有误');//错误信息
        $smarty->display('custom_service.html');
        exit;
    }
}

$mydata['time'] = get_param('time','int');
$mydata['md5'] = trim(get_param('md5'));

$ip    = return_user_ip();//访问者IP

//重新组合要验证的字符串
$tmp_md5=strtolower(md5($mydata['time'].$mydata['act'].$mydata['pb_wjuid']));

//验证数据
if($mydata['act']<1){
    $smarty->assign('code',300);//错误码
    $smarty->assign('mess','所属平台不能为空');//错误信息
    $smarty->display('custom_service.html');
    exit;
}
if(empty($mydata['md5'])){
    $smarty->assign('code',300);//错误码
    $smarty->assign('mess','验证数据不能为空');//错误信息
    $smarty->display('custom_service.html');
    exit;
}
if($tmp_md5!=$mydata['md5']){
    $smarty->assign('code',300);//错误码
    $smarty->assign('mess','验证数据不通过');//错误信息
    $smarty->display('custom_service.html');
    exit;
}

//查看当前访问玩家是否新增记录
$where = " and pb_wjuid=".$mydata['pb_wjuid']." and pb_status=1 ";//未处理
$result =  get_info($GLOBALS['conn'],'game_player_bug',array(),$where);
if($result){
    //接入之前的客服记录
    $smarty->assign('serviceid',$result['sysid']);//将接入ID传入聊天页面
    $smarty->assign('flag',1);//2客服1玩家
    $smarty->display('custom_service.html');
}else{
    //新增一条接入记录
    $pd_data = array(
        'pb_title' => $mydata['pb_wjuid'].'_'.date('Y-m-d'),
        'pb_is_game' => $mydata['act'],
        'pb_gameid' => $mydata['pb_gameid'],
        'pb_areaid' => $mydata['pb_areaid'],
        'pb_nickname' => $mydata['pb_nickname'],
        'pb_wjuid' => $mydata['pb_wjuid'],
        'pb_wjopenid' => $mydata['pb_wjopenid'],
        'pb_wjunionid' => $mydata['pb_wjunionid'],
        'pb_ip' => $ip,
    );
    $res = add_record($GLOBALS['conn'],'game_player_bug',$pd_data);
    if($res){
        $smarty->assign('serviceid',$res['id']);//将接入ID传入聊天页面
        $smarty->assign('flag',1);//2客服1玩家
        $smarty->display('custom_service.html');
    }else{
        $smarty->assign('code',300);//错误码
        $smarty->assign('mess','操作失败,请重试!');//错误信息
        $smarty->display('custom_service.html');
        exit;
    }
}

客服显示页面 custom_service.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
    <meta name="format-detection" content="telephone=no" />
    <meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Cache" content="no-cache">
    <!-- 这行代码是永远以最新的IE版本模式来显示网页,使IE支持HTML5。 -->
    <meta http-equiv="X-UA-Compatible"  content="IE=edge,chrome=1">
    <!-- 这行代码是360浏览器渲染页面需默认用极速内核 -->
    <meta name="renderer" content="webkit">
    <meta name="keywords" content="个人主页">
    <meta name="description" content="个人主页" />
    <title>个人主页</title>

    <link rel="stylesheet" type="text/css" href="./templates/media/css/base.css" />
    <link rel="stylesheet" type="text/css" href="./templates/media/css/index.css" />
    <style type="text/css">
        .form1{ background-color: #e3e1e2;}
    </style>
</head>
<body class="body-color">
<div class="main">
    <div class="content" id="content">
    </div>
</div>
<div class="main-bottom">
    <div class="send clearfix">
        <a onclick="return GzcawlIndex.change_icon();"><img id="pic" src="./templates/media/image/close.png" width="44" height="44"
alt="" data_key="close"/></a>
        <textarea name="" class="send-textarea" id="msg"></textarea>
        <button class="send-btn" onclick="return GzcawlIndex.sendmsg();">发送</button>
        <input type="hidden" id="sname"  value="<!--{$sername}-->" />
        <input type="hidden" id="flag"  value="<!--{$flag}-->" />
        <input type="hidden" id="sid" value="<!--{$serviceid}-->">
        <input type="hidden" id="code" value="<!--{$code}-->">
        <input type="hidden" id="mess" value="<!--{$mess}-->">
    </div>

    <div class="send-images">
        <iframe src="serfile.php?mytype=attach&gif|jpg|png" width="331px" height="47px" align="absmiddle" scrolling="no" frameborder="0"
class="form1"></iframe>
            <p>相册</p>
        <input type="hidden" name="attach" id="attach" value="" />
        <div id="attach_1"></div>
    </div>
</div>
<!--{include file="comm/javascript_tmp.html"}-->
<script>
    var GzcawlIndex = function(){
        var sendmsg = function(){
            var msg = $('#msg' ).val();
            var id = $('#sid' ).val();
            var flag = $('#flag' ).val();
            var attach = $('#attach' ).val();//图片
            if(msg=='' && attach==''){
                layer.msg('请输入发送内容或上传附件');
                return false;
            }

            ajax_get_data('custom_service.php?action=send&msg='+msg+'&id='+id+'&flag='+flag+'&attach='+attach,'',do_sendmsg,'POST','数据提交中');
        };
        var do_sendmsg = function(mydata){
            var data_code = mydata.code;
            switch(data_code) {
                case 200:
                    $('#msg' ).val('');
                    $('#attach' ).val('');
                    $('#attach_1' ).html('');
                    getwjmsg();//显示发送消息
                    break;
                default :
                    layer.msg( mydata.msg , { icon : 2 , time : 3000 } );
                    break;
            }
        };
        var change_icon = function(){
            var pic_obj =  $('#pic' );
            var key = pic_obj.attr('data_key');
            if(key=='close'){
                $('.send-images' ).css('display','none');
                pic_obj.attr('src','./templates/media/image/open.png');
                pic_obj.attr('data_key','open');
            }
            if(key=='open'){
                $('.send-images' ).css('display','block');
                pic_obj.attr('src','./templates/media/image/close.png');
                pic_obj.attr('data_key','close');
            }
            return false;
        }
        return {
            sendmsg:function(){
                sendmsg();
            },
            change_icon:function(){
                change_icon();
            }
        };
    }();

    var max_id = 0;
    function getwjmsg(){
        var id = $('#sid' ).val();//接入ID
        var flag = $('#flag' ).val();
        $.post('custom_service.php?action=getwjmsg&id='+id+'&flag='+flag+'&max_id='+max_id,function(data){
            var re = '';
            if(data.length>0) {
                for ( var i = 0 ; i < data.length ; i++ ) {
                    re += (data[i ].showtime!=0 ? '<div class="main-time"><p>'+data[ i ].time+'</p></div>' : '')+'<div class="content-'
+ (data[ i ].flag == data[ i ].pe_whoid ? 'right' : 'left') + '"><em></em><p>' + (data[ i ].pe_whoid != data[ i ].flag ? (data[ i ].pe_whoid==1 ? data[ i ].wname+': ' : '客服'+data[ i ].pe_kfname+': ') : '')  + data[ i ].pe_reply + (data[i ].pe_attachment!=''
? ('<a href="'+data[i ].pe_attachment+'" target="_blank"><img src="'+data[i ].pe_attachment+'" width="200px"></a>') : '')+'</p></div>';
                    max_id = data[ i ].sysid;
                }
            }
            $( '#content' ).append( re );
        },"json");
    }

    //页面加载完毕获取消息
    window.onload=function(){
        var code = $('#code' ).val();
        if(code==300){
            layer.msg($('#mess' ).val(),{ icon: 2, time: 3000  },function(){history.back();});
            return false;
        }
        setInterval("getwjmsg()",5000);
        GzcawlIndex.change_icon();
    }

</script>
</body>
</html>

上传iframe文件 serfile.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>文件上传</title>
    <link rel="stylesheet" type="text/css" href="./templates/media/css/base.css" />
    <link rel="stylesheet" type="text/css" href="./templates/media/css/index.css" />
    <style type="text/css">
        .send-file-btn img{  z-index: 5555;}
        .send-file-btn input{ position:absolute;left:0;top:0; width:46px; height:46px;cursor: pointer;opacity:0;}
    </style>
    <script src="./templates/media/js/jquery-1.12.3.min.js" type="text/javascript"></script>
<script language="javascript">
function IsExt(url,opt){
    var sTemp;
    var b=false;
    var s=opt.toLowerCase().split("|");
    for (var i=0;i<s.length ;i++ ){
        sTemp=url.substr(url.length-s[i].length-1);
       sTemp=sTemp.toLowerCase();
       s[i]="."+s[i];
       if (s[i]==sTemp){
           b=true;
           break;
       }
    }
    return b;
}

function images_onchanges(){
var tmpmyext = location.href;
//var  myext = tmpmyext.toLowerCase().split("?");
var myext = tmpmyext.toLowerCase().split("&");
    if(typeof(myext[1]) !="undefined"){
        if(IsExt(document.getElementById("uploadfilename").value,myext[1])){
           return true;
       }else{
           alert('请把文件转成' + myext[1] + '格式');
           return false;
       }
    }else{
       alert("请指定要上传的文件类型!");
       return false;
    }
}

    function upimage(){
        $('#uploadfilename' ).click();
        return false;
    }
</script>
</head>
<body>
<form action="serup.php" id="form1" name="form1" onsubmit="return images_onchanges()"   enctype="multipart/form-data" method="post"
>
    <div class="send-file-btn">
        <img src="./templates/media/image/send-images.png" height="48" width="48" alt="" onclick="return upimage()"/>
        <input name="uploadfilename" id="uploadfilename" onchange="return images_onchanges()"  type="file" />
    </div>
  <input name="upload_hidden" type="hidden" id="upload_hidden" value="1" />
    <button class="upload" type="submit" name="Submit" id="Submit">上传</button>
  <input name="myuplodtype" type="hidden" id="myuplodtype" value="<?PHP echo($_GET["mytype"]); ?>" />
</form>
</body>
</html>

上传处理文件 serup.php

<?PHP
set_time_limit(0);
include_once("config.inc.php");

if($_POST["upload_hidden"] == "1"){
    $file = $_FILES["uploadfilename"];
    $p_myuplodtype = trim($_POST["myuplodtype"]);//保存文件名的文本框名
    $filetype = $UPTYPE["myfiletype"];
    $myfile = new zdeFile();

    $oldpath = $file['tmp_name'];

    $filename=strtolower(basename($file['name']));//取上传文件的小写文件名
    $fileext=explode('.', $filename);//取后缀名
    $arraynum = count($fileext) - 1;

    $file_size = ceil(filesize($oldpath)/1024);//文件大小(K)
    if($file_size>2500){
       echo "<script>alert('上传文件超过1500K');history.go(-1);</script>";
       exit();
    }

    if(!in_array($fileext[$arraynum], $filetype)){//检查文件类型
        die("<script>alert('upload error!file type Error!');history.back();</script>");
    }
    $timepath = date('Y',time())."/".date('m',time())."/".date('d',time())."/";
    if($fileext[$arraynum] == 'swf'){
       $newpath = "./uploadfile/flash/";
    }elseif($fileext[$arraynum] == 'jpg' || $fileext[$arraynum] == 'gif' || $fileext[$arraynum] == 'png'){
       $newpath = "./uploadfile/images/".$timepath;
    }else{
       $newpath = "./uploadfile/file/".$timepath;
    }

    if($fileext[$arraynum]=='txt'){//如果为文本
        $newname = time().".php";//新文件名
    }else{
       $newname = time().".".$fileext[$arraynum];//新文件名
    }
    $newpath .=  $newname;//新文件名

    if($myfile->cp($oldpath,$newpath,true)){
       if($fileext[$arraynum] == 'txt'){
           $tmp_str = file($newpath);
           if($tmp_str){
               die("<script>parent.document.getElementById('".$p_myuplodtype."').value='".$newpath."';history.back(-1);</script>");
           }else{
               die("<script>alert('文件内容为空,请重新选择');history.back(-1);</script>");
           }
       }elseif( $fileext[$arraynum] == 'swf'){
           die("<script>parent.document.getElementById('".$p_myuplodtype."').value='".$newpath."';parent.document.getElementById('".$p_myuplodtype."_1').innerHTML='flash文件已成功上传!';history.back(-1);</script>");
       }else{
           die("<script>parent.document.getElementById('".$p_myuplodtype."').value='".$newpath."';parent.document.getElementById('".$p_myuplodtype."_1').innerHTML='<img
src=\"".$newpath."\" width=\"100px\"/>';history.back(-1);</script>");
       }
    }else{
       die("upload error!");
    }
}
?>

消息处理文件(ajax) custom_service.php

<?php
/**
* Created by PhpStorm.
* User: d
* Date: 2017/5/15
* Time: 15:13
*/
include_once("config.inc.php");
//include_once("check_login.php");
$realname = $_SESSION['realname'];  //真实姓名
$logname  = $_SESSION['admin'];      //管理员登录名
$admin_id = $_SESSION['admin_id'];  //管理员ID
$done_ip  = return_user_ip();       //管理员IP

$action = get_param("action");
$reply_sys = "您好,请问有什么可以帮您?";

switch($action){
    case 'getwjmsg'://接收消息
        $id = get_param('id');//接入ID
        $flag = get_param('flag');//接入身份
        $max_id = get_param('max_id');

        //查询玩家名称
        $where = " and sysid=$id";
        $wname = get_info($GLOBALS['conn'],'game_player_bug',array('pb_nickname'),$where)['pb_nickname'];

        //查询该用户的接收消息
        $condition = " pe_bugid=$id  and pe_isread=2 and sysid>$max_id ";
        $sql = "SELECT * FROM ".get_table("game_player_exchange")." WHERE $condition order by pe_replytime asc";
        $result  = $GLOBALS['conn']->Query($sql);
        while($row = $GLOBALS['conn']->FetchArray($result)){
            if($row['pe_whoid']!=$flag){
                //将查询记录改为已读
                $up_arr = array('pe_isread' => 1);
                $where = " and sysid=".$row['sysid'];
                update_record($GLOBALS['conn'],'game_player_exchange',$up_arr,array(),$where);
            }
            //查看上一条回复记录的时间
            $wherel = " and sysid=".($row['sysid']-1);
            $retime = get_info($GLOBALS['conn'],'game_player_exchange',array('pe_replytime'),$wherel)['pe_replytime'];
            $row['showtime'] =0;
            if(($row['pe_replytime']-$retime)>180){
                $row['showtime'] = 1;//超时显示时间
            }
            $row['time'] = date('H:i',$row['pe_replytime']);//时间
            $row['flag'] = $flag;
            $row['wname'] = $wname;
            $row['pe_attachment'] = $row['pe_attachment'] ?  : '';//图片
            $list[] = $row;
        }
        $string = return_ajax($list);
        echo $string;
        break;
    case 'send'://发送消息
        $msg = get_param('msg');//内容
        $id = get_param('id');//接入ID
        $flag = get_param('flag');//接入身份
        $attach = get_param('attach');//图片

        if($msg=='' && $attach==''){
            $return_arr = array(
                'code' => 300,
                'msg'  => '请输入发送内容或上传附件',
            );
            $string = return_ajax($return_arr);
            echo $string;exit;
        }

        //新增回复记录
        $where = " and sysid=".$id;
        $sinfo = get_info($GLOBALS['conn'],'game_player_bug',array(),$where);//查询出接入信息
        if($sinfo['pb_addtime']=='0' && $flag==1){//玩家第一次提问
            update_record($GLOBALS['conn'],'game_player_bug',array('pb_addtime'=>THIS_DATETIME),array(),$where);
        }
        if($sinfo['pb_isattach']==2 && $attach!=''){//没有附件
            update_record($GLOBALS['conn'],'game_player_bug',array('pb_isattach'=>1),array(),$where);
        }

        $redata  = array(
            'pe_bugid' => $id,
            'pe_is_game' => $sinfo['pb_is_game'],
            'pe_gameid' => $sinfo['pb_gameid'],
            'pe_areaid' => $sinfo['pb_areaid'],
            'pe_reply' => $msg,
            'pe_attachment' => $attach ? : '',
            'pe_replytime' => THIS_DATETIME,
            'pe_whoid' => $flag,
            'pe_kfid' => $sinfo['pb_receiveid'],
            'pe_kfname' => $sinfo['pb_receicename'],
            'pe_replyip' => $flag==1 ? $sinfo['pb_ip'] : $done_ip,
        );

        $res = add_record($GLOBALS['conn'],'game_player_exchange',$redata);
        if($res['rows']>0){
            //新增成功
            $return_arr = array(
                'code' => 200,
                'msg'  => '发送成功',
            );
        }else{
            $return_arr = array(
                'code' => 300,
                'msg'  => '发送失败,请重试',
            );
        }

        $string = return_ajax($return_arr);
        echo $string;

        break;
    default:
        //is_per('10098');
        $id = get_param('id','int');//接入ID
        if($id==0){
            showinfo('接入失败','',3);
        }

        //查询出当前接入记录
        $where = " and sysid=".$id;
        $info = get_info($GLOBALS["conn"],"game_player_bug",array(),$where);

         //新增一条即时通信数据
        if($info) {
            $a_nickname = get_nickname($admin_id);//客服昵称
            //更新接入记录
            $up_arr = array(
                'pb_receiveid' => $admin_id,
                'pb_receicename' => $a_nickname,
                'pb_receivetime' => THIS_DATETIME,
            );
            update_record($GLOBALS['conn'],'game_player_bug',$up_arr,array(),$where);
            //发送客服接入消息
            $pe_data = array(
                'pe_bugid' => $id,
                'pe_is_game' => $info['pb_is_game'],
                'pe_gameid' => $info['pb_gameid'],
                'pe_areaid' => $info['pb_areaid'],
                'pe_reply' => $reply_sys,
                'pe_replytime' => THIS_DATETIME,
                'pe_whoid' => 2,
                'pe_kfid' => $admin_id,
                'pe_kfname' => $a_nickname,
                'pe_replyip' => $done_ip
            );
            add_record($GLOBALS['conn'],'game_player_exchange',$pe_data);//新增一条即时信息
            $smarty->assign('serviceid', $id);//将接入ID传入聊天页面
            $smarty->assign('flag',2);//2客服1玩家
            $smarty->display('custom_service.html');
        }else{
            showinfo('操作失败','',3);
        }

        break;
}
if($GLOBALS["conn"]){ $GLOBALS["conn"]->Close(); }//关闭MYSQL链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax 客服