jayrui612 2017-03-29 16:45:39 10338次浏览 1条评论 8 3 0

此教程微信扫码登录 是打开新的二维码页面,扫完关闭二维码页面进入网站 建议参考之前先把官方文档看下
本教程是通过yii框架
视图层

第一步
设置微信扫码的连接

<a class="third_item" id="wechat" target="_blank"><span class="icon-chat"></span></a>

第二步
设置回调和进入不同站点 回调redirect_uri 填写你注册的那个名字 也可以通过window.location.host 来获取,
对于/login/callback 是返回你控制器login下的callback方法来进行业务处理

<script type="text/javascript">

$(document).ready(function()
{
	var i =0;
	//通过cookie进入不同页面
	var t1 = setInterval(function(){ 
		var bindphone = getCookie('bindphone');
		//这个是进入绑定手机页面
		if(bindphone == 128){		
			i=1;
			delCookie('bindphone');
			window.location.href = "/login/bindphone";
		}
		var login = getCookie('login');
		//这个是进入个人中心页面
	  if(login == 128){			
			i=1;
			delCookie('login');
			window.location.href = "/personal/info";
		} 		
	},1000);
	
	if(i == 1){
			window.clearInterval(t1);
		}
	//点击微信扫码登录
	$('#wechat').click(function(){
		var url 	 = encodeURIComponent("http://" + window.location.host + "/login/callback");
		var appid	 = 'wx985c926fee0fb7a3';
		//此state状态是由你自己传值的,随便传最好给个随机数。记住这个值一定要给session,后面要验证的
		var state	 = "<?=$state?>";
		window.open("https://open.weixin.qq.com/connect/qrconnect?appid="+appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_login&state="+state+"#wechat_redirect",'三立教育','width=400,height=700,left=30,top=10');
	});

	function getCookie(c_name){
	  if(document.cookie.length>0){
		 c_start=document.cookie.indexOf(c_name + "=")
		 if (c_start!=-1){ 
			c_start=c_start + c_name.length+1 ;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		 } 
	 }
	return "";
  }
  
  function delCookie(name){
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval=getCookie(name);
	if(cval!=null)
	document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
	
});
</script>

控制器层

    public function actionCallback()
	{
		$code = $_GET["code"];
		//state 是进行验证处理的
		$state = $_GET["state"];
        $appid = "wx985c926fee0fb7a3";
        $secret = "f73ecef46c7515cc7f53aac9369a1370";
		//验证的时候到了
        if(empty($code) && (Yii::$app->session->get('state')!=$state)){
			exit;			
		}
		//将state的session清除
		Yii::$app->session->remove('wx_state');
		这个你直接复制好了。是获取你微信的信息
		 //通过code获得 access_token + openid
		$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
		$jsonResult = file_get_contents($url);
		$resultArray = json_decode($jsonResult, true);
		$access_token = $resultArray["access_token"];
		$openid = $resultArray["openid"];
		
		//通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里
		$infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
		$infoResult = file_get_contents($infoUrl);
		$infoArray = json_decode($infoResult, true);
		如果你后面页面要使用到头像和昵称的话就设为session
		Yii::$app->session->set('wechat_info', $infoArray);	
		下面条件是你数据库的字段了。
		这个是微信登陆的标识
		$condition['oauth_id']   = $infoArray['unionid'];
		这个说明是微信登陆
		$condition['oauth_type'] = 3;
		通过条件获取学生的信息是否存在
	    $studentOauthObj = UserOauthInfo::find()->where($condition)->one();
		if ($studentOauthObj) {
			$studentOauthObj->last_time  = $studentOauthObj->login_time;
            $studentOauthObj->login_time = time();
            $studentOauthObj->login_ip   = CommonHelper::getIP();
            $studentOauthObj->save();
			$havePhone = UserStudentBase::find()
                ->where(['id' => $studentOauthObj->user_id])
                ->asArray()
                ->one();
			// 将登录信息和access token写入session
            $studentOauth = $studentOauthObj->toArray();
          
			if (Yii::$app->session->get('loginRefer')) {
                return $this->redirect(Yii::$app->session->get('loginRefer'))->send();
            }
            如果扫码登录过的话直接 跳转到个人中心
			setcookie("info", 128, time()+3600);
			return $this->render('callback');
           			
		} else {
		第一次扫码绑定手机号码 向数据库写入扫码登录记录
			setcookie("bindphone", 128, time()+3600);
			return $this->render('callback');
		}
		
	}
	
	
	//微信绑定手机
	public function actionBindphone()
	{
		 if (Yii::$app->request->isPost) {
			 $phone =  Yii::$app->session->get('telephone');			 
			 $havePhone = UserStudentBase::getUserStudentinfoByPhone($phone);
			 $wechat_info = Yii::$app->session->get('wechat_info');
			 if(empty($havePhone)){
				 $db = Yii::$app->db;
				 $transaction = $db->beginTransaction();
				try {
					//  add 表 user_student_base 一条记录
					$stuBase['phone']         = $phone;
					$stuBase['register_time'] = time();
					$db->createCommand()->insert('user_student_base', $stuBase)->execute();

					//  查询新增的学生id
					$userBase = UserStudentBase::find()
						->where(['phone' => $stuBase['phone']])
						->asArray()
						->one();
				//  add 表user_oauth_info 登录信息
                $userOauth['user_id']          = $userBase['id'];
                $userOauth['user_type']        = 1;   //   用户类型:1=学员
                $userOauth['oauth_type']       = 3;  //   认证类型:1=手机号
                $userOauth['oauth_id']         = $wechat_info['unionid'];
                $userOauth['oauth_credential'] = $wechat_info['openid'];
                $userOauth['login_time']       = time();
                $userOauth['login_ip']         = CommonHelper::getIP();

                $db->createCommand()->insert('user_oauth_info', $userOauth)->execute();

                $transaction->commit();
                // 成功跳转到完善信息页
                return $this->redirect(Yii::$app->urlManager->createUrl(['register/completion']))->send();

				} catch(\Exception $e) {
					$transaction->rollBack();
					return $this->redirect(Yii::$app->urlManager->createUrl(['register/index']))->send();
				}
			 }else{
				  //  add 表user_oauth_info 登录信息
				
                $userOauth['user_id']          = $havePhone['id'];
                $userOauth['user_type']        = 1;   //   用户类型:1=学员
                $userOauth['oauth_type']       = 3;  //   认证类型:1=手机号
                $userOauth['oauth_id']         = $wechat_info['unionid'];
                $userOauth['oauth_credential'] = $wechat_info['openid'];
                $userOauth['login_time']       = time();
                $userOauth['login_ip']         = CommonHelper::getIP();
				if(Yii::$app->db->createCommand()->insert('user_oauth_info', $userOauth)->execute()){
					 $whereCondition  = [
						'user_id'    => $havePhone['id'],
						'user_type'  => 1,
						'oauth_type' => 3,
					];
					$studentOauthObj = UserOauthInfo::find()->where($whereCondition)->one();
					$studentOauth = $studentOauthObj->toArray();
					CommonHelper::writeSessionOauth($havePhone, $studentOauth);
					if (Yii::$app->session->get('loginRefer')) {
						return $this->redirect(Yii::$app->session->get('loginRefer'))->send();
					}
					// 跳转到个人中心
					return $this->redirect(Yii::$app->urlManager->createUrl(['personal/info']))->send();
				}
			 }
		 }
		return $this->render('bindphone');
	}
觉得很赞
您需要登录后才可以评论。登录 | 立即注册