springboot 微信登入
生活随笔
收集整理的這篇文章主要介紹了
springboot 微信登入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
準備工作
https://open.weixin.qq.com
參考文檔: https://open.weixin.qq.com/cgi-bin/showdocument?
action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=e547653f995d8f402704d5cb2945177dc8aa4e7e&la
ng=zh_CN
application.properties
# 微信開放平臺 appidwx.open.app_id=wxed9954c01bb89b47 # 微信開放平臺 appsecret wx.open.app_secret=a7482517235173ddb4083788de60b90e # 微信開放平臺 重定向url wx.open.redirect_url=http://localhost:8160/ucenter/wx/callback獲取配置文件
@Component //@PropertySource("classpath:application.properties") public class ConstantPropertiesUtil implements InitializingBean { @Value("${wx.open.app_id}") private String appId; @Value("${wx.open.app_secret}") private String appSecret;@Value("${wx.open.redirect_url}") private String redirectUrl;public static String WX_OPEN_APP_ID;public static String WX_OPEN_APP_SECRET;public static String WX_OPEN_REDIRECT_URL;@Overridepublic void afterPropertiesSet() throws Exception {WX_OPEN_APP_ID = appId;WX_OPEN_APP_SECRET = appSecret;WX_OPEN_REDIRECT_URL = redirectUrl;}} 前后端分離 @CrossOrigin @Controller//注意這里沒有配置 @RestController @RequestMapping("/ucenter/wx") public class WxApiController {@Autowiredprivate UcenterMemberService ucenterMemberService;@GetMapping("login")public String genQrConnect(HttpSession session) {// 微信開放平臺授權baseUrl,%s占位符String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +"?appid=%s" +"&redirect_uri=%s" +"&response_type=code" +"&scope=snsapi_login" +"&state=%s" +"#wechat_redirect";// 回調地址String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //獲取業務服務器重定向地址try {redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //redirectUrl編碼} catch (UnsupportedEncodingException e) {throw new zdyException(20001, e.getMessage());}//生成二維碼,返回跳轉路勁/callbackString qrcodeUrl = String.format(//填寫%s字符串baseUrl,ConstantPropertiesUtil.WX_OPEN_APP_ID,redirectUrl,"atguigu");return "redirect:"+qrcodeUrl; }//重定向到/callback@GetMapping("/callback")//通過 code 獲取access_tokenpublic String vcallback(String code,String state) throws Exception {String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +"?appid=%s" +"&secret=%s" +"&code=%s" +"&grant_type=authorization_code";String accessTokenUrl = String.format(baseAccessTokenUrl,ConstantPropertiesUtil.WX_OPEN_APP_ID,ConstantPropertiesUtil.WX_OPEN_APP_SECRET,code);String result = HttpClientUtils.get(accessTokenUrl);//第二次請求使用httpclien參數訪問//解析json字符串Gson gson = new Gson();HashMap map = gson.fromJson(result, HashMap.class);String accessToken = (String)map.get("access_token");String openid = (String)map.get("openid"); UcenterMember ucenterMember=ucenterMemberService.selectopenid(openid); if (ucenterMember==null){//訪問微信的資源服務器,獲取用戶信息String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=%s" + "&openid=%s";String userInfoUrl=String.format(baseUserInfoUrl, accessToken, openid);String resultUserInfo = HttpClientUtils.get(userInfoUrl);//解析jsonHashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);String nickname = (String)mapUserInfo.get("nickname");String headimgurl = (String)mapUserInfo.get("headimgurl");//向數據庫中插入一條記錄ucenterMember.setNickname(nickname);ucenterMember.setOpenid(openid);ucenterMember.setAvatar(headimgurl);ucenterMemberService.save(ucenterMember);}String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());return "redirect:http://localhost:3000?jwtToken="+jwtToken;} }第二次請求使用httpclien參數訪問
public class HttpClientUtils {public static final int connTimeout=10000;public static final int readTimeout=10000;public static final String charset="UTF-8";private static HttpClient client = null;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build();}public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);}public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);}public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String get(String url) throws Exception {return get(url, charset, null, null);}public static String get(String url, String charset) throws Exception {return get(url, charset, connTimeout, readTimeout);}/*** 發送一個 Post 請求, 使用指定的字符集編碼.** @param url* @param body RequestBody* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3* @param charset 編碼* @param connTimeout 建立鏈接超時時間,毫秒.* @param readTimeout 響應超時時間,毫秒.* @return ResponseBody, 使用指定的字符集編碼.* @throws ConnectTimeoutException 建立鏈接超時異常* @throws SocketTimeoutException 響應超時* @throws Exception*/public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);String result = "";try {if (StringUtils.isNotBlank(body)) {HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));post.setEntity(entity);}// 設置參數Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res;if (url.startsWith("https")) {// 執行 Https 請求.client = createSSLInsecureClient();res = client.execute(post);} else {// 執行 Http 請求.client = HttpClientUtils.client;res = client.execute(post);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 提交form表單** @param url* @param params* @param connTimeout* @param readTimeout* @return* @throws ConnectTimeoutException* @throws SocketTimeoutException* @throws Exception*/public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List<NameValuePair> formParams = new ArrayList<NameValuePair>();Set<Entry<String, String>> entrySet = params.entrySet();for (Entry<String, String> entry : entrySet) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);post.setEntity(entity);}if (headers != null && !headers.isEmpty()) {for (Entry<String, String> entry : headers.entrySet()) {post.addHeader(entry.getKey(), entry.getValue());}}// 設置參數Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 執行 Https 請求.client = createSSLInsecureClient();res = client.execute(post);} else {// 執行 Http 請求.client = HttpClientUtils.client;res = client.execute(post);}return IOUtils.toString(res.getEntity().getContent(), "UTF-8");} finally {post.releaseConnection();if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}}/*** 發送一個 GET 請求** @param url* @param charset* @param connTimeout 建立鏈接超時時間,毫秒.* @param readTimeout 響應超時時間,毫秒.* @return* @throws ConnectTimeoutException 建立鏈接超時* @throws SocketTimeoutException 響應超時* @throws Exception*/public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)throws ConnectTimeoutException,SocketTimeoutException, Exception {HttpClient client = null;HttpGet get = new HttpGet(url);String result = "";try {// 設置參數Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}get.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 執行 Https 請求.client = createSSLInsecureClient();res = client.execute(get);} else {// 執行 Http 請求.client = HttpClientUtils.client;res = client.execute(get);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {get.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 從 response 里獲取 charset** @param ressponse* @return*/@SuppressWarnings("unused")private static String getCharsetFromResponse(HttpResponse ressponse) {// Content-Type:text/html; charset=GBKif (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {String contentType = ressponse.getEntity().getContentType().getValue();if (contentType.contains("charset=")) {return contentType.substring(contentType.indexOf("charset=") + 8);}}return null;}/*** 創建 SSL連接* @return* @throws GeneralSecurityException*/private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}@Overridepublic void verify(String host, SSLSocket ssl)throws IOException {}@Overridepublic void verify(String host, X509Certificate cert)throws SSLException {}@Overridepublic void verify(String host, String[] cns,String[] subjectAlts) throws SSLException {}});return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (GeneralSecurityException e) {throw e;}}public static void main(String[] args) {try {String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);//String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");/*Map<String,String> map = new HashMap<String,String>();map.put("name", "111");map.put("page", "222");String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/System.out.println(str);} catch (ConnectTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SocketTimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}總結
以上是生活随笔為你收集整理的springboot 微信登入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TextTranslatorOpenSo
- 下一篇: SimCSE论文及源码解读