JAVA获取微信小程序openid和获取公众号openid,以及通过openid获取用户信息

一,首先说明下这个微信的openid

  为了识别用户,每个用户针对每个公众号会产生一个安全的OpenID,如果需要在多公众号、移动应用之间做用户共通,则需前往微信开放平台,将这些公众号和应用绑定到一个开放平台账号下,绑定后,一个用户虽然对多个公众号和应用有多个不同的OpenID,但他对所有这些同一开放平台账号下的公众号和应用,只有一个UnionID

我用简单自己理解的话来说就是  这个  你在每个公众号 或者小程序  都是在这个小程序或者这个公众号下会有一个openid   你去别的公众号 或者 小程序 这个是会改变的  但是unionid是不管你在哪个小程序或者公众号是唯一不变的。

微信官方提供了 了一个  可以通过用户的openid来获取用户信息,前提是用户必须关注了你的公众号,这个好像要做的话需要关联一个需要三百块钱认证的那个啥来着。这个就先不说了吧,现在我们要说的问题是如何获取openid

二,小程序获取openid

1 1 /** 2 2 * 微信小程序获取openid 3 3 * @author Mr.Lin 4 4 */ 5 5 public class GetOpenIDUtil { 6 6 // 网页授权接口 7 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 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 9 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code"; 1010 public static Map<String,Object> oauth2GetOpenid(String appid,String code,String appsecret) { 1111 String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code); 1212 HttpClient client = null; 1313 Map<String,Object> result =new HashMap<String,Object>(); 1414 try { 1515 client = new DefaultHttpClient(); 1616 HttpGet httpget = new HttpGet(requestUrl); 1717 ResponseHandler<String> responseHandler = new BasicResponseHandler(); 1818 String response = client.execute(httpget, responseHandler); 1919 JSONObject OpenidJSONO=JSONObject.fromObject(response); 2020 String openid =String.valueOf(OpenidJSONO.get("openid")); 2121 String session_key=String.valueOf(OpenidJSONO.get("session_key")); 2222 String unionid=String.valueOf(OpenidJSONO.get("unionid")); 2323 String errcode=String.valueOf(OpenidJSONO.get("errcode")); 2424 String errmsg=String.valueOf(OpenidJSONO.get("errmsg")); 2525 2626 result.put("openid", openid); 2727 result.put("sessionKey", session_key); 2828 result.put("unionid", unionid); 2929 result.put("errcode", errcode); 3030 result.put("errmsg", errmsg); 3131 } catch (Exception e) { 3232 e.printStackTrace(); 3333 } finally { 3434 client.getConnectionManager().shutdown(); 3535 } 3636 return result; 3737 } 3838 } 39 40/** 41 * 小程序换取openid 42 * 43 * @param code 识别得到用户id必须的一个值 得到网页授权凭证和用户id 44 * @return 45 */ 46 @RequestMapping("/get/openid") 47 public @ResponseBody 48 Object GetOpenid(String 你的小程序APPID, String code, String 你的小程序秘钥) { 49 if (code == null || code.length() == 0) { 50 throw new CustomException("code不能为空!"); 51 } 52 return GetOpenIDUtil.oauth2GetOpenid(appid, code, appsecret); 53 54 }这个code的话我这个一般是前端生成比较好,所以你后台的话,把接口给前端,让他那边传个code,

三,获取公众号openid~

1 1 public class HttpGetUtil { 2 2 public static String httpRequestToString(String url, 3 3 Map<String,String> params) { 4 4 String result = null; 5 5 try { 6 6 InputStream is = httpRequestToStream(url, params); 7 7 BufferedReader in = new BufferedReader(new InputStreamReader(is, 8 8 "UTF-8")); 9 9 StringBuffer buffer = new StringBuffer(); 1010 String line = ""; 1111 while ((line = in.readLine()) != null) { 1212 buffer.append(line); 1313 } 1414 result = buffer.toString(); 1515 } catch (Exception e) { 1616 return null; 1717 } 1818 return result; 1919 } 2020 2121 private static InputStream httpRequestToStream(String url, 2222 Map<String, String> params) { 2323 InputStream is = null; 2424 try { 2525 String parameters = ""; 2626 boolean hasParams = false; 2727 for(String key : params.keySet()){ 2828 String value = null; 2929 try { 3030 value = URLEncoder.encode(params.get(key), "UTF-8"); 3131 } catch (UnsupportedEncodingException e) { 3232 e.printStackTrace(); 3333 } 3434 parameters += key +"="+ value +"&"; 3535 hasParams = true; 3636 } 3737 if(hasParams){ 3838 parameters = parameters.substring(0, parameters.length()-1); 3939 } 4040 4141 4242 url += "?"+ parameters; 4343 4444 URL u = new URL(url); 4545 HttpURLConnection conn = (HttpURLConnection) u.openConnection(); 4646 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 4747 conn.setRequestProperty("Accept-Charset", "UTF-8"); 4848 conn.setRequestProperty("contentType", "utf-8"); 4949 conn.setConnectTimeout(50000); 5050 conn.setReadTimeout(50000); 5151 conn.setDoInput(true); 5252 //设置请求方式,默认为GET 5353 conn.setRequestMethod("GET"); 5454 5555 5656 is = conn.getInputStream(); 5757 } catch (UnsupportedEncodingException e) { 5858 e.printStackTrace(); 5959 } catch (MalformedURLException e) { 6060 e.printStackTrace(); 6161 } catch (IOException e) { 6262 e.printStackTrace(); 6363 } 6464 return is; 6565 } 6666 6767 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"; 6868 public static String getCodeRequest(String appid){ 6969 HttpClient client = null; 7070 String result = null; 7171 String appId = appid; 7272 String REDIRECT_URI= "";//回调请求地址 7373 String SCOPE="snsapi_base"; 7474 7575 GetCodeRequest1 = GetCodeRequest1.replace("APPID", urlEnodeUTF8(appId)); 7676 GetCodeRequest1 = GetCodeRequest1.replace("REDIRECT_URI",urlEnodeUTF8(REDIRECT_URI)); 7777 GetCodeRequest1 = GetCodeRequest1.replace("SCOPE", SCOPE); 7878 result = GetCodeRequest1; 7979 8080 System.out.println(REDIRECT_URI); 8181 8282 return result; 8383 } 8484 public static String urlEnodeUTF8(String str){ 8585 String result = str; 8686 try { 8787 result = URLEncoder.encode(str,"UTF-8"); 8888 } catch (Exception e) { 8989 e.printStackTrace(); 9090 } 9191 return result; 9292 } 9393 } 94 95@RequestMapping("/get/gzh/openid") 96 public @ResponseBody 97 String GetGZHOpenid(HttpServletRequest request, HttpServletResponse response) throws IOException { 98 99 100 String code = request.getParameter("code");//获取code 101 Map params = new HashMap(); 102 params.put("secret", 你的公众号秘钥); 103 params.put("appid", 你的公众号APPID); 104 params.put("grant_type", "authorization_code"); 105 params.put("code", code); 106 String result = HttpGetUtil.httpRequestToString( 107 "https://api.weixin.qq.com/sns/oauth2/access_token", params); 108 JSONObject jsonObject = JSONObject.fromObject(result); 109 110 String openid = jsonObject.get("openid").toString(); 111 LOGGER.debug("code------" + code); 112 LOGGER.debug("得到的openid为:" + openid); 113 return openid; 114 115 }

四,通过微信获取的openid来获取用户信息

1 1 /** 2 2 * 获取accessToken 3 3 * 4 4 */ 5 5 public class GetAccessTokenUtil { 6 6 // 网页授权接口 7 7 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 8 8 public static Map<String, String> getAccessToken(String appid, String appsecret) { 9 9 String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret); 1010 HttpClient client = null; 1111 Map<String, String> result = new HashMap<String, String>(); 1212 String accessToken = null; 1313 try { 1414 client = new DefaultHttpClient(); 1515 HttpGet httpget = new HttpGet(requestUrl); 1616 ResponseHandler<String> responseHandler = new BasicResponseHandler(); 1717 String response = client.execute(httpget, responseHandler); 1818 JSONObject OpenidJSONO = JSONObject.fromObject(response); 1919 accessToken = String.valueOf(OpenidJSONO.get("access_token")); 2020 result.put("accessToken", accessToken); 2121 } catch (Exception e) { 2222 e.printStackTrace(); 2323 } finally { 2424 client.getConnectionManager().shutdown(); 2525 } 2626 return result; 2727 } 2828 } 29 30//通过openid获取用户的信息,这个看你需要获取用户的哪些信息,// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839 这个是微信官方的获取unionid机制 用户信息public class GetBasicInformation { 31 // 网页授权接口 32 public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; 33 34 public static Map<String, String> getAccessToken(String access_token, String openid) { 35 String requestUrl = GetPageAccessTokenUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid); 36 HttpClient client = null; 37 Map<String, String> result = new HashMap<String, String>(); 38 try { 39 client = new DefaultHttpClient(); 40 HttpGet httpget = new HttpGet(requestUrl); 41 ResponseHandler<String> responseHandler = new BasicResponseHandler(); 42 String response = client.execute(httpget, responseHandler); 43 JSONObject OpenidJSONO = JSONObject.fromObject(response); 44 45// String accessToken = String.valueOf(OpenidJSONO.get("access_token")); 46 String subscribe = String.valueOf(OpenidJSONO.get("subscribe")); 47 String nickname = new String(String.valueOf(OpenidJSONO.get("nickname")).getBytes("ISO8859-1"),"UTF-8"); 48 String sex = String.valueOf(OpenidJSONO.get("sex")); 49 String language = String.valueOf(OpenidJSONO.get("language")); 50 String city = new String(String.valueOf(OpenidJSONO.get("city")).getBytes("ISO8859-1"),"UTF-8"); 51 String province = new String(String.valueOf(OpenidJSONO.get("province")).getBytes("ISO8859-1"),"UTF-8"); 52 String country = new String(String.valueOf(OpenidJSONO.get("country")).getBytes("ISO8859-1"),"UTF-8"); 53 String headimgurl = String.valueOf(OpenidJSONO.get("headimgurl")); 54 String subscribeTime = String.valueOf(OpenidJSONO.get("subscribe_time")); 55 String unionid = String.valueOf(OpenidJSONO.get("unionid")); 56// String accessToken =new String(String.valueOf(OpenidJSONO.get("access_token")).getBytes("ISO8859-1"),"UTF-8"); 57// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 58// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 59// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 60// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 61// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 62// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 63// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 64// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 65// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 66// String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8"); 67 68// String openid = String.valueOf(OpenidJSONO.get("openid")); 69// result.put("accessToken", accessToken); 70 result.put("subscribe", subscribe); 71 result.put("nickname", nickname); 72 result.put("sex", sex); 73 result.put("language", language); 74 result.put("city", city); 75 result.put("province", province); 76 result.put("country", country); 77 result.put("headimgurl", headimgurl); 78 result.put("subscribeTime", subscribeTime); 79 result.put("unionid", unionid); 80 81// System.out.println(accessToken+"==================="+unionid); 82 } catch (Exception e) { 83 e.printStackTrace(); 84 } finally { 85 client.getConnectionManager().shutdown(); 86 } 87 return result; 88 } 89} 90 91 1 /** 92 2 * 微信公众号获取微信unionid和其他个人信息 需要关注公众号 93 3 * 94 4 * @param openid 95 5 * @return 96 6 */ 97 7 @RequestMapping("/basic/Information") 98 8 public @ResponseBody 99 9 Map basicInformation(String openid) { 10010 //得到access_token 10111 String accessToken = GetAccessTokenUtil.getAccessToken(你的公众号APPID, 你的公众号APPID对应的秘钥).get("accessToken"); 10212 LOGGER.debug("accessToken------" + accessToken); 10313 return GetBasicInformation.getAccessToken(accessToken, openid); 10414 }

总结:这个就是微信小程序和微信公众号获取openid  以及通过openid获取unionid以及用户信息的代码,微信开发文档上面看感觉功力不深厚是很难看懂的,这个我也是通过网上或者同事慢慢总结出来的。  请大家多多指教,谢谢!

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

小程序静默登录与维护自定义登录态

1.背景在小程序中,openid是一个用户对于一个小程序/公众号的标识,开发者可以通过这个标识识别出用户,就如同你的身份证一样。2.什么是静默登录?在普通的应用中,用户通过表单验证登录建立用户体系,这种常见的登录方式一般是通过登录页面表单进行登录,对用户来说是有感的。在小程序中,由于是基于微信,可以通过微信官方提供的API能力,使我们能够无感知得获取

PHP微信小程序支付——签名错误

!(https://static.oschina.net/uploads/space/2018/0509/141657_Tqix_3477605.png)先分清几个概念:微信公众平台、微信开放平台、微信商户平台1.微信公众平台、微信开放平台、微信商户平台是三个不同的平台2.微信公众平台:用于公众号、小程序等等的设置平台,包括APPID、APP