springboot 微信授權網頁登入操作流程
阿新 • • 發佈:2020-11-11
操作流程
假設你已經有自己的域名,因為微信公眾號和微信回撥都需要域名
先看看官方給的文件
根據官方文件,主要流程如下:
(1)引導使用者進入授權頁面同意授權,獲取code
(2)通過code換取網頁授權access_token(與基礎支援中的access_token不同)
(3)重新整理access_token(如果有需要)
(3)通過網頁授權access_token和openid獲取使用者基本資訊
提示:以下是本篇文章正文內容,下面案例可供參考
編寫微信授權方法和獲取使用者資訊方法
二、使用步驟
獲取微信二維碼資訊
程式碼如下(示例):
/** * 公眾號微信登入授權 */ @RequestMapping("/wxLogin") public void wxLogin(HttpServletResponse response) throws IOException { //這個url的域名必須在公眾號中進行註冊驗證,這個地址是成功後的回撥地址 String backUrl = "http://7ca0c439f61c.ngrok.io/callback";//使用自己的域名 // 第一步:使用者同意授權,獲取code //請求地址 snsapi_base snsapi_userinfo String url = "https://open.weixin.qq.com/connect/oauth2/authorize" + "?appid=" + HttpClientUtil.APPID + "&redirect_uri=" + URLEncoder.encode(backUrl,"utf-8") + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect"; logger.info("forward重定向地址{" + url + "}"); //必須重定向,否則不能成功 response.sendRedirect(url); } 備註:在前端頁面直接載入url 就可以出現二維碼介面了。直接用的微信的頁面,也可以根據自己的愛好進行設計頁面 /** * 公眾號微信登入授權回撥函式 */ @RequestMapping("/callback") public UserLoginRes callback(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { UserLoginRes userLoginRes = new UserLoginRes(); try{ WXUserInfoReq weixinUserInfo = new WXUserInfoReq(); /*start 獲取微信使用者基本資訊*/ String code = req.getParameter("code"); //第二步:通過code換取網頁授權access_token String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + HttpClientUtil.APPID + "&secret=" + HttpClientUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code"; System.out.println(url); String result = HttpClientUtil.doGet(url); JSONObject jsonObject = JSON.parseObject(result); /* { "access_token":"ACCESS_TOKEN","expires_in":7200,"refresh_token":"REFRESH_TOKEN","openid":"OPENID","scope":"SCOPE" } */ String openid = jsonObject.getString("openid"); String access_token = jsonObject.getString("access_token"); //第三步驗證access_token是否失效; String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid; String resultInfo = HttpClientUtil.doGet(chickUrl); JSONObject chickuserInfo = JSON.parseObject(resultInfo); System.out.println(chickuserInfo.toString()); if (!"0".equals(chickuserInfo.getString("errcode"))) { String refreshInfo1 = HttpClientUtil.doGet(chickUrl); JSONObject refreshInfo = JSON.parseObject(refreshInfo1); /* { "access_token":"ACCESS_TOKEN","scope":"SCOPE" } */ access_token = refreshInfo.getString("access_token"); } // 第四步:拉取使用者資訊 String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN"; JSONObject userInfo = JSON.parseObject(HttpClientUtil.doGet(infoUrl)); /* { "openid":" OPENID","nickname": NICKNAME,"sex":"1","province":"PROVINCE" "city":"CITY","country":"COUNTRY","headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46","privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" } */ System.out.println(userInfo.getString("openid") + ":" + userInfo.getString("nickname") +":" + userInfo.getString("sex")); }catch (Exception e){ e.printStackTrace(); userLoginRes.setResult("NO"); userLoginRes.setRtnErrId("ERROR"); userLoginRes.setRtnErrMsg(e.getMessage()); } return userLoginRes; }
使用到的HttpClientUtil工具類
程式碼如下(示例):
public class HttpClientUtil { //appid、secret為自己公眾號平臺的appid和secret public static final String APPID="xxxxxxx"; public static final String APPSECRET ="xxxxxxx"; public static String doGet(String url,Map<String,String> param) { // 建立Httpclient物件 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; HttpGet httpGet = null; try { // 建立uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key,param.get(key)); } } URI uri = builder.build(); // 建立http GET請求 httpGet = new HttpGet(uri); httpGet.setHeader("Host","api.weixin.qq.com"); httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); httpGet.setHeader("Accept","text/html,application/xhtml+xml,*/*"); httpGet.setHeader("Accept-Encoding","gzip,deflate,br"); httpGet.setHeader("Connection","keep-alive"); httpGet.setHeader("Accept-Language","zh-CN"); httpGet.setHeader("Cache-Control","no-cache"); // 執行請求 response = httpclient.execute(httpGet); // 判斷返回狀態是否為200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(),"UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpGet.releaseConnection(); httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url,null); } public static String doPost(String url,String> param) { // 建立Httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 建立Http Post請求 HttpPost httpPost = new HttpPost(url); // 建立引數列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key,param.get(key))); } // 模擬表單 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(),"utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url,null); } public static String doPostJson(String url,String json) { // 建立Httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 建立Http Post請求 HttpPost httpPost = new HttpPost(url); // 建立請求內容 StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 執行http請求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(),"utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGetStr(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字串 try { // 建立遠端url連線物件 URL url = new URL(httpurl); // 通過遠端url連線物件開啟一個連線,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設定連線方式:get connection.setRequestMethod("GET"); // 設定連線主機伺服器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設定讀取遠端返回的資料時間:60000毫秒 connection.setReadTimeout(60000); //設定請求頭 connection.setRequestProperty("Host","api.weixin.qq.com"); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); connection.setRequestProperty("Accept",*/*"); connection.setRequestProperty("Accept-Encoding",br"); connection.setRequestProperty("Connection","keep-alive"); connection.setRequestProperty("Accept-Language","zh-CN"); connection.setRequestProperty("Cache-Control","no-cache"); // 傳送請求 connection.connect(); // 通過connection連線,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is,"UTF-8")); // 存放資料 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠端連線 } return result; } }
最後根據實際業務處理使用者登入
//3.根據uuid查詢使用者是否存在,如果存在直接登入。如果不存在則自動註冊,在登入 UserInfoModel userInfoByWechat = iUserDao.getUserInfoByWechat(userInfoStr.get("unionid").toString()); if (userInfoByWechat != null) { return ReturnMessage.success(0,"獲取成功",userInfoByWechat); } //4.資料庫新增使用者資訊 String username = userInfoStr.get("nickname").toString(); String unionid = userInfoStr.get("unionid").toString(); UserInfoBean userInfoBean = new UserInfoBean(); userInfoBean.setUuid(unionid); userInfoBean.setUsername(username); // 微信登入 userInfoBean.setStatus(2); iUserDao.insertUser(userInfoBean); //5.根據uuid查詢新註冊的使用者資訊 UserInfoModel userInfoModel= iUserDao.getUserInfoByWechat(unionid); if (userInfoModel == null) { return ReturnMessage.fail(400,"使用者新增失敗,請重新操作"); }
到此這篇關於springboot 微信授權網頁登入操作流程的文章就介紹到這了,更多相關springboot 微信授權登入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!