微信掃碼登錄(JAVA)

  在web端用到weChat掃碼登陸,在手機掃碼登錄成功後,跳轉到相應的界面。javascript

一、第一步請求code

  調用接口:https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect;html

  參數信息說明:前端

參數 是否必須 說明
appid 應用惟一標識
redirect_uri 請使用urlEncode對連接進行處理
response_type 填code
scope 應用受權做用域,擁有多個做用域用逗號(,)分隔,網頁應用目前僅填寫snsapi_login即
state 用於保持請求和回調的狀態,受權請求後原樣帶回給第三方。該參數可用於防止csrf攻擊(跨站請求僞造攻擊),建議第三方帶上該參數,可設置爲簡單的隨機數加session進行校驗
前端代碼信息以下(經過後臺controller層返回url,來顯示二維碼):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信掃碼登陸</title>
<script type="text/javascript" src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<script type="text/javascript">
$().ready(function() {
  $.ajax({
  url: "${base}/weChat",
type: "post",
dataType: "json",
success: function(data) {
  var div = document.getElementById("login_container");
div.innerHTML = "";
var iframe = document.createElement("iframe");
var url = data.url;
var redirect_uri = data.redirect_uri;
var code = url+encodeURIComponent(redirect_uri);
iframe.setAttribute("src",code);
iframe.style.width = "100%";
iframe.style.height = "100%";
div.appendChild(iframe);
        }
      });
    });
</script>
</head>
<body>
  <!--內容-->
  <div class="content">
    <div id="login_container" class="login_container"></div>
  </div>
</body>
</html>

  後臺代碼(controller層獲取code的url信息)java

    /**
     * 微信掃碼登陸二維碼顯示
     */
    @PostMapping("/weChat")
    public ResponseEntity weChat(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(5);
        String state = DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30));
        request.getSession().setAttribute(STATE_ATTRIBUTE_NAME, state);
        String redirect_uri = "http://hbbdjw.nat300.top/social_user_login/get_sign_in_weixinQrCodeLoginPlugin";//紅色部分改成本身的redirect_url,藍色部分改成本身的掃碼後須要跳轉的頁面
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=【本身的appid】&scope=snsapi_login&response_type=code&state=" + state + "&redirect_uri=";
        map.put("url", url);
        map.put("redirect_uri", redirect_uri);
        return ResponseEntity.ok(map);
    }

二、第二步:經過code獲取access_token

  登錄後處理(判斷access_token是否爲null,不爲空,則驗證成功,不然失敗)web

  /**
     * 登陸後處理
     */
    @GetMapping({"/get_sign_in_weixinQrCodeLoginPlugin"})
    public ModelAndView getSignin(@PathVariable String loginPluginId, @PathVariable(required = false) String extra, HttpServletRequest request, HttpServletResponse response, ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
     String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=【本身的appid】&secret=【本身的secret】&code=" + code + "&grant_type=authorization_code";
     // 獲取網頁受權憑證
     JSONObject jsonObject = JSONObject.fromObject(HttpUtil.Get(getTokenUrl));//get方法是本身寫的
     if (jsonObject != null) {
       String openId = jsonObject.getString("access_token");
       String accessToken = jsonObject.getString("openid");
       String uniqueId = jsonObject.getString("openid");
     }
SocialUser socialUser = socialUserService.find(uniqueId); //從數據庫中查找用戶,
if (socialUser != null) {
//當數據庫中不存在該user的時候,事件處理
} else {
//當數據庫中存在該user的時候,事件處理(通常狀況下新建user信息數據在數據庫)
}
return modelAndView;
}

  GET請求方法ajax

  /**
      * 向指定URL發送GET方法的請求
      *
      * @param url   發送請求的URL
      * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
      * @return URL 所表明遠程資源的響應結果
      */
     public static String Get(String url) {
         int connectionTimeOut=HTTP_CONNECTION_TIMEOUT,  readTimeOut =HTTP_READ_TIMEOUT;
         String result = "";
         BufferedReader in = null;
         String urlNameString = url;
         try {
             logger.info("請求url+參數:" + urlNameString);
             URL realUrl = new URL(urlNameString);
             // 打開和URL之間的鏈接
             URLConnection connection = realUrl.openConnection();
             // 設置通用的請求屬性
             connection.setRequestProperty("accept", "*/*");
             connection.setRequestProperty("connection", "Keep-Alive");
             connection.setConnectTimeout(connectionTimeOut);
             connection.setReadTimeout(readTimeOut);
             // 創建實際的鏈接
             connection.connect();
             // 獲取全部響應頭字段
             // 定義 BufferedReader輸入流來讀取URL的響應
             in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
             String line;
             while ((line = in.readLine()) != null) {
                 result += line;
             }
         } catch (Exception e) {
             logger.error("發送GET請求出現異常!url: " + urlNameString + ", " + e);
         }
         // 使用finally塊來關閉輸入流
         finally {
             try {
                 if (in != null) {
                     in.close();
                 }
             } catch (Exception e2) {
                 logger.error("close exception", e2);
             }
         }
         return result;
     }

到此結束。數據庫

相關文章
相關標籤/搜索