public class WxGzhUtils {
public static String getCodeByUrl(String appid,String url){
String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
appid+"&redirect_uri="+url+"&response_type=code&scope=SCOPE&state=123#wechat_redirect&connect_redirect=1";
String res[] = requestJson(path);
JSONObject jsonObject = JSON.parseObject(res[0]);
//重定向的url,包含code
String ss = jsonObject.toString();
int i = ss.indexOf("=");
String code = ss.substring(i+1,ss.indexOf("&"));
return code;
}
/**
* 获取openid access_token
* @param appid
* @param secret
* @param code
* @return
*/
public static Map getOpenId(String appid, String secret, String code){
String path = " https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid +
"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
String res[] = requestJson(path);
JSONObject jsonObject = JSON.parseObject(res[0]);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
Map<String,Object> map = new HashMap<>();
map.put("openid",openid);
map.put("access_token",access_token);
return map;
}
/**
* 获取用户信息
* @param openid
* @param access_token
* @return
*/
public static Map getUserInfo(String openid,String access_token){
String path = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
String res[] = requestJson(path);
JSONObject jsonObject = JSON.parseObject(res[0]);
//map对象
Map<String, Object> map =new HashMap<>();
//循环转换
Iterator it =jsonObject.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
map.put(entry.getKey(), entry.getValue());
}
return map;
}
//get请求
private static String[] requestJson(String url) {
return request(url);
}
private static String[] request(String connurl) {
String[] resultStr = new String[]{"", ""};
StringBuilder resultData = new StringBuilder("");
HttpURLConnection conn = null;
try {
URL url = new URL(connurl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setUseCaches(false);
int mTimeout = 10000;
conn.setConnectTimeout(mTimeout);
conn.connect();
int resultCode = conn.getResponseCode();
InputStreamReader in;
if (resultCode == 200) {
in = new InputStreamReader(conn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine;
while ((inputLine = buffer.readLine()) != null) {
resultData.append(inputLine);
resultData.append("\n");
}
buffer.close();
in.close();
}
resultStr[0] = resultData.toString();
resultStr[1] = resultCode + "";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return resultStr;
}
}
公众号 java后端 获取code, openid、unionid, 用户信息
最新推荐文章于 2024-03-13 11:40:31 发布