天天看点

QQ互联登录- 前端为 vue.js

1.设置个图标点击请求后台,后台通过相应参数生成URL返回给前台,前台在指定div打开url,用户在QQ页面登录完成后会回调到刚刚返回的URL里面的redirect_uri 中,设置个定时器1秒钟去扫一次返回的信息,扫到相应的数据进行相应的处理

QQ互联登录- 前端为 vue.js
QQ互联登录- 前端为 vue.js
登录页面
<div class="dsflogin_1"><a class="icon-qq" href="#" target="_blank" rel="external nofollow"  @click.stop.prevent="login_qq" title="QQ登录"></a></div>
//定义参数
App._$declare({ 
			ewmDiv_qq : false, 
			qq_url : '', 
			setinterval_qq : null
});
 

方法
//qq登录
			login_qq : function(){
				var _this = this; 
				if(_this.setinterval_qq != null){//有定时器先关闭
				 	clearInterval(_this.setinterval_qq);
				}
				App._$get('${ctxPath}/api/qq-login.json?_type=requestQQ&_batch=true',null,null,null,null,
					function(data){  
						_this.ewmDiv_qq = true;
						_this.qq_url = data.url;//回传url
						//监听返回参数 
						_this.setinterval_qq = setInterval(function(){ 
							if(_this.ewmDiv_qq == false){//关闭二维码窗口
								clearInterval(setinterval_qq) 
							}
							var qqStatus = $("#qqStatus",$('#ewmDiv_qq iframe')[0].contentDocument).val();//$('#ewmDiv_qq iframe')[0].contentDocument 在哪里获得
							if(qqStatus != null){ 
								clearInterval(_this.setinterval_qq) 
								if(qqStatus == 200){//成功登录
									var login_jwt = $("#login_jwt",$('#ewmDiv_qq iframe')[0].contentDocument).val();
									var login_t = $("#login_t",$('#ewmDiv_qq iframe')[0].contentDocument).val();
									window.localStorage['_authorization'] = login_jwt;
									window.localStorage['_t'] = login_t;
									setTimeout(function(){
										//登录成功,跳转到指定页面 
										window.location.href = '${ctxPath}/member/';
									},100)
								}else if(qqStatus == 201){//未注册 
									_this.ewmDiv_qq = false;
									_this.registerDiv = true;//注册
									_this.memberForm.dsfType = 2;//登录类型
								}
							}
						},1000);  
					},function(err){
					_this.$message.error("qq登录失败");
				});
			},


 <!--QQ登录页面 -->
    <el-dialog id="ewmDiv_qq"  style="text-align: center;" :visible.sync="ewmDiv_qq" width="1000px">  
    	<iframe id="iframe_qq" :src="qq_url" style="width: 800px;height: 400px;border : none;" v-if="ewmDiv_qq"> 
    	</iframe>
    	<br>
    	<el-button @click="ewmDiv_qq = false">关&nbsp;闭</el-button>
	</el-dialog>  
           

1.后台代码

// 应用唯一标识 appid 申请的appid 
    private String appid = "10150967905";   

