微信二次开发点击菜单openId的获取

                 首先普及一个知识:一个关注的用户对于一个微信公众号是唯一的,也就是说一个用户针对与一个微信公众号是唯一的,对于不同的公众号,同一个微信号具有不同的openId;

                 在微信开发中,我们添加了一个二级菜单并实现一些相应的功能,往往是需要获取自己的openId,本文主要阐述如果通过与微信的交互得到自己的openId ;

                 这里提供一个连接,用于向微信发起请求:(在重定向之前准备好微信的AppId以及token,重定向的URL会被原样返回)

public static String buildAuthorizationUrl(String appid,String redirectUri, String state) {
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
		url = url + "appid=" + appid;
		url = url + "&redirect_uri=" + URIUtil.encodeURIComponent(redirectUri);
		url = url + "&response_type=code";
		url = url + "&scope=snsapi_base";
		if (state != null) {
			url = url + "&state=" + state;
		}
		url = url + "#wechat_redirect";
		return url;
}

            请求成功后,会额外返回一个code以及state参数,其中code参数是唯一的,也就是说一次请求,产生一个code,作为校验的唯一标准,state参数是之前请求中的token参数

                 之后,获取到公众号的APPID以及appscret,通过解析返回的json数据格式,获取到自己个人的openId,之后再进行对业务的操作

public static String oauth2getOpenID(String code, String appid,
String appsecret) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
url = url + "appid=" + appid;
url = url + "&secret=" + appsecret;
url = url + "&code=" + code;
url = url + "&grant_type=authorization_code";
JSONObject jsonObject = JsonUtil.httpsRequest(url, "GET", "");
System.out.println("jsonObject=" + jsonObject);
return jsonObject.getString("openid");
}

  

原文地址:https://www.cnblogs.com/zxx-813/p/7353977.html