微信公众号自动回复机器人
<?php //写你自己的token define("TOKEN", "xxxxxx"); define("APPID", "xxxxxxxxxxxxxxxxxxxxxxxxx"); define("APPSECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //XML的发送文本模板 define("TEXTTPL", "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"); //XML的发送图片模板 define("IMAGETPL", "<xml><ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Image><MediaId><![CDATA[%s]]></MediaId></Image> </xml>"); $wechatObj = new wechatCallbackapiTest(); //接口验证 /*$wechatObj->valid();*/ //调用回复消息方法 $wechatObj->responseMsg(); class wechatCallbackapiTest{ //验证方法 public function valid(){ $echoStr = $_GET["echostr"]; if($this->checkSignature()){ echo $echoStr; exit; } } //消息回复 public function responseMsg(){ $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //如果用户有请求 if (!empty($postStr)){ libxml_disable_entity_loader(true); //用户请求的对象 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; //用户输入的文字 $keyword = trim($postObj->Content); $time = time(); //消息类型 $msgType = $postObj->MsgType; //事件类型 $event = $postObj->Event; //xml模板 $Tpl = TEXTTPL; //默认发送类型 $sendType = 'text'; //如果用户的请求类型是事件 if($msgType=="event"){ if($event=="subscribe"){ $contentStr = "欢迎词"; } } //用户的请求类型是文本 if($msgType=="text"){ if(substr($keyword,-6)=='图片'){ $Tpl = IMAGETPL; $sendType = "image"; /*$dir = '@'.dirname(__FILE__).'/tupian.jpg';*/ //关键词过滤 $keyword = substr($keyword, 0,-6); //图片的网络地址 $picurl = $this->getJpg($keyword); //图片的本地地址 $dir = $this->jpgChangeLocal($picurl); $contentStr = $this->uploadRes('image',$dir); }else{ $contentStr =$this-> getWord($keyword); } } //自动填充xml $resultStr = sprintf($Tpl, $fromUsername, $toUsername, $time, $sendType, $contentStr); //回复 echo $resultStr; } //用户没有请求 else{ echo ""; exit; } } //验证 private function checkSignature(){ if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); } $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } //聊天机器人 public function getWord($keyword){ $url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=".urlencode($keyword); $result = $this->_request($url); if($result){ $result = json_decode($result,true); if($result['result']==0){ return $result['content']; } } return '系统故障'; } //抓取(支持get/post) function _request($curl,$https=true,$method='GET',$data=null){ //1.创建一个新cURL资源 $ch = curl_init(); //2.设置URL和相应的选项 //要访问的网站 curl_setopt($ch, CURLOPT_URL, $curl); //启用时会将头文件的信息作为数据流输出。 curl_setopt($ch, CURLOPT_HEADER, false); //将curl_exec()获取的信息以字符串返回,而不是直接输出。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if($https){ //FALSE 禁止 cURL 验证对等证书(peer's certificate)。 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //可以省略不写,默认为2 /* curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //验证主机 */ } if($method == 'POST'){ //发送 POST 请求 curl_setopt($ch, CURLOPT_POST, true); //全部数据使用HTTP协议中的 "POST" 操作来发送。 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } //3.抓取URL并把它传递给浏览器 $content = curl_exec($ch); if ($content === false) { return "网络请求出错: " . curl_error($ch); exit(); } //4.关闭cURL资源,并且释放系统资源 curl_close($ch); return $content; } //access_token是公众号的全局唯一接口调用凭据 function getAccess_token(){ $appid = APPID; $appsecret = APPSECRET; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}"; $resultData = json_decode($this->_request($url),true); return $resultData['access_token']; } //上传资源,新增临时素材,返回media_id function uploadRes($type,$media){ $data = array('media'=>$media); $access_token = $this->getAccess_token_sql(); $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type={$type}"; $resultData = json_decode($this->_request($url,true,'POST',$data),true); return $resultData['media_id']; } //为提高速度,通过MySQL获取Access_token function getAccess_token_sql(){ //创建数据库连接 $conn = mysqli_connect('xxxxxxxxxx','xxxxxx','xxxxx','xxxxxxxxxxxxxxx'); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $sql = "SELECT * FROM access_token WHERE ID = 1"; $result = mysqli_query($conn, $sql); if($row = mysqli_fetch_assoc($result)){ $access_token = $row['access_token']; $update_time = $row['update_time']; } $time = time(); //如果时间相隔小于两小时,以前的token还能用 if($time-$update_time<7150){ return $access_token; }else{ $access_token = $this->getAccess_token(); //更新数据库,把token写入并更新时间 mysqli_query($conn,"UPDATE access_token SET access_token = '{$access_token}',update_time = {$time} WHERE ID = 1"); return $access_token; } } //网络图片转换本地图片 function jpgChangeLocal($pic){ //获取文件 $file = $this->_request($pic); $filename = 'image/'.time().'.jpg'; //打开写入流 $resource = fopen($filename, 'a'); //写入 fwrite($resource, $file); //关闭资源 fclose($resource); return '@'.dirname(__FILE__).'/'.$filename; } //通过关键词返回jpg百度图片网络地址 function getJpg($keyword){ $url = "https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord+=&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&word={$keyword}"; $result = $this->_request($url); //查询后json转换得到的数组 $resultdata = json_decode($result,true); /*return $data['data'][0]['hoverURL'];*/ //过滤data foreach($resultdata['data'] as $key => $value){ //如果这url不为空 if(strlen($value['hoverURL'])>20){ //添加到数组 $urldata[] = $value['hoverURL']; } } if($urldata){ //随机发送图片 $index = rand(0,count($urldata)-1); return $urldata[$index]; // }else{ //查询失败默认返回图片 return 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=75145293,1379637150&fm=27&gp=0.jpg'; } } }