微信后台代码,自动更新access token,并存储到数据库,从而利用access token,在用户关注或发送消息时,获取用户昵称等信息 ?php define("TOKEN", "weixin");define("NO_OAUTH2", "noOauth2");$wechatObj = n
<?php define("TOKEN", "weixin"); define("NO_OAUTH2", "noOauth2"); $wechatObj = new wechatCallbackapiTest(); if (isset($_GET['echostr'])) { $wechatObj->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"]; if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $RX_TYPE = trim($postObj->MsgType); switch ($RX_TYPE) { case "text": $resultStr = $this->receiveText($postObj); break; case "image": $resultStr = $this->receiveImage($postObj); break; case "location": $resultStr = $this->receiveLocation($postObj); break; case "voice": $resultStr = $this->receiveVoice($postObj); break; case "video": $resultStr = $this->receiveVideo($postObj); break; case "link": $resultStr = $this->receiveLink($postObj); break; case "event": $resultStr = $this->receiveEvent($postObj); break; default: $resultStr = "unknow msg type: ".$RX_TYPE; break; } echo $resultStr; }else { echo ""; exit; } } function receiveText($object) { $funcFlag = 0; $contentStr = $this->get_name($object).",你发送的是文本,内容为:".$object->Content; $resultStr = $this->transmitText($object, $contentStr, $funcFlag); return $resultStr; } public function get_name($object) { $access_token=$this->readtoken(); //这里需要解决access_token 2个小时有效期的问题, //一个思路是,新定义一个函数,只要一调用这个函数,则查找数据库上一个access_token生成的时间,对比现在的时间 //若超过2个小时,则用get方式获取新的access_token,并返回新的access_token,且存储到数据库中; //若不到2个小时,则把数据库中已经存储的最新的access_token提取并返回; $openid=$object->FromUserName; //拼成获取用户信息的SSL get方式的API链接 $infourl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"; $result=$this->https_get($infourl); //var_dump($result); //echo $result; $utfresult=utf8_encode($result); $mm=json_decode($result,true); return trim($mm['nickname']); } public function newtoken() { //$appid="wx2b558d720b186565";//此为ipad mini账号对应的appid //$appsecret="fe9f74ef9abf75a63d6750e365d49cad";//此为ipad mini账号对应的secret $appid="wx66c888ff7a867359";//此为iphone对应的appid $appsecret="fad178aa420ceef67e16dd6a4812e6dc";//此为iphone账号对应的secret $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; //echo $access_token_url; $access_json=$this->https_get($access_token_url); //$access_json='{"access_token":"sXr18Q9qklWbLFuBAi5w6B-kWeXVXW2dtHwb53Iy2wdgnebSDFs8r4NwT8uTafgB6rMXc00lsE5HayE28N9-KTHv5HyHG8b8UFxsvLBNgAU","expires_in":7200}'; //echo $access_json; $access=json_decode($access_json,true); //var_dump($access); //echo $access_array['access_token']; return $access['access_token']; } public function savetoken($token) { $host=""; //数据库服务器名称 $user=""; // 连接数据库用户名 $pw=""; // 连接数据库密码 $db=""; // 数据库的名字 //连接到mysql数据库 $conn=mysql_connect($host,$user,$pw); //mysql_query("set names 'utf8'"); if ($conn) { mysql_select_db ($db); //mysql_set_charset("gbk"); //$sql = "select * from token"; $time=time(); //$token=newtoken(); //echo $time; $sql="insert into token (time,token) VALUES ('$time','$token')"; $result = mysql_query($sql) or die("Invalid query: " . mysql_error()); //$mm=mysql_fetch_array($result); //var_dump($mm); mysql_free_result($result); } else { echo "数据库连接KO"; } } public function readtoken() { $host=""; //数据库服务器名称 $user=""; // 连接数据库用户名 $pw=""; // 连接数据库密码 $db=""; // 数据库的名字 //连接到mysql数据库 $conn=mysql_connect($host,$user,$pw); //数据库输出编码 应该与你的数据库编码保持一致 //mysql_query("set names 'utf8'"); if ($conn) { //选择数据库 mysql_select_db($db); //mysql_set_charset("gbk"); //在token这个表里,按照time列降序排序,取出time列的第一个值(即limit 1) $sql = "select time,token from token order by time desc limit 1"; //执行sql语句 $result = mysql_query ($sql) or die("Invalid query: " . mysql_error()); //获取执行后的结果,以数组保存到变量¥mm中 $mm=mysql_fetch_array($result); mysql_free_result($result); //用列的表头访问数组,得到最后一次存储的时间戳 $lasttime=$mm['time']; //echo "<br><br><br><br><br>".$lasttime; //生成现在的时间,时间戳 $timenow=time(); //如果现在的时间减去最后一次存储的时间戳,如果小于7100,则再次sql,获取已经存储到表的token,若不是,则新生成token,并存储到数据库 if($timenow-$lasttime<7100){ $tokenread=$mm['token']; return $tokenread; //echo "<br><br><br><br><br>".$tokenread; }else{ $newtoken=$this->newtoken(); $this->savetoken($newtoken); $tokenread=$newtoken; return $tokenread; } } } public function https_get($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); //curl_setopt($curl, CURLOPT_POST, 1); //curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); if (curl_errno($curl)) { return 'Errno'.curl_error($curl); } curl_close($curl); return $result; } private function receiveEvent($object) { $contentStr = ""; switch ($object->Event) { case "subscribe": //$uername=json_decode($object,true); $contentStr = "欢迎你!".$this->get_name($object); //当用户订阅后,需要存储下所有用户的信息,openid,昵称,地址等等; //调用存储 函数,需要新创建。。。。 break; case "unsubscribe": $contentStr = ""; break; case "CLICK": switch ($object->EventKey) { case NO_OAUTH2: //$contentStr = NO_OAUTH2; $contentStr = "[<a href='http://www.xxx.com/weixin/courseCenter.php?wx_openid=" . $object->FromUserName . "'>我的课堂</a>] [<a href='http://www.xxx.com/weixin/orderList.php?wx_openid=" . $object->FromUserName . "'>订单记录</a>]"; break; case "Oauth2": $contentStr = $this->toAuthMsg(); break; default: $contentStr = "你点击了菜单: ".$object->EventKey; break; } break; default: $contentStr = "receive a new event: ".$object->Event; break; } $resultStr = $this->transmitText($object, $contentStr); if($contentStr == NO_OAUTH2){ header("location: http://www.xxx.com/weixin/courseCenter.php?wx_openid=" . $object->FromUserName); exit; } return $resultStr; } private function transmitText($object, $content, $flag = 0) { $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>%d</FuncFlag> </xml>"; $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag); return $resultStr; } private function toAuthMsg() { $resultStr = "<a href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx834404c1d1dbb5ec&redirect_uri=http://www.xxx.com/weixin/oauth2_code.php&response_type=code&scope=snsapi_base&state=liutest012#wechat_redirect'>马上绑定</a>"; return $resultStr; } } ?>