/**
	 * 
	 * @category 回调地址
	 * @author hjj
	 * @date 2018年10月13日
	 * @return
	 * @return String
	 * @throws UnsupportedEncodingException 
	 */
	public static String queryRelationCallbackUri(HttpServletRequest request, String upath) throws UnsupportedEncodingException{
		String path = request.getContextPath();
		String ServerName = request.getServerName(); 
		//String ServerName = "1608e55a.all123.net";//测试ip 不加ip
		String basePath = request.getScheme() + "://" + ServerName + path ; 
		basePath += upath;
		basePath = URLEncoder.encode(basePath, "UTF-8");
		return basePath;
	}
    
    /**
     * 
     * @category 登录请求微信操作 (步骤1)
     * @author hjj
     * @date 2018年10月13日
     * @return void
     */
	public void _$indexBatchRequestQQ(){///we-chat-login
		Resp result = initResult();
		try {
			String redirect_uri = queryRelationCallbackUri(request, "/qq-login");
			String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
					+appid+"&redirect_uri="+redirect_uri+"&state="+"requestQQ";
			result.dataMap("url", url);
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
           

2.回调地址及处理,判断用户是否注册等相关信息返回给页面qq-login.tpl

// 应用唯一标识
    private String appid = "10150967905"; 
    
    // 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
    private String APP_KEY = "00af379f60d2248ab7201b80bdf215de05"; 
    
    private Integer status = null;//状态
    
    private String statusTitle = "";//文字说明
    
    private String access_token = "";
    
  
	
    /**
	 * 
	 * @category (步骤1)回调地址   获得用户openid并处理数据
	 * @author hjj
	 * @date 2018年10月31日
	 * @return void
	 */
	@Override
	public String execute(){
		String code = param("code"); 
		String state = param("state"); 
		String msg = param("msg",null); //错误时会返回
		Resp result = initResult();  
		if(msg == null){//异常信息为空
			try {
				JsonObject json = queryData();
				if(json != null ){//获得到用户openid信息
					String openid = json.get("openid").getAsString();
					Members members = memberService.queryUserDate(null,openid);
					if(members != null){//0 正常 1不正常 2为注册  
						App app = WebHelper.getApp(request);
						if(Constants.USER_STATUS_NORMAL.equals(members.getStatus())){//用户转态正常
							JsonObject userJson = sessionService.thirdPartyLogin(members, null, response, request, app);
							attr("jwt",userJson.get("jwt").getAsString());
							attr("_t",userJson.get("_t").getAsString());
							status = 200;
							statusTitle = "登录成功";
						}else{//状态异常
							status = -4;
							statusTitle = "用户状态异常";
						}
					}else{//未绑定账号
						//{"ret":0,"msg":"","is_lost":0,"nickname":"酒丿精","gender":"男","province":"广东","city":"广州","year":"1994","constellation":"","figureurl":"http://qzapp.qlogo.cn/qzapp/101509679/9471D2E4C63F087EBE8C0AB2B51FCFE3/30","figureurl_1":"http://qzapp.qlogo.cn/qzapp/101509679/9471D2E4C63F087EBE8C0AB2B51FCFE3/50","figureurl_2":"http://qzapp.qlogo.cn/qzapp/101509679/9471D2E4C63F087EBE8C0AB2B51FCFE3/100","figureurl_qq_1":"http://thirdqq.qlogo.cn/qqapp/101509679/9471D2E4C63F087EBE8C0AB2B51FCFE3/40","figureurl_qq_2":"http://thirdqq.qlogo.cn/qqapp/101509679/9471D2E4C63F087EBE8C0AB2B51FCFE3/100","is_yellow_vip":"0","vip":"0","yellow_vip_level":"0","level":"0","is_yellow_year_vip":"0"}
						JsonObject json2 = queryUserData(access_token, openid);
						
						if(json2.get("ret").getAsInt() != 0){//获得用户信息
							status = -5;
							statusTitle = json2.get("msg").getAsString();//返回信息
						}else{
							HttpSession session = request.getSession();
							json2.addProperty("openid", openid);//追加openid
							session.setAttribute(Constants.SESSION_USER_QQ, json2);//设置到Session中
							status = 201;
							statusTitle = "";//未绑定账号
						}
					}
				}
					
			} catch (Exception e) {
				e.printStackTrace();
				status = -999;
				statusTitle = "系统异常,请重新操作!";
			}
			
		}else{  
			status = -1;
			statusTitle = msg;
		}
		attr("status",status);
		attr("statusTitle",statusTitle);
		return SUCCESS;
	} 
	
	
	/**
	 * 
	 * @category 获得qq用户信息
	 * @author hjj
	 * @date 2018年10月17日
	 * @param ACCESS_TOKEN 调用凭证
	 * @param openid 普通用户的标识,对当前开发者帐号唯一
	 * @return void
	 * 
	 *  ret	返回码
		msg	如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。
		nickname	用户在QQ空间的昵称。
		figureurl	大小为30×30像素的QQ空间头像URL。
		figureurl_1	大小为50×50像素的QQ空间头像URL。
		figureurl_2	大小为100×100像素的QQ空间头像URL。
		figureurl_qq_1	大小为40×40像素的QQ头像URL。
		figureurl_qq_2	大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100x100的头像,但40x40像素则是一定会有。
		gender	性别。 如果获取不到则默认返回"男"
	 */
	public JsonObject queryUserData(String ACCESS_TOKEN, String openid){
		String url = "https://graph.qq.com/user/get_user_info?access_token="+ACCESS_TOKEN+"&oauth_consumer_key="+appid+"&openid="+openid;
		String fhz = UrlUitl.sendGet(url);  
		return JsonUtil.fromJson(fhz);
	}
	
	/**
	 * 
	 * @category qq返回字符串转对象json
	 * @author hjj
	 * @date 2018年11月1日
	 * @param str   access_token=4EA7D04DC15AB2AEE86F5B6812ADC0CB&expires_in=7776000&refresh_token=4CD647A8C4ECE3A362BEEB981AD0BD3F
	 * @return JsonObject
	 */
	public JsonObject dataToObject(String str){
		str = "{"+str.replaceAll("=", ":").replaceAll("&", ",")+"}";
		return JsonUtil.fromJson(str);
	}

	/**
	 * 
	 * @category 切割返回数据转JsonObject对象
	 * @author hjj
	 * @date 2018年11月1日
	 * @param str   callback( {"client_id":"101509679","openid":"D008664CA03401B781C7F96E015DE959"} );
	 * @return
	 * @return JsonObject
	 */
	public JsonObject dataToObject2(String str){
		str = str.split("\\(")[1].split("\\)")[0];
		return JsonUtil.fromJson(str);
	}
	
	
	/**
	 * 
	 * @category 登录回调获得用户  openid 信息
	 * @author hjj
	 * @date 2018年11月2日
	 * @return
	 * @throws UnsupportedEncodingException
	 * @return JsonObject
	 */
	public JsonObject queryData() throws UnsupportedEncodingException{
		String code = param("code"); 
		String state = param("state"); 
		String msg = param("msg",null); //错误时会返回
		JsonObject reJson = null;
		if(msg == null){//异常信息为空 
			String redirect_uri = UrlUitl.queryRelationCallbackUri(request, "/api/qq-login");
			String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id="+appid
					+"&client_secret="+APP_KEY+"&code="+code+"&redirect_uri="+redirect_uri;
			String fhz = UrlUitl.sendGet(url); 
			JsonObject json = dataToObject(fhz);
			if(json.get("msg") != null){
				status = -2;
				statusTitle = json.get("msg").toString();
			}else{//获得access_token  那这个去获得用户信息
				access_token = json.get("access_token").getAsString();
				url = "https://graph.qq.com/oauth2.0/me?access_token="+access_token;
				fhz = UrlUitl.sendGet(url); 
				json = dataToObject2(fhz);
				if(json.get("msg") != null){
					status = -3;
					statusTitle = json.get("msg").toString();
				}else{
					reJson = json;
				}
			}
		}else{  
			status = -1;
			statusTitle = msg;
		}
		return reJson;
	} 
           

3.qq-login.tpl  1中定时器不断扫面的数据

<div>
<input type="hidden" id="qqStatus" value="${status!}"/>
<input type="hidden" id="login_jwt" value="${jwt!}"/> 
<input type="hidden" id="login_t" value="${_t!}"/> 
<div style="text-align: center;margin-top: 100px;">
	<div class="thirdParty_1">
		<span class="thirdParty_1_1" style="font-size: 18px;">${statusTitle!}</span>
	</div> 
</div> 
</div>