QQ互聯登錄- 前端爲 vue.js

1.設置個圖標點擊請求後臺,後臺通過相應參數生成URL返回給前臺,前臺在指定div打開url,用戶在QQ頁面登錄完成後會回調到剛剛返回的URL裏面的redirect_uri 中,設置個定時器1秒鐘去掃一次返回的信息,掃到相應的數據進行相應的處理

登錄頁面
<div class="dsflogin_1"><a class="icon-qq" href="#" @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> 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章