微信客服自动回复(thinkphp5)

define("TOKEN","123456");//自己设置的Token
class wechatAPI{

    const APP_ID = 'wx3**********'; //你自己的appid
    const APP_SECRET = '72c*****************';//你自己生成的appSecret
    //用于小程序第一步验证返回之后注释掉
    public function isValid(){
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function send($data){
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->getAccessToken();
        $data = urldecode(json_encode($data));
        $this->curl_post($url,$data);

    }

    //xml数据转数组
    public function xml2Array($contents = NULL, $encoding = 'UTF-8', $get_attributes = 1, $priority = 'tag'){
        if (!$contents)
        {
            return array();
        }
        if (!function_exists('xml_parser_create'))
        {
            return array ();
        }
        $parser = xml_parser_create('');
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $encoding);
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, trim($contents), $xml_values);
        xml_parser_free($parser);
        if (!$xml_values)
            return array();
        $xml_array = array ();
        $parents = array ();
        $opened_tags = array ();
        $arr = array ();
        $current = & $xml_array;
        $repeated_tag_index = array ();
        foreach ($xml_values as $data)
        {
            unset ($attributes, $value);
            extract($data);
            $result = array ();
            $attributes_data = array ();
            if (isset ($value))
            {
                if ($priority == 'tag')
                    $result = trim($value);
                else
                    $result['value'] = trim($value);
            }
            if (isset ($attributes) && $get_attributes) {
                foreach ($attributes as $attr => $val)
                {
                    if ($priority == 'tag')
                        $attributes_data[$attr] = $val;
                    else
                        $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            if ($type == "open")
            {
                $parent[$level -1] = & $current;
                if (!is_array($current) || (!in_array($tag, array_keys($current)))) {
                    $current[$tag] = $result;
                    if ($attributes_data)
                        $current[$tag . '_attr'] = $attributes_data;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if (isset($tag) && $tag && isset($current[$tag])) {
                        $current = & $current[$tag];
                    }
                }
                else
                {
                    if (isset ($current[$tag][0]))
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 2;
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = & $current[$tag][$last_item_index];
                }
            }
            elseif ($type == "complete")
            {
                if (!isset ($current[$tag]))
                {
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' && $attributes_data) {
                        $current[$tag . '_attr'] = $attributes_data;
                    }
                }
                else
                {
                    if (isset ($current[$tag][0]) && is_array($current[$tag])) {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        if ($priority == 'tag' && $get_attributes && $attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    }
                    else
                    {
                        $current[$tag] = array (
                            $current[$tag],
                            $result
                        );
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' && $get_attributes) {
                            if (isset ($current[$tag . '_attr']) && is_array($current[$tag]))
                            {
                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset ($current[$tag . '_attr']);
                            }
                            if ($attributes_data)
                            {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            }
            elseif ($type == 'close')
            {
                $current = & $parent[$level -1];
            }
        }
        return ($xml_array);
    }


    //获取accesstoken
    public function getAccessToken() {
        $tokenFile = ROOT_PATH."public/XmlLog/access_token.txt";
        $data = json_decode(file_get_contents($tokenFile,1));
        //accesstoken有效期是7200秒,这里用到的文件缓存
        //注意:文件权限问题
        if (!$data || !$data->expire_time || $data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::APP_ID."&secret=".self::APP_SECRET;
            $res = $this->curlRequest($url);
            $res =  json_decode($res);
            if($res) {
                $arr = array();
                $access_token = $res->access_token;
                $arr['expire_time'] = time() + 7000;
                $arr['access_token'] = $access_token;
                $fp = fopen($tokenFile, "w");
                fwrite($fp, json_encode($arr));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }

        return $access_token;
    }

    /**
     * 请求
     * @param $url
     * @param null $post
     * @return mixed|string
     */
    public function curl_post($url, $post=null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch,CURLOPT_HEADER,0);

        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if(!empty($post)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result=curl_exec($ch);
        $this->write_log($result);
        if(!$result){
            throw new Exception('发送消息失败:'.curl_error($ch));
        }
        curl_close($ch);
    }
    public  function write_log($data){
        $years = date('Y-m');
        //设置路径目录信息
        $url = ROOT_PATH.'public/XmlLog/'.$years.'/'.date('Ymd').'_xmlstring_log.txt';
        $dir_name=dirname($url);
        //目录不存在就创建
        if(!file_exists($dir_name))
        {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        fwrite($fp,var_export($data,true)."\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }

   
    //将临时素材上传至微信服务器返回media_id
    public function uploadPicture($load){
        $shell = "curl -F media=@".$load." 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->getAccessToken()."&type=image'";
        $lists = shell_exec($shell);
        $da = json_decode($lists,true);
        return $da["media_id"];
    }

    /**
     * 请求
     * @param $url
     * @param null $post
     * @return mixed|string
     */
    public static function curlRequest($url, $post=null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
        curl_setopt($ch,CURLOPT_HEADER,0);

        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        if(!empty($post)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }

        $result=curl_exec($ch);
        if(curl_getinfo($ch,CURLINFO_HTTP_CODE) != 200){
            $result = curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
}

 

 

 public function queryData()
    {
        $wechatObj = new WechatAPI();
//令牌成功后注释掉
//        $wechatObj->isValid();

        if ($wechatObj->checkSignature() === true) {

            $xmlstring = file_get_contents("php://input");
            $accept_info = $wechatObj->xml2Array($xmlstring)['xml'];
            if ($accept_info) {
                $ToUserName = $accept_info['ToUserName'];
                $FromUserName = $accept_info['FromUserName'];
                $CreateTime = $accept_info['CreateTime'];
                $MsgType = $accept_info['MsgType'];
                //$MsgId = $accept_info['MsgId'];
                // $Encrypt = $accept_info['Encrypt'];

                $data = array();
                if ($MsgType == 'text') {//接收文本
                    $Content = $accept_info['Content'];//文本内容
                    if ($Content != '人工客服') {
//                        $da = '';//服务器图片地址
//                        $data['touser'] = $FromUserName;
//                        $data['msgtype'] = 'image';
//                        $data['image']['media_id'] = $da;//urlencode 解决中文乱码问题
//                        $wechatObj->send($data);
//                        exit;
//                    } else {
                        //从结果集中取出数据
                        $question_model = new QuestionModel();
                        $result1 = $question_model->where('title','like','%'.$Content.'%')->select();
                        if (count($result1) == 0) {
                            $anser= '小葫芦听不懂你在说啥,如有疑问请输入“人工客服”字样进行人工客服私聊哦';
                        }else{
                            $anser = $this->html2text($result1[0]["content"]);
                        }
                        $this->write_log($anser);
                        $data['touser'] = $FromUserName;
                        $data['msgtype'] = 'text';
                        $data['text']['content'] = urlencode($anser);//urlencode 解决中文乱码问题
                        $wechatObj->send($data);
                        exit;
                    }

                } else if ($MsgType === 'image') {//接收图片
                    $data['touser'] = $FromUserName;
                    $data['msgtype'] = 'text';
                    $data['text']['content'] = urlencode('还看不懂图片哦,如有需要回复“人工客服“字样进行人工客服私聊哦');//urlencode 解决中文乱码问题
                    $wechatObj->send($data);
                    exit;
                } else if ($MsgType === 'event') {//进入客服窗口事件
                    $Event = $accept_info['Event'];
                    $SessionFrom = $accept_info['SessionFrom'];
                    if ($Event == 'user_enter_tempsession') {
                        $data['touser'] = $FromUserName;
                        $data['msgtype'] = 'text';
                        $data['text']['content'] = urlencode('您好!我是机器人,如有需要回复“人工客服“字样进行人工客服私聊哦');//urlencode 解决中文乱码问题
                        $wechatObj->send($data);
                        exit;
                    }
                }

                echo '<xml><ToUserName><![CDATA[' . $FromUserName . ']]></ToUserName><FromUserName><![CDATA[' . $ToUserName . ']]></FromUserName><CreateTime>' . $CreateTime . '</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>';
            }

        }
    }
    public static function write_log($data){
        $years = date('Y-m');
        //设置路径目录信息
        $url = ROOT_PATH.'public/XmlLog/'.$years.'/'.date('Ymd').'_xmlstring_log.txt';
        $dir_name=dirname($url);
        //目录不存在就创建
        if(!file_exists($dir_name))
        {
            //iconv防止中文名乱码
            $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        fwrite($fp,var_export($data,true)."\r\n");//写入文件
        fclose($fp);//关闭资源通道
    }

    public function html2text($str){
        $str = preg_replace("/<style .*?<\\/style>/is", "", $str);
        $str = preg_replace("/<script .*?<\\/script>/is", "", $str);
        $str = preg_replace("/<br \\s*\\/>/i", ">>>>", $str);
        $str = preg_replace("/<\\/?p>/i", "", $str);
        $str = preg_replace("/<\\/?td>/i", "", $str);
        $str = preg_replace("/<\\/?div>/i", "", $str);
        $str = preg_replace("/<\\/?blockquote>/i", "", $str);
        $str = preg_replace("/<\\/?li>/i", "", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/ /i", " ", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/&/i", "&", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/</i", "<", $str);
        $str = preg_replace("/“/i", '"', $str);
        $str = preg_replace("/&ldquo/i", '"', $str);
        $str = preg_replace("/‘/i", "'", $str);
        $str = preg_replace("/&lsquo/i", "'", $str);
        $str = preg_replace("/'/i", "'", $str);
        $str = preg_replace("/&rsquo/i", "'", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/>/i", ">", $str);
        $str = preg_replace("/”/i", '"', $str);
        $str = preg_replace("/&rdquo/i", '"', $str);
        $str = strip_tags($str);
        $str = html_entity_decode($str, ENT_QUOTES, "utf-8");
        $str = preg_replace("/&#.*?;/i", "", $str);
        return $str;
    }

微信公众平台 开发->开发设置 ->消息推送

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值