基于微信注册登录类 一句代码调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhongyuchuan147/article/details/80147849
首先需要配置基本的文件
	private $Wxconfig=[
		'appID'=>'appid',//微信公众号appid
		'appsecret'=>'appsecret',//微信公众号appsecret
		'token'=>'token',//token
		// 'Callback'=>'http://'.$this->_server('SERVER_NAME').'/index.php/Home/WeiXinUser/getWxUserInfo/',//回调地址
		
		'EncodingAESKey'=>'JpZS1G3bYooK3ziBlbXrqwN3LIFlISOmnlVXBocx53k',//
		// 'Callback'=>"'".$_SERVER['SERVER_NAME']."'"
	];   

这些配置可以在微信公众号里面调用然后根据数据库修改WeiXinOpenidGetUserInfo方法 里面有数据库的相关操作

以下是完整代码

<?php
namespace movie\Controller;
use Think\Controller;
class WeiXinUserController extends ComController
{
	
	
	private $Wxconfig=[
		'appID'=>'wx0b8fe631e5826552',//微信公众号appid
		'appsecret'=>'c5eefb983d6ed4c46c9e7b8afc939a0b',//微信公众号appsecret
		'token'=>'8ef3c0b7455b61d2af9c5aeee3fc3c7b',//token
		// 'Callback'=>'http://'.$this->_server('SERVER_NAME').'/index.php/Home/WeiXinUser/getWxUserInfo/',//回调地址
		
		'EncodingAESKey'=>'JpZS1G3bYooK3ziBlbXrqwN3LIFlISOmnlVXBocx53k',//
		// 'Callback'=>"'".$_SERVER['SERVER_NAME']."'"
	];   

	public function getWxConfig(){
		return $Wxconfig;
	}


	// 获取用户信息
	public function getWxUserInfo($link){ 
 
		// 如果存在则直接生成token
        $token=cookie('token')?cookie('token'):'';
      	$gettoken=isset($_GET['token'])?$_GET['token']:'';
        
		if($gettoken or $token){
              if($gettoken){$token=$gettoken;}
              $userid=isset(explode('-',$token)[0])?explode('-',$token)[0]:0;
              $userInfo=M('user')->where('userid='.$userid)->find();
              if(!$userInfo){
                $COM=$_SERVER['SERVER_NAME'];
                 if(C('COM_LIST')!=$COM){
                    if(isset($_GET['userid'])){
                        echo "<script language='javascript' type='text/javascript'>window.location.href='http://".C('COM_LIST')."/index.php?userid=".$_GET['userid']."'</script>"; exit;
                    }
                    echo "<script language='javascript' type='text/javascript'>window.location.href='http://".C('COM_LIST')."/index.php'</script>"; exit;

                }
                  $token=$this->Wxlogin($link);
              }

              $COM=$_SERVER['SERVER_NAME'];
              if(C('COM_LIST')==$COM){
                  $link=M('comlist')->where('status=1')->find()['com'];
                  if($link){
                      if(isset($_GET['userid'])){
                      echo "<script language='javascript' type='text/javascript'>window.location.href='http://".$link."?userid=".$_GET['userid']."&token=".$token."'</script>"; exit;
                      }
                      echo "<script language='javascript' type='text/javascript'>window.location.href='http://".$link."?token=".$token."'</script>"; 

                      exit;
                  }
              }

              cookie('token',$token,60*60);//一个小时
              return $userInfo;
          }
      
    
          	$COM=$_SERVER['SERVER_NAME'];
       
			if(C('COM_LIST')!=$COM){
             
				if(isset($_GET['userid'])){
	        		echo "<script language='javascript' type='text/javascript'>window.location.href='http://".C('COM_LIST')."/index.php?userid=".$_GET['userid']."'</script>";
	        		exit;
	        	}
             	$link='http://'.C('COM_LIST');
              	//echo $link;exit;
				echo '<script>window.location.href="'.$link.'"</script>';  ;
	        	exit;
			}
      
      
    
			$token=$this->Wxlogin($link);
			$userid=isset(explode('-',$token)[0])?explode('-',$token)[0]:0;
			$userInfo=M('user')->where('userid='.$userid)->find();
			cookie('token',$token,60*60);//一个小时
     		$link=M('comlist')->where('status=1')->find()['com'];
     		if(isset($_GET['userid'])){
	        	echo "<script language='javascript' type='text/javascript'>window.location.href='http://".$link."?userid=".$_GET['userid']."&token=".$token."'</script>";  
	        	exit;
	        }
      	    echo "<script language='javascript' type='text/javascript'>window.location.href='http://".$link."?token=".$token."'</script>";  
	        exit;
			return $userInfo;
	}

	//微信登录
	public function Wxlogin($link){
		$token=$this->getWeiXinUserCode($link);
		return $token;
	}

