微信公眾號開發(5)---使用開源組件開發公眾號OAuth2.0網頁授權授權登錄
阿新 • • 發佈:2018-08-26
esp 開發 color use oauth2 url rec wired 公眾號
搞清微信公眾號授權登錄的步驟步驟,我們的開發就完成了一大步
獻上github 地址: https://github.com/Wechat-Group/weixin-java-tools/wiki/MP_OAuth2%E7%BD%91%E9%A1%B5%E6%8E%88%E6%9D%83
第一步:需要在微信後臺配置:註意,只填寫自己的域名
2.配置完畢後,構建網頁授權url,配置重定向地址
3.當用戶同意授權後,會回調所設置的url並把authorization code傳過來
4, 拿到這個code 獲得access token,與openid
5.拿到之後,進行微信請求就可以拿到信息了
@Autowired private WxMpInMemoryConfigStorage config; @Autowired private WxMpService wxMpService; @RequestMapping("/WxOauthLogin") public void wxxLogin(HttpServletResponse response) throws IOException { //我們可以將config配置在xml文件中管理 config.setAppId("wx426aad126775582c"); config.setSecret("d79b69215c50cee0c848415eb34c659a"); wxMpService.setWxMpConfigStorage(config); String redirectURI="http://ea40c4fc.ngrok.io/Wxredirect"; /** * 構造微信重定向地址 * url不用我們進行urlencode * */ String url=wxMpService.oauth2buildAuthorizationUrl(redirectURI, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null); System.out.println("重定向地址------->"+url); response.sendRedirect(url); } //**在用戶點擊授權後會觸發下面的方法,即重定向的地址,必須在微信中打開哦**// @RequestMapping("/Wxredirect") public void WxRedirect(String code,HttpServletResponse response) throws WxErrorException, IOException { System.out.println("已經重定向到我這裏了---success"); System.out.println("code--->"+code); /*當用戶同意授權後,會回調所設置的url並把authorization code傳過來 * ,然後用這個code獲得access token,其中也包含用戶的openid等信息 */ WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code); /* * 獲取用戶的基本信息 */ WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null); System.out.print("用戶的基本信息"+wxMpUser); /* * 業務邏輯處理,自己看自己的業務 */ @Cleanup PrintWriter writer =response.getWriter(); writer.write(wxMpUser.toString()); }
微信公眾號開發(5)---使用開源組件開發公眾號OAuth2.0網頁授權授權登錄