您好,登錄后才能下訂單哦!
原創聲明:本文轉來源本人另一博客【http://blog.csdn.net/liaohaojian/article/details/70175835】絕非他人處轉載
從接觸公眾號到現在,開發維護了2個公眾號,開發過程中遇到很多問題,現在把部分模塊功能在這備案一下,做個總結也希望能給其他人幫助
工欲善其事,必先利其器,先看看開發公眾號需要準備或了解什么
web開發工具:官方提供的開發工具,使用自己的微信號來調試微信網頁授權、調試、檢驗頁面的 JS-SDK 相關功能與權限,模擬大部分 SDK 的輸入和輸出。下載地址:web開發工具下載
開發文檔:https://mp.weixin.qq.com/wiki
登錄微信測試公眾號,獲取公眾號的appID、appsecret,登錄地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login (一般測試開發階段,都不拿正式公眾號測試,因為存在風險并且你調試時不用擔心影響到正式公眾號的正常使用,而且有些接口在正式公眾號上比較嚴格,而在測試公眾號上可以放開,如模板信息)
下面進入正題,實現微信網頁授權,獲取微信信息,主要用于以微信帳號作為用戶登錄,如果你只是需要綁定微信,就可以不用授權,直接請求獲取微信OpenId(對當前公眾號唯一),進行用戶綁定(在下面代碼時是寫明如何實現),該功能可在開發文檔:微信網頁開發-》微信網頁授權里查看詳細信息,下面正式開始。
進入測試公眾號,在體驗接口權限表中找到網頁帳號,右側添加自己的域名,測試公眾號可填寫本地IP,如你是正式公眾號只能填寫自己的域名,如果未填寫,當進行接口調用時,會提示:redirect_uri參數錯誤!如果還有其他不了解的配置,可以在開發文檔里查看詳信息,
1).調用微信接口返回的參數都是JSON格式,封裝個Http請求方法
public class WeixinUtil { /** * 發起https請求并獲取結果 * @param requestUrl 請求地址 * @param requestMethod 請求方式(GET、POST) * @param outputStr 提交的數據 * @return JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 創建SSLContext對象,并使用我們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對象中得到SSLSocketFactory對象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 設置請求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 當有數據需要提交時 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意編碼格式,防止中文亂碼 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 將返回的輸入流轉換成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 釋放資源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } }
2).下面展示訪問個人中心時,進行用戶授權
/** * 個人中心 * @param request * @param response * @return */ @RequestMapping("/gotoPeopleIndex") public String gotoPeopleIndex(HttpServletRequest request,HttpServletResponse response){ //判斷是否授權過,授權通過時,會保存session“WeixinUserInfo”,這樣下次訪問時,如果WeixinUserInfo存在,說明已經授權過,用戶信息已經存在 WeixinUserInfo WeixinUserInfo = (WeixinUserInfo) session.getAttribute("WeixinUserInfo"); if(WeixinUserInfo==null){//沒有授權過,跳轉授權頁面,如果你不需要授權,則scope為snsapi_base,這是不會彈出授權頁面 String url = "https://open.weixin.qq.com/connect/oauth3/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfo/gotoPeopleIndex&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; return "redirect:"+url; }else{ return "weixin/customer/userInfo"; } } /** * 微信網頁授權獲得微信詳情 * @param code * @param state * @param view 授權后調整的視圖 * @param request * @param appid 公眾號appid * @param appsecret 公眾號appsecret * @param websiteAndProject 請求地址跟工程名,如我當前的為http://192.168.2.113/seafood * @param response * @throws ServletException * @throws IOException */ @RequestMapping("/getOpenInfo/{view}") public void getOpenInfo(@RequestParam("code") String code,@RequestParam("state") String state,@PathVariable("view") String view,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ // 用戶同意授權 if (!"authdeny".equals(code)) { //獲取OpenId OpenIdResult open = WeixinUtil.getOpenId(request, code, TimedTask.appid, TimedTask.appsecret); //檢驗授權憑證(access_token)是否有效 int result = WeixinUtil.checkAccessToken(open.getAccess_token(), open.getOpenid()); if(0 != result){ open = WeixinUtil.getNewAccess_Token(open,open.getRefresh_token(),TimedTask.appid); } // 網頁授權接口訪問憑證 String accessToken = open.getAccess_token(); String openId = open.getOpenid(); //獲取微信用戶詳細信息,如果你不需要授權,可跳過該步驟,直接以微信的OpenId,查找是否已經綁定,沒有跳轉到綁定界面 WeixinUserInfo user = WeixinUtil.getWeixinUserInfo(accessToken, openId); Customer customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId()); if(customer!=null){ if(customer.getAccountStatus()==2){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"); } catch (IOException e) { e.printStackTrace(); } return; } customer.setHeadPhoto(user.getHeadImgUrl()); }else{ Customer newuser = new Customer(); newuser.setCustomerWeixinId(openId); newuser.setCustomerWNickname(user.getNickname()); newuser.setSex(user.getSex()); //綁定 result = weixinFirstServer.addCustomerInfo(newuser); if(result<=0){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp"); } catch (IOException e) { e.printStackTrace(); } }else{ customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId()); if(customer.getAccountStatus()==2){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"); } catch (IOException e) { e.printStackTrace(); } return; } } } session.setAttribute("customerInfo", customer); session.setAttribute("WeixinUserInfo", user); request.setAttribute("state", state); response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixinF/"+view); } catch (IOException e) { e.printStackTrace(); } }else{ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp"); } catch (IOException e) { e.printStackTrace(); } } }
微信工具類代碼:
public class WeixinUtil { public final static String getOpen_id_url = "https://api.weixin.qq.com/sns/oauth3/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; /** * 檢驗授權憑證(access_token)是否有效 * @param accessToken 憑證 * @param openid id * @return */ public static int checkAccessToken(String accessToken, String openid) { String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid; JSONObject jsonObject = httpRequest(requestUrl, "GET", null); int result = 1; // 如果請求成功 if (null != jsonObject) { try { result = jsonObject.getInt("errcode"); } catch (JSONException e) { accessToken = null; // 獲取token失敗 log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } /** * 用戶授權,使用refresh_token刷新access_token * @return */ public static OpenIdResult getNewAccess_Token(OpenIdResult open,String refresh_token,String openId) { String requestUrl = getNewAccess_token.replace("REFRESH_TOKEN", refresh_token).replace("APPID", openId); JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // 如果請求成功 if (null != jsonObject) { try { open.setAccess_token(jsonObject.getString("access_token")); } catch (JSONException e) { // 獲取token失敗 log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return open; } /** * 獲得用戶基本信息 * @param request * @param code * @param appid * @param appsecret * @return */ public static OpenIdResult getOpenId(HttpServletRequest request, String code,String appid, String appsecret) { String requestURI = request.getRequestURI(); String param = request.getQueryString(); if(param!=null){ requestURI = requestURI+"?"+param; } String url = getOpen_id_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code); JSONObject jsonObject = httpRequest(url, "POST", null); OpenIdResult result = new OpenIdResult(); if (null != jsonObject) { Object obj = jsonObject.get("errcode"); if (obj == null) { result.setAccess_token(jsonObject.getString("access_token")); result.setExpires_in(jsonObject.getString("expires_in")); result.setOpenid(jsonObject.getString("openid")); result.setRefresh_token(jsonObject.getString("refresh_token")); result.setScope(jsonObject.getString("scope")); }else{ System.out.println("獲取openId回執:"+jsonObject.toString()+"訪問路徑:"+requestURI); log.error("訪問路徑:"+requestURI); log.error("獲取openId失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } /** * 通過網頁授權獲取用戶信息 * @param accessToken 網頁授權接口調用憑證 * @param openId 用戶標識 * @return WeixinUserInfo */ public static WeixinUserInfo getWeixinUserInfo(String accessToken, String openId) { WeixinUserInfo user = null; // 拼接請求地址 String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"; requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId); // 通過網頁授權獲取用戶信息 JSONObject jsonObject = httpRequest(requestUrl, "GET", null); if (null != jsonObject) { try { user = new WeixinUserInfo(); // 用戶的標識 user.setOpenId(jsonObject.getString("openid")); // 昵稱 user.setNickname(jsonObject.getString("nickname")); // 性別(1是男性,2是女性,0是未知) user.setSex(jsonObject.getInt("sex")); // 用戶所在國家 user.setCountry(jsonObject.getString("country")); // 用戶所在省份 user.setProvince(jsonObject.getString("province")); // 用戶所在城市 user.setCity(jsonObject.getString("city")); // 用戶頭像 user.setHeadImgUrl(jsonObject.getString("headimgurl")); // 用戶特權信息 user.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class)); } catch (Exception e) { user = null; int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); log.error("獲取用戶信息失敗 errcode:{} errmsg:{},reqUrl{}", errorCode, errorMsg); } } return user; } }
下面展示,當用戶session失效時,自動登錄的代碼,這時是不需要授權的
@RequestMapping("/gotoGoodsView") public String gotoGoodsView(@RequestParam(value="longitude",defaultValue="",required=false) String longitude,@RequestParam(value="latitude",defaultValue="",required=false) String latitude){ String param = request.getQueryString(); String url = request.getServletPath(); if(param!=null){ url = url+"?"+param.replaceAll("&","-");//如果不把&替換成別的,當重新登錄成功后調整會參數丟失 } Customer customerInfo = (Customer) session.getAttribute("customerInfo"); if(customerInfo==null){//session失效,跳轉到獲取微信詳情頁面(授權) return "redirect:/weixinF/getCode?view="+TimedTask.websiteAndProject+"/weixinF/autoLogin&view2="+TimedTask.websiteAndProject+url; } return "/weixin/customer/goodsList"; } @RequestMapping("/getCode") public void getCode(HttpServletResponse response){ String view = request.getParameter("view");//獲取openId的路徑 String view2 = request.getParameter("view2");//獲取openId成功后跳轉的路徑 String redirect_url = ""; try { redirect_url = URLEncoder.encode(view,"UTF-8"); if(view2!=null && !"".equals(view2)){ view2 = view2.replaceAll("-","&"); redirect_url = redirect_url +"?redirect_url="+ URLEncoder.encode(URLEncoder.encode(view2,"UTF-8"),"UTF-8"); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String url = WeixinUtil.getCode_url.replace("APPID",TimedTask.appid).replace("REDIRECT_URI",redirect_url); response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } } /** * 自動登錄并跳轉 * @param code * @param appid 公眾號appid * @param appsecret 公眾號appsecret * @param websiteAndProject 請求地址跟工程名,如我當前的為http://192.168.2.113/seafood * @param url 自動登錄后跳轉路徑 * @return */ @RequestMapping("/autoLogin") public String autoLogin(HttpServletResponse response,@RequestParam(value="code",defaultValue="") String code,@RequestParam(value="redirect_url",defaultValue="") String url){ OpenIdResult open = WeixinUtil.getOpenId(request,code,TimedTask.appid,TimedTask.appsecret);//根據Code獲取OpenId //根據OpenId查找是否有該客戶,沒有進行綁定 Customer customerInfo = weixinFirstServer.getCustomerDetailByOpenId(open.getOpenid()); if(customerInfo!=null){ if(customerInfo.getAccountStatus()==2){//用戶賬戶是否正常 return "redirect:"+TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"; } session.setAttribute("customerInfo", customerInfo);//把用戶信息存在session中 response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } return null; }else{ url= url.replaceAll("&","-"); url = url.replace(TimedTask.websiteAndProject,""); String redirectUrl = "https://open.weixin.qq.com/connect/oauth3/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfoRedirectAction?actionName="+url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(redirectUrl); } catch (IOException e) { e.printStackTrace(); } return null; } }
到此,微信網頁授權認證,與session失效自動登錄已經完成,如果有問題歡迎在評論區指出
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。