微信公众号对接

<?php
class UserAction extends Action {
	//获取微信网页授权
	public function wechatLogin(){
		$state=$_GET['state'];
		if(!isset($state) || empty($state)){
			$state='STATE';
		}
		$WX_APPID = 'wxeffd**************';
		$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 "<script>";
        echo "window.location.href='".$url."'";
        echo "</script>";
	}
	//获取用户的openid  
	public function getopenid($code){  
	    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=".$code."&grant_type=authorization_code";
	    $info=$this->geturl($url);
	    $info=json_decode($info);
	    $info=$this->objecttoarray($info);
	    return $info;
	} 
	//获取用户详细个人信息
	function userinfo($token,$openid){
		$url1="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openid."&lang=zh_CN";
	    $userinfo=$this->geturl($url1);
	    $userinfo==json_decode($userinfo);
	    $userinfo=$this->objecttoarray($userinfo);
	    return $userinfo;
	} 
	//判断用户是否登录
	function islogin(){
        
		//session没有openid,去授权登录,有openid,直接跳页面
		$openid=$_SESSION['openid'];
		$code=$_GET['code'];
		$state=$_GET['state'];
		if(!isset($openid) || empty($openid)){
			//获取openid,没有就去重新获取openid,查看数据库,如果没有,写入库
			$info=$this->getopenid($code);
			$res=M('zpuser')->where("openid='".$info['openid']."'")->find();
			//如果表里没有openid,写入openid
			if(!$res){
				$info1['openid']=$info['openid'];
				$login=M('zpuser')->add($info1);
				$_SESSION['openid']=$info['openid'];
				$_SESSION['uid']=$login;
				if($login){
					if($state=='STATE'){
						$urlrec="http://www.hxgz.com.cn/htzp/wechat/#/job/list/staff";
					}else{
						$urlrec="http://www.hxgz.com.cn/htzp/wechat/#/".$state;
					}
				}else{
					//授权失败
					$urlrec="http://www.hxgz.com.cn/htzp/index.php/User/wechatLogin";
				}
			}else{
				//如果有openid,直接跳页面
				$_SESSION['openid']=$res['openid'];
				$_SESSION['uid']=$res['id'];
			}
		}else{
			$urlrec="http://www.hxgz.com.cn/htzp/wechat/#/".$state;
		}
//        redirect($urlrec);
		echo "<script>";
		echo "window.location.href='".$urlrec."'";
		echo "</script>";
	}
	//获取网页内容
	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 = "wx********************";
			$appsecret = "55**********";
			$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)<time()){
					
					$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
					$re = $this->curlGet($url);
					$re=json_decode($re,true);
					$data['ticket'] = $re['ticket']; 
					$data['creat_time'] = time(); 				
					M('ticket')->where('id='.$ticket['id'])->save($data);
				}
			}else{
				$access_token = $this->gettoken();
				$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
				$re = $this->curlGet($url);
				$re=array(json_decode($re));
				$data['ticket'] = $re['ticket'];  
				$data['creat_time'] = time();  
				M('ticket')->add($data);
			}
			$ticket=M('ticket')->find();
			$msg=array('code'=>0,'msg'=>$ticket['ticket']);
			echo json_encode($msg);
			
		} 
		
		function curlGet($url,$method='get',$data=''){  
			$ch = curl_init();  
			curl_setopt($ch, CURLOPT_URL, $url);  
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));  
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');  
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
			curl_setopt($ch, CURLOPT_AUTOREFERER, 1);  
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
			$temp = curl_exec($ch);  
			return $temp;  
		} 
		function getsignature(){
			//获取signature验证
			$config=array(
				'appid' =>"wxeff",
				'appsecret' =>"553",
			);
			$noncestr=$this->getNonceStr();
			$timestamp=time();
			
			$ticket=M('ticket')->find();
			$access_token=$this->gettoken();
			if($ticket){
				if(($ticket['creat_time']+3600)<time()){
					
					$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
					$re = $this->curlGet($url);
					$re=json_decode($re,true);
					$data['ticket'] = $re['ticket']; 
					$data['creat_time'] = time(); 				
					M('ticket')->where('id='.$ticket['id'])->save($data);
				}
			}else{
				$access_token = $this->gettoken();
				$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
				$re = $this->curlGet($url);
				$re=array(json_decode($re));
				$data['ticket'] = $re['ticket'];  
				$data['creat_time'] = time();  
				M('ticket')->add($data);
			}
			$ticket=M('ticket')->find();
			$ticket=$ticket['ticket'];
			
			$url=$_GET['url'];
			//dump($noncestr);dump($timestamp);dump($ticket);dump($url);
			if($noncestr&&$timestamp&&$ticket&&$url){
				$str="jsapi_ticket=".$ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$url;
				$signature=sha1($str);
				$data['appId']=$config['appid'];
				$data['timestamp']=$timestamp;
				$data['nonceStr']=$noncestr;
				$data['signature']=$signature;
				//dump($data);
				echo json_encode($data);
			}else{
				return 0;
			}

		}
		//随机生成字符串
		 function getNonceStr($length = 16){
			$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			$str = "";
			for ($i = 0; $i < $length; $i++) {
				$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
			}
			return $str;
		}		
		
}
?>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值