QQ微信的第三方登錄實現


參考資料:

https://www.cnblogs.com/v-weiwang/p/5732423.html
[qq登錄](https://wiki.connect.qq.com/%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7openid_oauth2-0)

http://www.imooc.com/wenda/detail/381845

 

導航地址解碼 如 http://www.baidu.com ==> http%3A%2F%2Fwww.baidu.con
[](http://www.jsons.cn/urlencode/)

代碼拷貝 https://www.cnblogs.com/minzhousblogs/p/6872510.html?utm_source=itdadao&utm_medium=referral (多說一句,以后遇到好的文章最好自己拷貝一下,有可能呢你所參考的文章直接沒了)

 

這里的實現主要用JS_SDK來實現,通過這種實現回調地址基本沒有什么用,區別於這種實現方式:如何在自己的網站上實現QQ授權登錄?。步驟就不一一說了,直接上代碼(紅色部分為qq授權相關的,里面的appid和回調地址改成自己申請時候的既可)

<%@ 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){   
                    //調用登陸方法;
                    $(".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){//成功回調
                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){//失敗回調
                alert("獲取用戶信息失敗!登錄失敗!");
                location.href = "/security/toLoginPage.do";
            })
            .complete(function(c){//完成請求回調
            //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 onkeydown="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;" onclick="qqlogin()" >
                    <img src='<%=path%>/resource/images/login/btn_qzone.png' alt="QQ授權登錄 " >
                    </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="微信授權登錄 ">
                    </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 這種不能回調的情況,參考了:QC.Login.showPopup可有回調? 

qq授權后台處理思路:通過點擊qq登錄,登錄成功后回調,在回調中通過 QC.api("get_user_info")獲取登錄后的信息,在后台通過qq的openid來查詢數據庫,若是庫中有值,則直接進入登錄成功流程,若是沒有值則跳轉到手機號注冊流程。(回調地址里面基本為空)

3.2、微信授權登錄實現

  上面代碼的藍色部分即為微信登錄的連接,相應地方改成申請的既可.

  這里有三個地方需要注意:

  1、地址需要改成轉義后的,%3A%2F%2F就等於://這樣的形式。

  2、若是前面微信開放平台的是https,對應的回調也是https。

  3、這里寫的回調地址是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是否之前用過,同時判斷loginName是否唯一
                    member.setLastLoginTime(new Date());
                    memberService.update(member);
                    // 設置線程變量
                    CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_USER_ID, member.getId());
                    CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_MEMBER, member);
                    CurrentThreadContext.setValue(CurrentThreadContext.CURRENT_MANAGE_SHOP_ID, member.getManageShopId());
                    // 單點登錄Cookie
                    Cookie 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);

                    // 用戶Cookie
                    loginName = 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授權的不存在,跳轉到輸入手機驗證碼的地方
                    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);
    }

主要是幾次握手過程。

四、總結

   qq微信的第三方登錄按照官方文檔一步一步實習還是比較容易的,有什么問題可以交流交流。

    以上用到的連接若是對該作者造成影響的,可以聯系刪掉。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM