Java微信开发基本数据的获取
时间:2020-05-04 19:37:01
收藏:0
阅读:85
本文主要实例JAVA获取微信小程序openid和获取公众号openid,以及通过openid获取用户信息!
微信官网文档链接:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
前端有个wx.login({
success: res =>{
res.code //直接可以获取到code的默认每五分钟一次.
一,微信的openid
为了识别用户,每个用户针对每个公众号会产生一个安全的OpenID,如果需要在多公众号、移动应用之间做用户共通,则需前往微信开放平台,将这些公众号和应用绑定到一个开放平台账号下,绑定后,一个用户虽然对多个公众号和应用有多个不同的OpenID,但他对所有这些同一开放平台账号下的公众号和应用,只有一个UnionID.
简单点说:你在每个公众号或者小程序 都是在这个小程序或者这个公众号下会有一个openid 你去别的公众号或者小程序这个是会改变的 但是unionid是不管你在哪个小程序或者公众号是唯一不变的。
微信官方提供了了一个可以通过用户的openid来获取用户信息,前提是用户必须关注了你的公众号,这个就先不说了吧,现在我们要说的问题是如何获取openid
二,小程序获取openid
1 /** 2 * 微信小程序获取openid 3 * 4 */ 5 public class GetOpenIDUtil { 6 // 网页授权接口 7 // public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";// 8 // public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; 9 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; 10 public static Map<String,Object> oauth2GetOpenid(String appid,String code,String appsecret) { 11 String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code); 12 HttpClient client = null; 13 Map<String,Object> result =new HashMap<String,Object>(); 14 try { 15 client = new DefaultHttpClient(); 16 HttpGet httpget = new HttpGet(requestUrl); 17 ResponseHandler<String> responseHandler = new BasicResponseHandler(); 18 String response = client.execute(httpget, responseHandler); 19 JSONObject OpenidJSONO=JSONObject.fromObject(response); 20 String openid =String.valueOf(OpenidJSONO.get("openid")); 21 String session_key=String.valueOf(OpenidJSONO.get("session_key")); 22 String unionid=String.valueOf(OpenidJSONO.get("unionid")); 23 String errcode=String.valueOf(OpenidJSONO.get("errcode")); 24 String errmsg=String.valueOf(OpenidJSONO.get("errmsg")); 25 26 result.put("openid", openid); 27 result.put("sessionKey", session_key); 28 result.put("unionid", unionid); 29 result.put("errcode", errcode); 30 result.put("errmsg", errmsg); 31 } catch (Exception e) { 32 e.printStackTrace(); 33 } finally { 34 client.getConnectionManager().shutdown(); 35 } 36 return result; 37 } 38 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/** * 小程序换取openid * * @param code 识别得到用户id必须的一个值 得到网页授权凭证和用户id * @return */ @RequestMapping ( "/get/openid" ) public @ResponseBody Object GetOpenid(String 你的小程序APPID, String code, String 你的小程序秘钥) { if (code == null || code.length() == 0 ) { throw new CustomException( "code不能为空!" ); } return GetOpenIDUtil.oauth2GetOpenid(appid, code, appsecret); }<br>这个code的话我这个一般是前端生成比较好,所以你后台的话,把接口给前端,让他那边传个code, |
三,获取公众号openid
1 public class HttpGetUtil { 2 public static String httpRequestToString(String url, 3 Map<String,String> params) { 4 String result = null; 5 try { 6 InputStream is = httpRequestToStream(url, params); 7 BufferedReader in = new BufferedReader(new InputStreamReader(is, 8 "UTF-8")); 9 StringBuffer buffer = new StringBuffer(); 10 String line = ""; 11 while ((line = in.readLine()) != null) { 12 buffer.append(line); 13 } 14 result = buffer.toString(); 15 } catch (Exception e) { 16 return null; 17 } 18 return result; 19 } 20 21 private static InputStream httpRequestToStream(String url, 22 Map<String, String> params) { 23 InputStream is = null; 24 try { 25 String parameters = ""; 26 boolean hasParams = false; 27 for(String key : params.keySet()){ 28 String value = null; 29 try { 30 value = URLEncoder.encode(params.get(key), "UTF-8"); 31 } catch (UnsupportedEncodingException e) { 32 e.printStackTrace(); 33 } 34 parameters += key +"="+ value +"&"; 35 hasParams = true; 36 } 37 if(hasParams){ 38 parameters = parameters.substring(0, parameters.length()-1); 39 } 40 41 42 url += "?"+ parameters; 43 44 URL u = new URL(url); 45 HttpURLConnection conn = (HttpURLConnection) u.openConnection(); 46 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 47 conn.setRequestProperty("Accept-Charset", "UTF-8"); 48 conn.setRequestProperty("contentType", "utf-8"); 49 conn.setConnectTimeout(50000); 50 conn.setReadTimeout(50000); 51 conn.setDoInput(true); 52 //设置请求方式,默认为GET 53 conn.setRequestMethod("GET"); 54 55 56 is = conn.getInputStream(); 57 } catch (UnsupportedEncodingException e) { 58 e.printStackTrace(); 59 } catch (MalformedURLException e) { 60 e.printStackTrace(); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 } 64 return is; 65 } 66 67 public static String GetCodeRequest1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect"; 68 public static String getCodeRequest(String appid){ 69 HttpClient client = null; 70 String result = null; 71 String appId = appid; 72 String REDIRECT_URI= "";//回调请求地址 73 String SCOPE="snsapi_base"; 74 75 GetCodeRequest1 = GetCodeRequest1.replace("APPID", urlEnodeUTF8(appId)); 76 GetCodeRequest1 = GetCodeRequest1.replace("REDIRECT_URI",urlEnodeUTF8(REDIRECT_URI)); 77 GetCodeRequest1 = GetCodeRequest1.replace("SCOPE", SCOPE); 78 result = GetCodeRequest1; 79 80 System.out.println(REDIRECT_URI); 81 82 return result; 83 } 84 public static String urlEnodeUTF8(String str){ 85 String result = str; 86 try { 87 result = URLEncoder.encode(str,"UTF-8"); 88 } catch (Exception e) { 89 e.printStackTrace(); 90 } 91 return result; 92 } 93 }
@RequestMapping("/get/gzh/openid") public @ResponseBody String GetGZHOpenid(HttpServletRequest request, HttpServletResponse response) throws IOException { String code = request.getParameter("code");//获取code Map params = new HashMap(); params.put("secret", 你的公众号秘钥); params.put("appid", 你的公众号APPID); params.put("grant_type", "authorization_code"); params.put("code", code); String result = HttpGetUtil.httpRequestToString( "https://api.weixin.qq.com/sns/oauth2/access_token", params); JSONObject jsonObject = JSONObject.fromObject(result); String openid = jsonObject.get("openid").toString(); LOGGER.debug("code------" + code); LOGGER.debug("得到的openid为:" + openid); return openid; }
四,通过微信获取的openid来获取用户信息
1 /** 2 * 获取accessToken 3 * 4 */ 5 public class GetAccessTokenUtil { 6 // 网页授权接口 7 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 8 public static Map<String, String> getAccessToken(String appid, String appsecret) { 9 String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret); 10 HttpClient client = null; 11 Map<String, String> result = new HashMap<String, String>(); 12 String accessToken = null; 13 try { 14 client = new DefaultHttpClient(); 15 HttpGet httpget = new HttpGet(requestUrl); 16 ResponseHandler<String> responseHandler = new BasicResponseHandler(); 17 String response = client.execute(httpget, responseHandler); 18 JSONObject OpenidJSONO = JSONObject.fromObject(response); 19 accessToken = String.valueOf(OpenidJSONO.get("access_token")); 20 result.put("accessToken", accessToken); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } finally { 24 client.getConnectionManager().shutdown(); 25 } 26 return result; 27 } 28 }
public class GetBasicInformation { // 网页授权接口 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; public static Map<String, String> getAccessToken(String access_token, String openid) { String requestUrl = GetPageAccessTokenUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid); HttpClient client = null; Map<String, String> result = new HashMap<String, String>(); try { client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpget, responseHandler); JSONObject OpenidJSONO = JSONObject.fromObject(response); // String accessToken = String.valueOf(OpenidJSONO.get("access_token")); String subscribe = String.valueOf(OpenidJSONO.get("subscribe")); String nickname = new String(String.valueOf(OpenidJSONO.get("nickname")).getBytes("ISO8859-1"),"UTF-8"); String sex = String.valueOf(OpenidJSONO.get("sex")); String language = String.valueOf(OpenidJSONO.get("language")); String city = new String(String.valueOf(OpenidJSONO.get("city")).getBytes("ISO8859-1"),"UTF-8"); String province = new String(String.valueOf(OpenidJSONO.get("province")).getBytes("ISO8859-1"),"UTF-8"); String country = new String(String.valueOf(OpenidJSONO.get("country")).getBytes("ISO8859-1"),"UTF-8"); String headimgurl = String.valueOf(OpenidJSONO.get("headimgurl")); String subscribeTime = String.valueOf(OpenidJSONO.get("subscribe_time")); String unionid = String.valueOf(OpenidJSONO.get("unionid")); // String openid = String.valueOf(OpenidJSONO.get("openid")); // result.put("accessToken", accessToken); result.put("subscribe", subscribe); result.put("nickname", nickname); result.put("sex", sex); result.put("language", language); result.put("city", city); result.put("province", province); result.put("country", country); result.put("headimgurl", headimgurl); result.put("subscribeTime", subscribeTime); result.put("unionid", unionid); // System.out.println(accessToken+"==================="+unionid); } catch (Exception e) { e.printStackTrace(); } finally { client.getConnectionManager().shutdown(); } return result; } }
1 /** 2 * 微信公众号获取微信unionid和其他个人信息 需要关注公众号 3 * 4 * @param openid 5 * @return 6 */ 7 @RequestMapping("/basic/Information") 8 public @ResponseBody 9 Map basicInformation(String openid) { 10 //得到access_token 11 String accessToken = GetAccessTokenUtil.getAccessToken(你的公众号APPID, 你的公众号APPID对应的秘钥).get("accessToken"); 12 LOGGER.debug("accessToken------" + accessToken); 13 return GetBasicInformation.getAccessToken(accessToken, openid); 14 }
评论(0)