要获取微信的openid首先需要获取到code值。获取code值请求链接为
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
参数 | 是否必填 | 参数说明 |
appid | 是 | 公众号唯一标识 |
redirect_uri
| 是 |
|
response_type | 是 |
|
scope | 是 |
|
state | 否 |
|
#wechat_redirect | 是 |
|
请求过后回调地址会带上code参数值
然后根据code值查询到openId,一个微信号与一个微信公众号只有唯一的openid
/**
* 获取验证码
* @param appId
* @param appSecret
* @param code
* @return result
*/
public static String getOauth2AccessToken(String appId, String appSecret,
String code) {
System.out.println(appId);
System.out.println(appSecret);
System.out.println(code);
//url获取openid地址
String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("SECRET", appSecret);
requestUrl = requestUrl.replace("CODE", code);
// 提交请求
String result = httpRequest(requestUrl, "GET", null);
System.out.println(result);
return result;
}
private static String httpRequest(String url, String method, String jsonStr) {
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet
.openConnection();
http.setRequestMethod(method); // 必须是get方式请求
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
if (method.equals("POST") && !StringUtil.isEmpty(jsonStr)) {
// POST请求
DataOutputStream out = new DataOutputStream(
http.getOutputStream());
out.write(jsonStr.getBytes("UTF-8"));
out.flush();
out.close();
}
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println(result);
return result;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}