	public function getWxJsApiConfig(){
		$access_token=$this->getWeiXinServerAccess();
		$noncestr=$this->generate_password();//随机字符串
		$timestamp=time();
		$jsapi_ticket=$this->getWeiXinjsapi_ticket();
		$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		$url=explode('#', $url)[0];
		$signature=sha1('jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url);
		$data=array(
			'appid'=>$this->Wxconfig['appID'],
			'access_token'=>$access_token,
			'noncestr'=>$noncestr,
			'timestamp'=>$timestamp,
			'jsapi_ticket'=>$jsapi_ticket,
			'url'=>$url,
			'signature'=>$signature
		);
		return $data;

	}

	private function getWeiXinjsapi_ticket(){
		$ticket=session('ticket');
		if(!$ticket){
			$api='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this->getWeiXinServerAccess().'&type=jsapi';
			$json=json_decode($this->post_Https($api));
			$ticket=$json->ticket;
			session(array('ticket'=>$ticket,'expire'=>7200));
		}
		return $ticket;
		
	}


	//获取服务器Access方法
	private function getWeiXinServerAccess(){
		$ServerAccess=session('WxServerAccess');
		if($ServerAccess){
			return $ServerAccess;
		}else{
			$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->Wxconfig['appID'].'&secret='.$this->Wxconfig['appsecret'];
			$json=json_decode($this->post_Https($url));
			session(array('WxServerAccess'=>$json->access_token,'expire'=>60*30));
			return $json->access_token;
		}
	}

	// 返回随机字符串
	private function generate_password( $length = 8 ) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
		$password = '';  
		for ($i=0;$i<$length;$i++){
			$password.=substr($chars,mt_rand(0,strlen($chars)-1),1);  
		}  
		return $password;  
	} 


	// 获取code进行请求
	private function getWeiXinUserCode($link){
		$code=isset($_GET['code'])?$_GET['code']:'';
		if($code){
			// 获取网页授权access_token
			$api='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->Wxconfig['appID'].'&secret='.$this->Wxconfig['appsecret'].'&code='.$code.'&grant_type=authorization_code';
			$json=json_decode($this->post_Https($api));
			$access_token=$json->access_token;
			$openid=$json->openid;
			if(!$openid){
				if($link){
					$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->Wxconfig['appID'].'&redirect_uri='.urlencode($link).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
					echo "<script>window.location.href='".$url."'</script>"; exit;
				}else{
					$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->Wxconfig['appID'].'&redirect_uri='.urlencode($this->Wxconfig['Callback']).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
					echo "<script>window.location.href='".$url."'</script>";exit;
				}			}
			$token=$this->WeiXinOpenidGetUserInfo($openid,$access_token,$link);
			return $token;

		}else{
			if($link){
				$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->Wxconfig['appID'].'&redirect_uri='.urlencode($link).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
				echo "<script>window.location.href='".$url."'</script>"; exit;
			}else{
				$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->Wxconfig['appID'].'&redirect_uri='.urlencode($this->Wxconfig['Callback']).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
				echo "<script>window.location.href='".$url."'</script>"; exit;
			}
			 
		}
	}

	//拿openid进行数据请求
	private function WeiXinOpenidGetUserInfo($openid,$access_token,$link){
		if(!$openid){
			if($link){
				echo "<script>window.location.href='".$link."'</script>";exit;
			}else{
				echo "<script>window.location.href='".$this->Wxconfig['Callback']."'</script>"; exit;
			}
			 
		}
		// 查询数据库是否存在 如果用户存在则直接返回不然请求之后返回数据库
		$user=M('user')->where('openid="'.$openid.'"')->find();

		if($user){
			$token=$user['userid'].'-'.md5($user['openid'].time());
			cookie('token',$token,60*60);//一个小时
			return $token;
		}else{
			$api='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
			$json=json_decode($this->post_Https($api));
            $status=M('movie_config')->where('id=2')->find();
          	if(!$status['value']){
              $data=array('openid'=>$openid,'name'=>$json->nickname,'sex'=>$json->sex,'head'=>$json->headimgurl,'createtime'=>time(),'status'=>1);
            }else{
              $data=array('openid'=>$openid,'name'=>$json->nickname,'sex'=>$json->sex,'head'=>$json->headimgurl,'createtime'=>time());
            }
			
			$userid=M('user')->add($data);
			// 随机vip时间
			$data=M('movie_config')->where('id=5')->find();
			$times=$data['value'];

			$timestamp=time()+($times*60*60*24);//随机vip时间
			M('user_info')->add(['userid'=>$userid,'movietime'=>$timestamp]);
			$token=$userid.'-'.md5($openid.time().$access_token);
			M('user')->where('userid='.$userid)->save(['token'=>$token]);
			cookie('token',$token,60*60);//一个小时
			return $token;
		}

	}

	// 发送https请求
	public function post_Https($url){
		$curl = curl_init(); // 启动一个CURL会话
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_HEADER, 0);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
	    $tmpInfo = curl_exec($curl);     //返回api的json对象
	    curl_close($curl);
	    return $tmpInfo;    //返回json对象
	}

	




}



?

调用方法

$link='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
$user=$this->getWxUserInfo($link);//返回用户相关信息 link是登录之后跳转的地址

猜你喜欢

转载自blog.csdn.net/zhongyuchuan147/article/details/80147849
今日推荐