微信授權登錄實現


微信授權登錄。和其它授權類似,需要去官方渠道注冊開發者賬號,微信授權登錄需要到微信公眾平台申請.

假設獲取到了公眾平台appid。

和掃碼類似,進入微信指定的一個鏈接。

但是授權登錄是先直接訪問微信指定的頁面。(掃碼是從自己頁面跳轉到指定微信鏈接,再回調自己頁面。授權是直接從指定的鏈接地址跳轉回自己指定頁面

先上代碼:

var param=location.href.split("?")[1];
//wechat
var url=encodeURIComponent("http://h5.laikanxing.com/h5-crowd/html/wechat.html?"+param);
    window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadc302736fea5abf&redirect_uri="+
        url+"&response_type=code&scope=snsapi_userinfo&"+param+"#wechat_redirect";

param:需要帶回的參數。

url:回調頁面。(公眾平台注冊的域

以上步驟可以從前台跳轉,可以從后端進行轉發。看個人業務需求。

當用戶確認授權登錄以后,微信從定向到指定回調頁面,並且url后拼接了換取用戶信息的code。

拿到code以后,和網頁掃碼登錄一樣,進行幾步交換(必須后台進行)。

后台Java代碼:

/**
     * activity
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/get/h5/wechat/{code}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public LoginResultJSON getWechatUserInfo(@PathVariable("code") String code) {
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxadc302736fea5abcf&secret=11241d710a5726a57e6ebd2dfd98b0bf&code="+code+"&grant_type=authorization_code";
        String result=RequestUtil.get(url);
        JSONObject jsonObject=new JSONObject(result);
        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");
        url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        result=RequestUtil.get(url);
        jsonObject=new JSONObject(result);
        ThirdPartyUserLoginInfoJSON json=new ThirdPartyUserLoginInfoJSON();
        json.setDeviceId(null);
        json.setDeviceSystem(null);
        json.setHeadUrl(jsonObject.getString("headimgurl"));
        json.setNickname(jsonObject.getString("nickname"));
        json.setSourceType(2);
        json.setUniqId(jsonObject.getString("openid"));
        return userService.thirdPartyLogin(json);
    }

具體換取解釋,請看上篇。第三方登錄集合


免責聲明!

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



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