拾人牙慧篇之———QQ微信的第三方登录实现
一、寫在前面
關(guān)于qq微信登錄的原理之流我就不一一贅述了,對應(yīng)的官網(wǎng)都有,在這里主要是展示我是怎么實現(xiàn)出來的,看了好幾個博客,有的是直接復(fù)制官網(wǎng)的,有的不知道為什么實現(xiàn)不了。我只能保證我的這個是我實現(xiàn)后才貼出來的,本文有看不懂的地方請結(jié)合官網(wǎng)看。(話說我感覺我寫博客廢話好多)
二、準備工作
通過以下官網(wǎng)獲得相應(yīng)AppID和AppSecret以及對應(yīng)的回調(diào)地址。
QQ登錄官網(wǎng):https://connect.qq.com
微信登錄官網(wǎng):https://open.weixin.qq.com
三、登錄實現(xiàn)第三方
3.1、QQ授權(quán)登錄實現(xiàn)
這里的實現(xiàn)主要用JS_SDK來實現(xiàn),通過這種實現(xiàn)回調(diào)地址基本沒有什么用,區(qū)別于這種實現(xiàn)方式:如何在自己的網(wǎng)站上實現(xiàn)QQ授權(quán)登錄?。步驟就不一一說了,直接上代碼(紅色部分為qq授權(quán)相關(guān)的,里面的appid和回調(diào)地址改成自己申請時候的既可)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path = request.getContextPath() ;%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="UTF-8"> <title>登錄頁</title> <link href="<%=path%>/resource/css/public.css" rel="stylesheet" type="text/css" /> <link href="<%=path%>/resource/css/index.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<%=path%>/resource/js/tools/jquery-1.8.2.min.js"></script> <script type="text/javascript" src="<%=path%>/resource/js/tools/base.js"></script> <script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" data-appid="1013XXXXX" data-redirecturi="http://www.xxxxxx.com/qqlogincheck.jsp" charset="utf-8"> </script> <script type="text/javascript"> var PATH ='<%=path%>'; var FROM='${from}'; jQuery(function(){loginEnterCheck(); }); function getOs(){var OsObject = "";if (navigator.userAgent.indexOf("MSIE") > 0) {return "MSIE";}if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {return "Firefox";}if (isSafari = navigator.userAgent.indexOf("Safari") > 0) {return "Safari";}if (isCamino = navigator.userAgent.indexOf("Camino") > 0) {return "Camino";}if (isMozilla = navigator.userAgent.indexOf("Gecko/") > 0) {return "Gecko";} }//回車鍵登陸,支持火狐和IE瀏覽器; function loginEnterCheck(){//獲取當前瀏覽器;var browser = getOs();if(browser=="Firefox"){//判斷IE還是火狐瀏覽器;$("html").die().live("keydown",function(event){ if(event.keyCode==13){ //調(diào)用登陸方法;$(".J_login_btn").click(); } }); }else if(browser=="" || browser=="MSIE"){document.onkeydown=function(){if(event.keyCode==13||event.which==13){ $(".J_login_btn").click();}}}else{if(event.keyCode==13||event.which==13){ $(".J_login_btn").click();}} }function getInfo() {if(QC.Login.check()){QC.api("get_user_info").success(function(s){//成功回調(diào)QC.Login.getMe(function(openId, accessToken){var _data={loginName:s.data.nickname,openId:openId,otype:1,token:accessToken};//console.log(_data);$.ajax({url:PATH+"/security/qqlogin.do",type:"POST",data:_data,dataType:'json',success:function(result) {if(result.code==200){ //登錄成功 window.location.href=PATH+'/';}else{if(result.code==101){$("#openId").val(result.openId);console.info(result);$("#loginName_qw").val(result.loginName); var fm=document.getElementById("qqcheckForm"); // fm.action="";fm.submit(); }}}});})}).error(function(f){//失敗回調(diào)alert("獲取用戶信息失敗!登錄失敗!");location.href = "/security/toLoginPage.do";}).complete(function(c){//完成請求回調(diào)//alert("獲取用戶信息完成!");});}else{alert("請先登錄qq!");location.href = "/security/toLoginPage.do";} }function qqlogin(){QC.Login({}, function (reqData, opts) {//登錄成功getInfo();}, function (opts) {alert('注銷成功');});QC.Login.showPopup({appId:"10139XXXX",redirectURI:"http://www.xxxxxx.com/qqlogincheck.jsp"}); }</script><script type="text/javascript" src="<%=path%>/resource/js/login.js"></script> </head> <body οnkeydοwn="loginEnterCheck();"><form method="post" action="<%=path%>/security/toQwRegisterPage.do" id="qqcheckForm"><input type="hidden" id="openId" name="openId"><input type="hidden" id="loginName_qw" name="loginName_qw"></form> <div class="m_header"><div class='m_header_logo fix m_setWidth'><a href='http://www.xxxxxx.com' class='m_logo'><img src='<%=path%>/resource/images/logo.png' /></a><span class='welcome_title'>歡迎登錄</span></div> </div> <div class="m_login_wrapper"><div class='m_login m_setWidth fix'><div class='m_login_from'><div class='m_login_box'><p class='m_login_title'>西瑪會員</p><div class='m_login_input fix'><i class='m_login_user'></i><input name="loginName" type='text' placeholder='用戶名' class='m_input J_user'/></div><div class='m_login_input fix'><i class='m_login_lock'></i><input name="password" type='password' placeholder='密碼' class='m_input J_password'/></div><div class='m_login_handle fix'><span class='m_square_box c_switch checked'><span class='m_square'></span><i class='m_square_text'>自動登錄</i></span><a href='<%=path%>/security/findPassword.do' class='m_forget_password'>忘記密碼</a></div><button class='c_btn c_btn_green J_login_btn'>登錄</button><div class='m_login_handle fix'><a >其他登錄方式></a></div><div class='m_header_title_left '> <a style="margin-right: 10px;" οnclick="qqlogin()" ><img src='<%=path%>/resource/images/login/btn_qzone.png' alt="QQ授權(quán)登錄 " ></a> <a style="margin-right: 10px;" href="http://open.weixin.qq.com/connect/qrconnect?appid=wx1fbfXXXXXX&redirect_uri=http%3A%2F%2Fwww.xxxxxx.com%2Fsecurity%2FgetWebchatCode.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect"><img src='<%=path%>/resource/images/login/btn_weixin.png' alt="微信授權(quán)登錄 "></a></div><div class='m_to_register'><a href='<%=path%>/security/toRegisterPage.do'>免費注冊></a></div></div></div></div> </div> <jsp:include page="../public/buttom.jsp" flush="true" /> </body> </html>
這里用到的是?QC.Login.showPopup,期間遇到了showPopup?這種不能回調(diào)的情況,參考了:QC.Login.showPopup可有回調(diào)??。
qq授權(quán)后臺處理思路:通過點擊qq登錄,登錄成功后回調(diào),在回調(diào)中通過?QC.api("get_user_info")獲取登錄后的信息,在后臺通過qq的openid來查詢數(shù)據(jù)庫,若是庫中有值,則直接進入登錄成功流程,若是沒有值則跳轉(zhuǎn)到手機號注冊流程。(回調(diào)地址里面基本為空)
3.2、微信授權(quán)登錄實現(xiàn)
上面代碼的藍色部分即為微信登錄的連接,相應(yīng)地方改成申請的既可.
這里有三個地方需要注意:
1、地址需要改成轉(zhuǎn)義后的,%3A%2F%2F就等于://這樣的形式。
2、若是前面微信開放平臺的是https,對應(yīng)的回調(diào)也是https。
3、這里寫的回調(diào)地址是http://www.xxxxxx.com/security/getWebchatCode.do,但是微信申請里寫http://www.xxxxxx.com既可。
下面看看微信登錄成功后的后臺處理代碼
?
/*** 微信登錄獲取code*/@RequestMapping(value = "/getWebchatCode.do")public ModelAndView getWebchatCode(HttpServletRequest request, HttpServletResponse response) {String code = request.getParameter("code");System.out.println("微信登錄獲取code=="+code);String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret=XXX&code="+code+"&grant_type=authorization_code";Map<String, Object> map = new HashMap<String, Object>();map.put("from", code);try { JSONObject jb = HttpUtils.httpRequest(url,"GET",null);System.out.println("通過code獲取token=="+jb.toString());String access_token= jb.getString("access_token"); JSONObject userinfo = HttpUtils.httpRequest("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+appid+"","GET",null);System.out.println("通過token獲取=="+userinfo.toString());String loginName= userinfo.getString("nickname");String openId=userinfo.getString("openid");Member member = memberService.selectOneByWeixinOpenId(openId);if (member != null ) {//通過qq唯一openID判斷該qq是否之前用過,同時判斷l(xiāng)oginName是否唯一member.setLastLoginTime(new Date());memberService.update(member);// 設(shè)置線程變量 CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_USER_ID, member.getId());CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_MEMBER, member);CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_MANAGE_SHOP_ID, member.getManageShopId());// 單點登錄CookieCookie cookie_sso = new Cookie(CurrentThreadContext.COOKIES_LOGIN_KEY, AESUtil.encrypt(loginName,PropertiesUtil.getInstance().getValue("security.cipher.key")));cookie_sso.setMaxAge(-1);cookie_sso.setDomain(PropertiesUtil.getInstance().getValue("security.root.domain"));cookie_sso.setPath("/");response.addCookie(cookie_sso);// 用戶CookieloginName = DESUtil.strEnc(loginName, PropertiesUtil.getInstance().getValue("security.cipher.key"), "","");String shopFlage = "";if (member.getManageShopId() != null) {Shop t = new Shop();t.setId(member.getManageShopId());Shop shop = shopApiService.selectOne(t);if (shop != null && shop.getStatus() != null&& shop.getStatus().equals(ShopConstant.SHOP_STATUS_3)) {shopFlage = member.getManageShopId().toString();}}Cookie cookie_memberinfo = new Cookie(CurrentThreadContext.COOKIES_MEMBERINFO,loginName + "|" + shopFlage + "|" + member.getId());cookie_memberinfo.setMaxAge(-1);cookie_memberinfo.setDomain(PropertiesUtil.getInstance().getValue("security.root.domain"));cookie_memberinfo.setPath("/");response.addCookie(cookie_memberinfo);map.put("code", "200");map.put("msg", "登錄成功");return new ModelAndView("redirect:/",map);} else {//qq授權(quán)的不存在,跳轉(zhuǎn)到輸入手機驗證碼的地方map.put("code", "101");Member membertemp = memberService.selectOneByLoginName(loginName);if(membertemp!=null){map.put("loginName", loginName+"_xima"+new Random().nextInt(1000));}else{map.put("loginName", loginName);}map.put("wqType", "weixin");map.put("openId", openId);/* map.put("msg", "用戶名或密碼不正確");*/return new ModelAndView("security/qwRegister",map);}} catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();}return new ModelAndView("security/login",map);}
主要是幾次握手過程。
四、總結(jié)
qq微信的第三方登錄按照官方文檔一步一步實習還是比較容易的,有什么問題可以交流交流。
以上用到的連接若是對該作者造成影響的,可以聯(lián)系刪掉。
轉(zhuǎn)載于:https://www.cnblogs.com/minzhousblogs/p/6872510.html
總結(jié)
以上是生活随笔為你收集整理的拾人牙慧篇之———QQ微信的第三方登录实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 报告王爷王妃是只猫有电视剧版吗在哪能看
- 下一篇: 几个不错的开源的.net界面控件