spring boot 微信网页授权的实现

    技术2022-07-10  98

    spring boot 微信网页授权的实现

    按照官方文档步骤,网页授权分为四步。这里不再累述,官方文档传送门:微信网页授权

    1 - 获取用户授权,获取code

    @RequestMapping(value = "/login", method = RequestMethod.GET) public void wxLogin(HttpServletResponse response) throws IOException { //重定向页面 String redirectUrl = "http://weauth.tisnz.cn/api/callBack"; // String redirectUrl = "http://127.0.0.1:8801/api/callBack"; //请求用户授权 String url = "https://open.weixin.qq.com/connect/oauth2/authorize" + "?appid=" + appId + "&redirect_uri=" + URLEncoder.encode(redirectUrl, "UTF-8") + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STAE"+ "#wechat_redirect"; //重定向 // String URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3f7beb7a7abe0e63&redirect_uri=https://platform.tisnz.cn/login?redirect=/dashboard&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; response.sendRedirect(url); }

    需要注意的是redirectUrl 地址为/claback你需要操作的接口

    2-通过code获取token,拉取用户信息(公众号不能获取用户的电话)

    @RequestMapping(value = "/callBack", method = RequestMethod.GET) public void wxCallBack(HttpServletRequest request, HttpServletResponse response, @PathParam("code") String code) throws IOException { HttpSession session = request.getSession(); log.info("{ 用户同意后获取code:/callBack }"+code); // String code = request.getParameter("code"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //获取access_token String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"; //返回结果的json对象 JSONObject resultObject = HttpClientUtil.doGetJson(url); log.info("{ resultObject }"+resultObject); //请求获取userInfo String infoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=" + resultObject.getString("access_token") + "&openid=" + resultObject.getString("openid") + "&lang=zh_CN"; JSONObject resultInfo = HttpClientUtil.doGetJson(infoUrl); System.out.println("resultInfo: "+resultInfo.toJSONString()); String openid = resultObject.getString("openid"); log.info("{ openid }"+openid); User user = userService.selectById(openid); if( user == null ){ User user1 = new User(); user1.setId(openid); user1.setAddTime(sdf.format(new Date())); userService.insertUser(user1); String token = tokenService.getToken(user1); Cookie cookie = new Cookie("token",token); //cookie共享 cookie.setPath("/"); response.addCookie(cookie); // session.setAttribute("user",user); } else { String token = tokenService.getToken(user); Cookie cookie = new Cookie("token",token); cookie.setPath("/"); response.addCookie(cookie); } log.info("{resultObject}: " + resultObject.toJSONString()); }

    3-将URL解析为JSON工具类

    package com.detecation.common.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = 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 httpGet = new HttpGet(uri); // 执行请求 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(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } // url转换JSON public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException { JSONObject jsonObject =null; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet =new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity =response.getEntity(); if(entity!=null) { //把返回的结果转换为JSON对象 String result =EntityUtils.toString(entity, "UTF-8"); jsonObject = JSON.parseObject(result); } return jsonObject; } public static String doPost(String url, Map<String, 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; } }

    收工

    你以为我会求你?

    Processed: 0.018, SQL: 12