微信公眾號對接
阿新 • • 發佈:2019-01-07
<?php class UserAction extends Action { //獲取微信網頁授權 public function wechatLogin(){ $state=$_GET['state']; if(!isset($state) || empty($state)){ $state='STATE'; } $WX_APPID = 'wxeffd2c87deb3d6de'; $redirectUrl = urlEncode("http://www.a.com/htzp/index.php/User/islogin"); $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$WX_APPID.'&redirect_uri='.$redirectUrl.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect'; //redirect($url); echo ""; } //獲取網頁內容 function geturl($url){ $ch1 = curl_init (); $timeout = 5; curl_setopt ( $ch1, CURLOPT_URL, $url ); curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false ); $res = curl_exec ( $ch1 ); curl_close ( $ch1 ); return $res; } //物件轉陣列 function objecttoarray($obj) { $obj = (array)$obj; foreach ($obj as $k => $v) { if (gettype($v) == 'resource') { return; } if (gettype($v) == 'object' || gettype($v) == 'array') { $obj[$k] = (array)object_to_array($v); } } return $obj; } //獲取access_token值 function tonkenacc($appid,$appsecret){ $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); //file_put_contents('token.txt',"-----token呼叫".date("Y-m-d H:i:s")."----- \r\n".$output." \r\n",FILE_APPEND); curl_close($ch); $jsoninfo = json_decode($output, true); $access_token = $jsoninfo["access_token"]; return $access_token; } //將access_token寫入資料庫 //記錄時間,訪問1小時以內,值不變,超過2個小時,直接讀取資料庫的值 function gettoken(){ $appid = "wxeffd2c8"; $appsecret = "5539bb3e636"; $tok=M('accesstoken')->find(); //如果有值 if($tok){ //access_token15分鐘過期 $begtime=$tok['creat_time']+3600; //判斷時間是否過期 if($begtime<=time()){ //超時。獲取值,並更新資料庫 //不超時,不做任何改變 $access_token=$this->tonkenacc($appid,$appsecret); $arr=array("token"=>$access_token,"creat_time"=>time()); $re=M('accesstoken')->where('id='.$tok['id'])->save($arr); //沒有更新成功,反回識別符號1 } }else{ //沒有值。獲取值並存入資料庫 $access_token=$this->tonkenacc($appid,$appsecret); $arr=array("token"=>$access_token,"creat_time"=>time()); $rea=M('accesstoken')->add($arr); } $tok=M('accesstoken')->find(); //$msg=array('code'=>0,'msg'=>$tok['token']); //echo json_encode($msg); return $tok['token']; } /** * [getJsapiTicket description] 獲取jsapi_ticket * @return [type] [description] */ function getJsapiTicket(){ $ticket=M('ticket')->find(); $access_token=$this->gettoken(); if($ticket){ if(($ticket['creat_time']+3600)