|
- <?php
- class WeChat{
- private $_appid;
- private $_appsecret;
- private $_accessToken;
- public $debug=DEBUG;
- public $MsgType='text';
- public $msg=array();
- /* //QRCode类型
- const QRCODE_TYPE_TEMP=1;
- const QRCODE_TYPE_LIMIT=2;
- const QRCODE_TYPE_LIMIT_STR=3; */
- public function __construct($appid,$appsecret){
-
- $this->_appid=$appid;
- $this->_appsecret=$appsecret;
- if (isset($_GET['echostr'])) {
- $this->valid();
- }
- if (ALWAYSCHECK==true){
- $check=$this->checkSignature();
- if (!$check){
- $this->writelog("checkSignature()--非法服务器");
- exit;
- }
- }
- $this->_accessToken= $this->getAccessToken();
- }
- public function getAccessToken(){
-
- $dir="./Log";
- if (!is_dir($dir)){
- mkdir($dir);
- }
- $token_file=$dir.'/access_token';
- if (file_exists($token_file) && time()-filemtime($token_file)<4800){
- $this->writelog("文件中读取的token:".file_get_contents($token_file));
- return file_get_contents($token_file);
- }
- $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
- $result=$this->_requestGet($url);
- if(!$result){
- $this->writelog("获取token出错");
- return false;
- }
- $result_obj=json_decode($result);
-
- file_put_contents($token_file, $result_obj->access_token);
- $this->writelog("url获取的token:".$result_obj->access_token);
- return $result_obj->access_token;
- }
- private function _requestGet($url,$ssl=true){
- $curl=curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- /* $user_agent=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
- curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); */
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- if ($ssl){
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
- }
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $response=curl_exec($curl);
- if ($response===false){
- $this-> writelog('_requestGet()--返回值错误');
- return false;
- }
- return $response;
- }
- private function _requestPost($url,$data,$ssl=true){
- $curl=curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- $user_agent=isset($_SERVER['HTTP_USER_AGENT'])?$$_SERVER['HTTP_USER_AGENT']:'';
- curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- if ($ssl){
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
- }
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $response=curl_exec($curl);
- if ($response===false){
- $this->writelog('_requestPost()--返回值错误');
- return false;
- }
- //$error=json_decode($response,true);
- $this->writelog("url:".$url);
- $this->writelog("curl返回值为".$response);
-
- return $response;
- }
-
- public function valid()
- {
- $echoStr = $_GET["echostr"];
- //valid signature , option
- if($this->checkSignature()){
- $this->writelog( "valid()--第一次验证成功");
- echo $echoStr;
- exit;
- }else {
- $this->writelog( "valid()--第一次验证,非法服务器");
- exit();
- }
- }
- private function checkSignature()
- {
- // you must define TOKEN by yourself
- 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;
- }
- }
- private function writelog($activation){
- $dir="./Log";
- if (!is_dir($dir)){
- mkdir($dir);
- }
- $filename=date("Y-m-d").".txt";
- $open=fopen($dir."/".$filename,"a");
- fwrite($open,date("Y-m-d H:i:s")."\t".$activation."\r\n");
- fclose($open);
- }
- //获取消息
- public function responseMsg()
- {
- //get post data, May be due to the different environments
- //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
- $postStr = file_get_contents("php://input");
-
- if ($this->debug){
- $this->writelog("function:responseMsg--接收到的消息为--".$postStr);
- }
- //extract post data
- if (!empty($postStr)){
- /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
- the best way is to check the validity of xml by yourself */
- libxml_disable_entity_loader(true);
- $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
- foreach ($this->msg as $key=>$v){
- $this->writelog("function:responseMsg--接收到的消息为--".$key);
- $this->writelog("function:responseMsg--接收到的消息为--".$v);
- }
- $this->MsgType=strtolower($this->msg['MsgType']);
- return $this->msg;
- }else {
- $this->writelog("消息为空");
- return false;
- }
- }
- public function eventMsg($array){
- switch ($array['Event']){
- case 'subscribe':
- if (!empty($array['EventKey'])){
- $id=substr($array['EventKey'],strpos($array['EventKey'],"qrscene_")+8);
- $openid=$array['FromUserName'];
- $time=date("Y-m-d H:i:s");
- $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
- $selectDate=$pdo->query($sql);
- $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
- if (empty($selectRes)){
- $sql1="INSERT INTO qrcodeDetail values($id,'$openid','subscribe','$time')";
- $this->writelog("eventMsg function : subscribe:result id=".$id."--sql1-".$sql1);
- $result=$pdo->exec($sql1);
- }
-
-
-
-
- /* $this->writelog("eventMsg function : SCAN:result id=".$id."---".json_encode($result));
- $errinfo=$pdo->errorInfo();
- if ($errinfo[0] !='00000')
- $this->writelog("eventMsg function : SCAN:error id=".$id."---".$errinfo[2]);
- else{
- $res=$result->fetchAll(PDO::FETCH_ASSOC);
- $this->writelog("eventMsg function : SCAN:res id=".$id."---".json_encode($res));
- $headUrl=$res[0]['url'];
- $this->writelog("eventMsg function : SCAN:headUrl id=".$id."---".$headUrl);
-
- header("Location: $headUrl");exit;
- } */
- // $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
-
- $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
- $selectDate2=$pdo->query($sql2);
- $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
- if (!empty($selectRes2)){
- $media_id= $selectRes2[0]['media_id'];
- $Rurl= $selectRes2[0]['url'];
- }else {
- $media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
- $Rurl="http://xmwxc.zhizhuchuxing.cn/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
- }
- $data='{"media_id":"'.$media_id.'"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
-
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- }
- }else{
-
- $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- }
-
-
- /* $contentStr="朋友你好,欢迎关注蜘蛛出行💐~
- 蜘蛛出行是专注于互联网+交通出行的科技品牌,您提供安全舒适便捷的巴士出行服务。
-
- 点击下方预订按钮开始体验吧!
-
- <a href='http://xmwxc.zhizhuchuxing.cn/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01'>点这里预订普陀山门票</a>
- 免去窗口排队苦恼😄
- 普陀山官方合作伙伴";
- $textTpl="
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType="text";
- $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr); */
- }
-
- break;
- case 'SCAN':
- if (isset($array['EventKey'])){
- $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- $id=$array['EventKey'];
- $openid=$array['FromUserName'];
- $time=date("Y-m-d H:i:s");
- $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
- $selectDate=$pdo->query($sql);
- $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
- if (empty($selectRes)){
- $sql1="INSERT INTO qrcodeDetail values($id,'$openid','SCAN','$time')";
- $this->writelog("eventMsg function : SCAN:result id=".$id."--sql1-".$sql1);
- $result=$pdo->exec($sql1);
- }
-
- /* $this->writelog("eventMsg function : SCAN:result id=".$id."---".json_encode($result));
- $errinfo=$pdo->errorInfo();
- if ($errinfo[0] !='00000')
- $this->writelog("eventMsg function : SCAN:error id=".$id."---".$errinfo[2]);
- else{
- $res=$result->fetchAll(PDO::FETCH_ASSOC);
- $this->writelog("eventMsg function : SCAN:res id=".$id."---".json_encode($res));
- $headUrl=$res[0]['url'];
- $this->writelog("eventMsg function : SCAN:headUrl id=".$id."---".$headUrl);
-
- header("Location: $headUrl");exit;
- } */
- // $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
- $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
- $selectDate2=$pdo->query($sql2);
- $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
- if (!empty($selectRes2)){
- $media_id= $selectRes2[0]['media_id'];
- $Rurl= $selectRes2[0]['url'];
- }else {
- $media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
- $Rurl="http://xmwxc.zhizhuchuxing.cn/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
- }
- $data='{"media_id":"'.$media_id.'"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- elseif($k==2){
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- }
- }
- break;
- case 'CLICK':
- if (isset($array['EventKey']) && $array['EventKey']=='Push-Photo-List'){
- $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- }
- }
-
- }
- /*
- $data='{"type":"news","offset":0,"count":20}';
- $url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response); */
- $this->writelog("回复用户event--".json_encode($result));
- return $result;
-
- }
- private function aa(){
-
- }
- //把openid存入数据库
- public function insertOpenid($data,$type){
- $openid=$data['FromUserName'];
- if ($type =='subscribe'){
- $sql="insert into wx_user(openid) values('{$openid}')";
- }else if($type =='unsubscribe'){
- $sql="delete from wx_user where openid='{$openid}'";
- }
- $result='';
- try {
- $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- //$pdo=new PDO("mysql:host=".HOST.";dbname=".DB,USER,PASSWORD); //7.0版本pdo连接mysql
- $result=$pdo->exec($sql);
- $errinfo=$pdo->errorInfo();
- if ($errinfo[0] !='00000')
- $this->writelog($errinfo[2]);
- } catch (PDOException $e) {
- $this->writelog($e->getMessage());
- }
- if ($result){
- return true;
- }else {
- return false;
- }
- }
- //有用户关注的时候推送多图文消息
- private function transmitNews($array, $newsArray)
- {
- if(!is_array($newsArray)){
- return;
- }
- $itemTpl = "<item>
- <Title><![CDATA[%s]]></Title>
- <Description><![CDATA[%s]]></Description>
- <PicUrl><![CDATA[%s]]></PicUrl>
- <Url><![CDATA[%s]]></Url>
- </item>";
- $item_str = "";
- foreach ($newsArray as $item){
- $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
- }
- $xmlTpl = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[news]]></MsgType>
- <ArticleCount>%s</ArticleCount>
- <Articles>
- $item_str</Articles>
- </xml>";
-
- $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), count($newsArray));
- return $result;
- }
- //获取文本
- public function textMsg($data){
- $Content=trim($data['Content']);
- $textTpl="
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType = "text";
- $contentStr=$this->simsimiHttp($Content);
- $this->writelog("textMsg有调用:".$contentStr);
-
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
- $this->writelog($resultStr);
- //return $resultStr;
- return "";
- }
- private function simsimiHttp($msg){
- $url="http://www.xiaodoubi.com/simsimiapi.php?msg=".$msg;
- $res = file_get_contents($url);
- file_put_contents("./demo.txt",date("Y-m-d H:i:s")." ".$res.PHP_EOL,FILE_APPEND);
- if (strpos($res,"xiaodouqqcom") !== false){
- $res="无法回答,请不要发一下奇怪的问题或字符😒";
- }
- if (strpos($msg,"主人") !== false){
- $res="我的主人是宇宙无敌超级大帅哥^_^人称陌帅";
- }
- return $res;
- }
- private function checkAccessToken($check){
- if (isset($check['errcode']) && $check['errcode'] ==40001){
- $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
- $result=$this->_requestGet($url);
- if(!$result){
- $this->writelog("获取token出错");
- return false;
- }
- $result_obj=json_decode($result);
-
- file_put_contents($token_file, $result_obj->access_token);
- $this->writelog("url获取的token:".$result_obj->access_token);
- return $result_obj->access_token;
- }
- }
- }
- ?>
|