您好,登錄后才能下訂單哦!
原創(chuàng)聲明:本文轉(zhuǎn)來源本人另一博客【http://blog.csdn.net/liaohaojian/article/details/70175835】絕非他人處轉(zhuǎn)載
從接觸公眾號到現(xiàn)在,開發(fā)維護了2個公眾號,開發(fā)過程中遇到很多問題,現(xiàn)在把部分模塊功能在這備案一下,做個總結(jié)也希望能給其他人幫助
工欲善其事,必先利其器,先看看開發(fā)公眾號需要準備或了解什么
web開發(fā)工具:官方提供的開發(fā)工具,使用自己的微信號來調(diào)試微信網(wǎng)頁授權(quán)、調(diào)試、檢驗頁面的 JS-SDK 相關(guān)功能與權(quán)限,模擬大部分 SDK 的輸入和輸出。下載地址:web開發(fā)工具下載
開發(fā)文檔:https://mp.weixin.qq.com/wiki
登錄微信測試公眾號,獲取公眾號的appID、appsecret,登錄地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login (一般測試開發(fā)階段,都不拿正式公眾號測試,因為存在風(fēng)險并且你調(diào)試時不用擔(dān)心影響到正式公眾號的正常使用,而且有些接口在正式公眾號上比較嚴格,而在測試公眾號上可以放開,如模板信息)
下面進入正題,實現(xiàn)微信網(wǎng)頁授權(quán),獲取微信信息,主要用于以微信帳號作為用戶登錄,如果你只是需要綁定微信,就可以不用授權(quán),直接請求獲取微信OpenId(對當(dāng)前公眾號唯一),進行用戶綁定(在下面代碼時是寫明如何實現(xiàn)),該功能可在開發(fā)文檔:微信網(wǎng)頁開發(fā)-》微信網(wǎng)頁授權(quán)里查看詳細信息,下面正式開始。
進入測試公眾號,在體驗接口權(quán)限表中找到網(wǎng)頁帳號,右側(cè)添加自己的域名,測試公眾號可填寫本地IP,如你是正式公眾號只能填寫自己的域名,如果未填寫,當(dāng)進行接口調(diào)用時,會提示:redirect_uri參數(shù)錯誤!如果還有其他不了解的配置,可以在開發(fā)文檔里查看詳信息,
1).調(diào)用微信接口返回的參數(shù)都是JSON格式,封裝個Http請求方法
public class WeixinUtil { /** * 發(fā)起https請求并獲取結(jié)果 * @param requestUrl 請求地址 * @param requestMethod 請求方式(GET、POST) * @param outputStr 提交的數(shù)據(jù) * @return JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 創(chuàng)建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); // 設(shè)置請求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 當(dāng)有數(shù)據(jù)需要提交時 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意編碼格式,防止中文亂碼 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 將返回的輸入流轉(zhuǎn)換成字符串 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).下面展示訪問個人中心時,進行用戶授權(quán)
/** * 個人中心 * @param request * @param response * @return */ @RequestMapping("/gotoPeopleIndex") public String gotoPeopleIndex(HttpServletRequest request,HttpServletResponse response){ //判斷是否授權(quán)過,授權(quán)通過時,會保存session“WeixinUserInfo”,這樣下次訪問時,如果WeixinUserInfo存在,說明已經(jīng)授權(quán)過,用戶信息已經(jīng)存在 WeixinUserInfo WeixinUserInfo = (WeixinUserInfo) session.getAttribute("WeixinUserInfo"); if(WeixinUserInfo==null){//沒有授權(quán)過,跳轉(zhuǎn)授權(quán)頁面,如果你不需要授權(quán),則scope為snsapi_base,這是不會彈出授權(quán)頁面 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"; } } /** * 微信網(wǎng)頁授權(quán)獲得微信詳情 * @param code * @param state * @param view 授權(quán)后調(diào)整的視圖 * @param request * @param appid 公眾號appid * @param appsecret 公眾號appsecret * @param websiteAndProject 請求地址跟工程名,如我當(dāng)前的為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{ // 用戶同意授權(quán) if (!"authdeny".equals(code)) { //獲取OpenId OpenIdResult open = WeixinUtil.getOpenId(request, code, TimedTask.appid, TimedTask.appsecret); //檢驗授權(quán)憑證(access_token)是否有效 int result = WeixinUtil.checkAccessToken(open.getAccess_token(), open.getOpenid()); if(0 != result){ open = WeixinUtil.getNewAccess_Token(open,open.getRefresh_token(),TimedTask.appid); } // 網(wǎng)頁授權(quán)接口訪問憑證 String accessToken = open.getAccess_token(); String openId = open.getOpenid(); //獲取微信用戶詳細信息,如果你不需要授權(quán),可跳過該步驟,直接以微信的OpenId,查找是否已經(jīng)綁定,沒有跳轉(zhuǎn)到綁定界面 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"; /** * 檢驗授權(quán)憑證(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; } /** * 用戶授權(quán),使用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回執(zhí):"+jsonObject.toString()+"訪問路徑:"+requestURI); log.error("訪問路徑:"+requestURI); log.error("獲取openId失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } /** * 通過網(wǎng)頁授權(quán)獲取用戶信息 * @param accessToken 網(wǎng)頁授權(quán)接口調(diào)用憑證 * @param openId 用戶標(biāo)識 * @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); // 通過網(wǎng)頁授權(quán)獲取用戶信息 JSONObject jsonObject = httpRequest(requestUrl, "GET", null); if (null != jsonObject) { try { user = new WeixinUserInfo(); // 用戶的標(biāo)識 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")); // 用戶特權(quán)信息 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; } }
下面展示,當(dāng)用戶session失效時,自動登錄的代碼,這時是不需要授權(quán)的
@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("&","-");//如果不把&替換成別的,當(dāng)重新登錄成功后調(diào)整會參數(shù)丟失 } Customer customerInfo = (Customer) session.getAttribute("customerInfo"); if(customerInfo==null){//session失效,跳轉(zhuǎn)到獲取微信詳情頁面(授權(quán)) 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成功后跳轉(zhuǎn)的路徑 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(); } } /** * 自動登錄并跳轉(zhuǎn) * @param code * @param appid 公眾號appid * @param appsecret 公眾號appsecret * @param websiteAndProject 請求地址跟工程名,如我當(dāng)前的為http://192.168.2.113/seafood * @param url 自動登錄后跳轉(zhuǎn)路徑 * @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);//根據(jù)Code獲取OpenId //根據(jù)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; } }
到此,微信網(wǎng)頁授權(quán)認證,與session失效自動登錄已經(jīng)完成,如果有問題歡迎在評論區(qū)指出
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。